text stringlengths 1 1.05M |
|---|
#include "arguments.hpp"
#include "builtin/block_environment.hpp"
#include "builtin/class.hpp"
#include "builtin/compiled_code.hpp"
#include "builtin/constant_scope.hpp"
#include "builtin/exception.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/jit.hpp"
#include "builtin/location.hpp"
#include "builtin/native_method.hpp"
#include "builtin/object.hpp"
#include "builtin/symbol.hpp"
#include "builtin/system.hpp"
#include "builtin/tuple.hpp"
#include "builtin/variable_scope.hpp"
#include "call_frame.hpp"
#include "configuration.hpp"
#include "instruments/tooling.hpp"
#include "object_utils.hpp"
#include "on_stack.hpp"
#include "ontology.hpp"
#ifdef ENABLE_LLVM
#include "llvm/state.hpp"
#endif
#include <iostream>
namespace rubinius {
void BlockEnvironment::init(STATE) {
GO(blokenv).set(ontology::new_class(state, "BlockEnvironment", G(object),
G(rubinius)));
G(blokenv)->set_object_type(state, BlockEnvironmentType);
}
void BlockEnvironment::bootstrap_methods(STATE) {
GCTokenImpl gct;
System::attach_primitive(state, gct,
G(blokenv), false,
state->symbol("call_under"),
state->symbol("block_call_under"));
}
void BlockEnvironment::lock_scope(STATE) {
if(scope_ && !scope_->nil_p()) {
scope_->set_locked(state);
}
if(top_scope_ && !top_scope_->nil_p()) {
top_scope_->set_locked(state);
}
}
BlockEnvironment* BlockEnvironment::allocate(STATE) {
BlockEnvironment* env = state->new_object<BlockEnvironment>(G(blokenv));
return env;
}
MachineCode* BlockEnvironment::machine_code(STATE, GCToken gct, CallFrame* call_frame) {
return compiled_code_->internalize(state, gct, call_frame);
}
Object* BlockEnvironment::invoke(STATE, CallFrame* previous,
BlockEnvironment* env, Arguments& args,
BlockInvocation& invocation)
{
MachineCode* mcode = env->compiled_code_->machine_code();
if(!mcode) {
OnStack<3> os(state, env, args.recv_location(), args.block_location());
OnStack<3> iv(state, invocation.self, invocation.constant_scope, invocation.module);
VariableRootBuffer vrb(state->vm()->current_root_buffers(),
&args.arguments_location(), args.total());
GCTokenImpl gct;
mcode = env->machine_code(state, gct, previous);
if(!mcode) {
Exception::internal_error(state, previous, "invalid bytecode method");
return 0;
}
}
#ifdef ENABLE_LLVM
if(executor ptr = mcode->unspecialized) {
return (*((BlockExecutor)ptr))(state, previous, env, args, invocation);
}
#endif
return execute_interpreter(state, previous, env, args, invocation);
}
// TODO: this is a quick hack to process block arguments in 1.9.
class GenericArguments {
public:
static bool call(STATE, CallFrame* call_frame,
MachineCode* mcode, StackVariables* scope,
Arguments& args, int flags)
{
/* There are 5 types of arguments, illustrated here:
* m(a, b=1, *c, d, e: 2)
*
* where:
* a is a head (pre optional/splat) fixed position argument
* b is an optional argument
* c is a rest argument
* d is a post (optional/splat) argument
* e is a keyword argument, which may be required (having no default
* value), optional, or keyword rest argument (**kw).
*
* The arity checking above ensures that we have at least one argument
* on the stack for each fixed position argument (ie arguments a and d
* above).
*
* We assign the arguments in the following order: first the fixed
* arguments (head and post) and possibly the keyword argument, then the
* optional arguments, and the remainder (if any) are combined in an
* array for the rest argument.
*
* We assign values from the sender's side to local variables on the
* receiver's side. Which values to assign are computed as follows:
*
* sender indexes (arguments)
* -v-v-v-v-v-v-v-v-v-v-v-v--
*
* 0...H H...H+ON H+ON...N-P-K N-P-K...N-K N-K
* | | | | |
* H O R P K
* | | | | |
* 0...H H...H+O RI PI...PI+P KI
*
* -^-^-^-^-^-^-^-^-^-^-^-^-
* receiver indexes (locals)
*
* where:
*
* arguments passed by sender
* --------------------------
* N : total number of arguments passed
* H* : number of head arguments
* E : number of extra arguments
* ON : number or arguments assigned to optional parameters
* RN : number of arguments assigned to the rest argument
* P* : number of post arguments
* K : number of keyword arguments passed, 1 if the last argument is
* a Hash or if #to_hash returns a Hash, 0 otherwise
* HL : maximum number of head arguments passed
* PM : post arguments missing when N < M
*
* parameters defined by receiver
* ------------------------------
* T : total number of parameters
* M : number of head + post parameters
* H* : number of head parameters
* O : number of optional parameters
* RP : true if a rest parameter is defined, false otherwise
* RI : index of rest parameter if RP is true, else -1
* P* : number of post parameters
* PI : index of the first post parameter
* KP : true if a keyword parameter is defined, false otherwise
* KA : true if the keyword argument was extracted from the passed
* argument leaving a remaining value
* KI : index of keyword rest parameter
*
* (*) The values of H and P are fixed and they represent the same
* values at both the sender and receiver, so they are named the same.
*
* formulas
* --------
* K = KP && !KA && N > M ? 1 : 0
* E = N - M - K
* O = T - M - (keywords ? 1 : 0)
* ON = (X = MIN(O, E)) > 0 ? X : 0
* RN = RP && (X = E - ON) > 0 ? X : 0
* PI = H + O + (RP ? 1 : 0)
* KI = RP ? T : T - 1
* HL = (H - N) > 0 ? MIN(N, H - N) : H
* PM = N - H > 0 ? P - (N - H) : P
*
*/
native_int N = args.total();
const native_int T = mcode->total_args;
const native_int M = mcode->required_args;
const native_int O = T - M - (mcode->keywords ? 1 : 0);
/* TODO: Clean up usage to uniformly refer to 'splat' as N arguments
* passed from sender at a single position and 'rest' as N arguments
* collected into a single argument at the receiver.
*/
const native_int RI = mcode->splat_position;
const bool RP = (RI >= 0);
// expecting 0, got 0.
if(T == 0 && N == 0) {
if(RP) {
scope->set_local(mcode->splat_position, Array::create(state, 0));
}
return true;
}
const bool lambda = ((flags & CallFrame::cIsLambda) == CallFrame::cIsLambda);
// Only do destructuring in non-lambda mode
if(!lambda) {
/* If only one argument was yielded and the block takes more than one
* argument or has form { |a, | }:
*
* 1. If the object is an Array, assign elements to arguments.
* 2. If the object returns 'nil' from #to_ary, assign the object
* to the first argument.
* 3. If the object returns an Array from #to_ary, assign the
* elements to the arguments.
* 4. If the object returns non-Array from #to_ary, raise a TypeError.
*/
if(N == 1 && (T > 1 || (RP && T > 0) || RI < -2)) {
Object* obj = args.get_argument(0);
Array* ary = 0;
if(!(ary = try_as<Array>(obj))) {
if(CBOOL(obj->respond_to(state, G(sym_to_ary), cFalse))) {
if(!(obj = obj->send(state, call_frame, G(sym_to_ary)))) {
return false;
}
if(!(ary = try_as<Array>(obj)) && !obj->nil_p()) {
Exception::type_error(state, "to_ary must return an Array", call_frame);
return false;
}
}
}
if(ary) {
if(RI == -4 && M == 1) {
args.use_argument(ary);
} else {
args.use_array(ary);
}
N = args.total();
}
}
}
const native_int P = mcode->post_args;
const native_int H = M - P;
// Too many args (no rest argument!)
if(!RP && N > T) {
if(lambda) return false;
N = T;
}
// Too few args!
if(lambda && N < M) return false;
Object* kw = 0;
Object* kw_remainder = 0;
bool KP = false;
bool KA = false;
if(mcode->keywords && N > M) {
Object* obj = args.get_argument(args.total() - 1);
OnStack<1> os(state, obj);
Object* arguments[2];
arguments[0] = obj;
arguments[1] = RBOOL(O > 0 || RP);
Arguments args(G(sym_keyword_object), G(runtime), 2, arguments);
Dispatch dis(G(sym_keyword_object));
Object* kw_result = dis.send(state, call_frame, args);
if(kw_result) {
if(Array* ary = try_as<Array>(kw_result)) {
Object* o = 0;
if(!(o = ary->get(state, 0))->nil_p()) {
kw_remainder = o;
KA = true;
}
kw = ary->get(state, 1);
KP = true;
}
} else {
return false;
}
}
// A single kwrest argument
if(mcode->keywords && !RP && !KP && N >= T) {
if(lambda) return false;
N = T - 1;
}
const native_int K = (KP && !KA && N > M) ? 1 : 0;
const native_int N_M_K = N - M - K;
const native_int E = N_M_K > 0 ? N_M_K : 0;
native_int X;
const native_int ON = (X = MIN(O, E)) > 0 ? X : 0;
const native_int RN = (RP && (X = E - ON) > 0) ? X : 0;
const native_int PI = H + O + (RP ? 1 : 0);
const native_int KI = RP ? T : T - 1;
native_int a = 0; // argument index
native_int l = 0; // local index
// head arguments
if(H > 0) {
for(; l < H && a < N; l++, a++) {
scope->set_local(l, args.get_argument(a));
}
for(; l < H; l++) {
scope->set_local(l, cNil);
}
}
// optional arguments
if(O > 0) {
for(; l < H + O && a < MIN(N, H + ON); l++, a++) {
if(unlikely(kw_remainder && !RP && (a == N - 1))) {
scope->set_local(l, kw_remainder);
} else {
scope->set_local(l, args.get_argument(a));
}
}
for(; l < H + O; l++) {
scope->set_local(l, G(undefined));
}
}
// rest arguments
if(RP) {
Array* ary;
if(RN > 0) {
ary = Array::create(state, RN);
for(int i = 0; i < RN && a < N - P - K; i++, a++) {
if(unlikely(kw_remainder && (a == N - 1))) {
ary->set(state, i, kw_remainder);
} else {
ary->set(state, i, args.get_argument(a));
}
}
} else {
ary = Array::create(state, 0);
}
scope->set_local(RI, ary);
}
// post arguments
if(P > 0) {
const native_int N_K = (X = MIN(N, N - K)) > 0 ? X : N;
for(l = PI; l < PI + P && a < N_K; l++, a++) {
scope->set_local(l, args.get_argument(a));
}
for(; l < PI + P; l++) {
scope->set_local(l, cNil);
}
}
// keywords
if(kw) {
scope->set_local(KI, kw);
}
return true;
}
};
// Installed by default in BlockEnvironment::execute, it runs the bytecodes
// for the block in the interpreter.
//
// Future code will detect hot blocks and queue them in the JIT, whereby the
// JIT will install a newly minted machine function into ::execute.
Object* BlockEnvironment::execute_interpreter(STATE, CallFrame* previous,
BlockEnvironment* env, Arguments& args,
BlockInvocation& invocation)
{
// Don't use env->machine_code() because it might lock and the work should
// already be done.
MachineCode* const mcode = env->compiled_code_->machine_code();
if(!mcode) {
Exception::internal_error(state, previous, "invalid bytecode method");
return 0;
}
#ifdef ENABLE_LLVM
if(mcode->call_count >= 0) {
if(mcode->call_count >= state->shared().config.jit_threshold_compile) {
OnStack<1> os(state, env);
G(jit)->compile_soon(state, env->compiled_code(), previous,
invocation.self->direct_class(state), env, true);
} else {
mcode->call_count++;
}
}
#endif
StackVariables* scope = ALLOCA_STACKVARIABLES(mcode->number_of_locals);
Module* mod = invocation.module;
if(!mod) mod = env->module();
Object* block = cNil;
if(VariableScope* scope = env->top_scope_) {
if(!scope->nil_p()) block = scope->block();
}
scope->initialize(invocation.self, block, mod, mcode->number_of_locals);
scope->set_parent(env->scope_);
InterpreterCallFrame* frame = ALLOCA_CALLFRAME(mcode->stack_size);
frame->prepare(mcode->stack_size);
frame->previous = previous;
frame->constant_scope_ = invocation.constant_scope;
frame->arguments = &args;
frame->dispatch_data = env;
frame->compiled_code = env->compiled_code_;
frame->scope = scope;
frame->top_scope_ = env->top_scope_;
frame->flags = invocation.flags | CallFrame::cMultipleScopes
| CallFrame::cBlock;
if(!GenericArguments::call(state, frame, mcode, scope, args, invocation.flags)) {
if(state->vm()->thread_state()->raise_reason() == cNone) {
Exception* exc =
Exception::make_argument_error(state, mcode->required_args, args.total(),
mcode->name());
exc->locations(state, Location::from_call_stack(state, previous));
state->raise_exception(exc);
}
return NULL;
}
#ifdef RBX_PROFILER
if(unlikely(state->vm()->tooling())) {
Module* mod = scope->module();
if(SingletonClass* sc = try_as<SingletonClass>(mod)) {
if(Module* ma = try_as<Module>(sc->singleton())) {
mod = ma;
}
}
OnStack<2> os(state, env, mod);
// Check the stack and interrupts here rather than in the interpreter
// loop itself.
GCTokenImpl gct;
if(!state->check_interrupts(gct, frame, frame)) return NULL;
state->checkpoint(gct, frame);
tooling::BlockEntry method(state, env, mod);
return (*mcode->run)(state, mcode, frame);
} else {
// Check the stack and interrupts here rather than in the interpreter
// loop itself.
GCTokenImpl gct;
if(!state->check_interrupts(gct, frame, frame)) return NULL;
state->checkpoint(gct, frame);
return (*mcode->run)(state, mcode, frame);
}
#else
// Check the stack and interrupts here rather than in the interpreter
// loop itself.
GCTokenImpl gct;
if(!state->check_interrupts(gct, frame, frame)) return NULL;
state->checkpoint(gct, frame);
return (*mcode->run)(state, mcode, frame);
#endif
}
Object* BlockEnvironment::call(STATE, CallFrame* call_frame,
Arguments& args, int flags)
{
BlockInvocation invocation(scope_->self(), constant_scope_, flags);
return invoke(state, call_frame, this, args, invocation);
}
Object* BlockEnvironment::call_prim(STATE, CallFrame* call_frame,
Executable* exec, Module* mod,
Arguments& args)
{
return call(state, call_frame, args);
}
Object* BlockEnvironment::call_on_object(STATE, CallFrame* call_frame,
Arguments& args, int flags)
{
if(args.total() < 1) {
Exception* exc =
Exception::make_argument_error(state, 1, args.total(),
compiled_code_->name());
exc->locations(state, Location::from_call_stack(state, call_frame));
state->raise_exception(exc);
return NULL;
}
Object* recv = args.shift(state);
BlockInvocation invocation(recv, constant_scope_, flags);
return invoke(state, call_frame, this, args, invocation);
}
Object* BlockEnvironment::call_under(STATE, CallFrame* call_frame,
Executable* exec, Module* mod,
Arguments& args)
{
if(args.total() < 3) {
Exception* exc =
Exception::make_argument_error(state, 3, args.total(),
compiled_code_->name());
exc->locations(state, Location::from_call_stack(state, call_frame));
state->raise_exception(exc);
return NULL;
}
Object* recv = args.shift(state);
ConstantScope* constant_scope = as<ConstantScope>(args.shift(state));
Object* visibility_scope = args.shift(state);
int flags = CBOOL(visibility_scope) ? CallFrame::cTopLevelVisibility : 0;
BlockInvocation invocation(recv, constant_scope, flags);
return invoke(state, call_frame, this, args, invocation);
}
BlockEnvironment* BlockEnvironment::under_call_frame(STATE, GCToken gct,
CompiledCode* ccode, MachineCode* caller,
CallFrame* call_frame)
{
MachineCode* mcode = ccode->machine_code();
if(!mcode) {
OnStack<1> os(state, ccode);
mcode = ccode->internalize(state, gct, call_frame);
if(!mcode) {
Exception::internal_error(state, call_frame, "invalid bytecode method");
return 0;
}
}
BlockEnvironment* be = state->new_object_dirty<BlockEnvironment>(G(blokenv));
be->scope(state, call_frame->promote_scope(state));
be->top_scope(state, call_frame->top_scope(state));
be->compiled_code(state, ccode);
be->constant_scope(state, call_frame->constant_scope());
be->module(state, call_frame->module());
return be;
}
BlockEnvironment* BlockEnvironment::dup(STATE) {
BlockEnvironment* be = state->new_object_dirty<BlockEnvironment>(G(blokenv));
be->scope(state, scope_);
be->top_scope(state, top_scope_);
be->compiled_code(state, compiled_code_);
be->constant_scope(state, constant_scope_);
be->module(state, nil<Module>());
return be;
}
Object* BlockEnvironment::of_sender(STATE, CallFrame* call_frame) {
if(NativeMethodFrame* nmf = call_frame->previous->native_method_frame()) {
return state->vm()->native_method_environment->get_object(nmf->block());
}
CallFrame* target = call_frame->previous->top_ruby_frame();
// We assume that code using this is going to use it over and
// over again (ie Proc.new) so we mark the method as not
// inlinable so that this works even with the JIT on.
if(!target) {
return cNil;
}
target->compiled_code->machine_code()->set_no_inline();
if(target->scope) {
return target->scope->block();
}
return cNil;
}
void BlockEnvironment::Info::show(STATE, Object* self, int level) {
BlockEnvironment* be = as<BlockEnvironment>(self);
class_header(state, self);
//indent_attribute(++level, "scope"); be->scope()->show(state, level);
// indent_attribute(level, "top_scope"); be->top_scope()->show(state, level);
indent_attribute(level, "compiled_code"); be->compiled_code()->show(state, level);
close_body(level);
}
}
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE:
FILE: uiStartingGradientColorSelector.asm
AUTHOR: Jon Witort
METHODS:
Name Description
---- -----------
FUNCTIONS:
Scope Name Description
----- ---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
jon 24 feb 1992 Initial version.
DESCRIPTION:
Code for the GrObjStartingGradientColorSelectorClass
$Id: uiStartingGradientColorSelector.asm,v 1.1 97/04/04 18:05:52 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
GrObjUIControllerCode segment resource
COMMENT @----------------------------------------------------------------------
MESSAGE: GrObjStartingGradientColorSelectorGetInfo --
MSG_GEN_CONTROL_GET_INFO for GrObjStartingGradientColorSelectorClass
DESCRIPTION: Return group
PASS:
*ds:si - instance data
es - segment of GrObjStartingGradientColorSelectorClass
ax - The message
RETURN:
cx:dx - list of children
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
------------------------------------------------------------------------------@
GrObjStartingGradientColorSelectorGetInfo method dynamic GrObjStartingGradientColorSelectorClass,
MSG_GEN_CONTROL_GET_INFO
; first call our superclass to get the color selector's stuff
pushdw cxdx
mov di, offset GrObjStartingGradientColorSelectorClass
call ObjCallSuperNoLock
; now fill in a few things
popdw esdi
mov si, offset GOSGCS_newFields
mov cx, length GOSGCS_newFields
call CopyFieldsToBuildInfo
ret
GrObjStartingGradientColorSelectorGetInfo endm
GOSGCS_newFields GC_NewField \
<offset GCBI_flags, size GCBI_flags,
<GCD_dword mask GCBF_SUSPEND_ON_APPLY>>,
<offset GCBI_initFileKey, size GCBI_initFileKey,
<GCD_dword GOSGCS_IniFileKey>>,
<offset GCBI_gcnList, size GCBI_gcnList,
<GCD_dword GOSGCS_gcnList>>,
<offset GCBI_gcnCount, size GCBI_gcnCount,
<GCD_dword size GOSGCS_gcnList>>,
<offset GCBI_notificationList, size GCBI_notificationList,
<GCD_dword GOSGCS_notifyList>>,
<offset GCBI_notificationCount, size GCBI_notificationCount,
<GCD_dword size GOSGCS_notifyList>>,
<offset GCBI_controllerName, size GCBI_controllerName,
<GCD_optr GOSGCSName>>,
<offset GCBI_features, size GCBI_features,
<GCD_dword GOSGCS_DEFAULT_FEATURES>>,
<offset GCBI_helpContext, size GCBI_helpContext,
<GCD_dword GOSGCS_helpContext>>
if FULL_EXECUTE_IN_PLACE
GrObjControlInfoXIP segment resource
endif
GOSGCS_helpContext char "dbStGradClr", 0
GOSGCS_IniFileKey char "GrObjStartingGradientColor", 0
GOSGCS_gcnList GCNListType \
<MANUFACTURER_ID_GEOWORKS, GAGCNLT_APP_TARGET_NOTIFY_GROBJ_AREA_ATTR_CHANGE>
GOSGCS_notifyList NotificationType \
<MANUFACTURER_ID_GEOWORKS, GWNT_GROBJ_AREA_ATTR_CHANGE>
if FULL_EXECUTE_IN_PLACE
GrObjControlInfoXIP ends
endif
COMMENT @----------------------------------------------------------------------
MESSAGE: GrObjStartingGradientColorSelectorOutputAction -- MSG_GEN_OUTPUT_ACTION
for GrObjStartingGradientColorSelectorClass
DESCRIPTION: Intercept ColorSelector output that we want
PASS:
*ds:si - instance data
es - segment of GrObjStartingGradientColorSelectorClass
ax - The message
cx:dx - destination (or travel option)
bp - event
RETURN:
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 3/24/92 Initial version
------------------------------------------------------------------------------@
GrObjStartingGradientColorSelectorOutputAction method dynamic GrObjStartingGradientColorSelectorClass,
MSG_GEN_OUTPUT_ACTION
mov di, offset GrObjStartingGradientColorSelectorClass
GOTO ColorInterceptAction
GrObjStartingGradientColorSelectorOutputAction endm
;---
COMMENT @----------------------------------------------------------------------
MESSAGE: GrObjStartingGradientColorSelectorSetColor -- MSG_META_COLORED_OBJECT_SET_COLOR
for GrObjStartingGradientColorSelectorClass
DESCRIPTION: Handle a color change
PASS:
*ds:si - instance data
es - segment of GrObjStartingGradientColorSelectorClass
ax - The message
dxcx - color
RETURN:
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 3/24/92 Initial version
------------------------------------------------------------------------------@
GrObjStartingGradientColorSelectorSetColor method dynamic GrObjStartingGradientColorSelectorClass,
MSG_META_COLORED_OBJECT_SET_COLOR
uses ax, cx, dx, bp
.enter
; if passed index then convert to RGB
cmp ch, CF_RGB
jz rgb
; must convert index to rgb
xchgdw dxcx, bxax
clr di
mov ah, al ;ah = index
call GrMapColorIndex ;al <- red, bl <- green, bh <- blue
xchgdw dxcx, bxax
rgb:
; cl = red, dl = green, dh = blue
mov ch, dl
mov dl, dh
mov ax, MSG_GO_SET_STARTING_GRADIENT_COLOR
call GrObjControlOutputActionRegsToGrObjs
.leave
ret
GrObjStartingGradientColorSelectorSetColor endm
;---
COMMENT @----------------------------------------------------------------------
MESSAGE: GrObjStartingGradientColorSelectorUpdateUI --
MSG_GEN_CONTROL_UPDATE_UI for GrObjStartingGradientColorSelectorClass
DESCRIPTION: Handle notification of attributes change
PASS:
*ds:si - instance data
es - segment of GrObjStartingGradientColorSelectorClass
ax - The message
ss:bp - GenControlUpdateUIParams
GCUUIP_manufacturer ManufacturerID
GCUUIP_changeType word
GCUUIP_dataBlock hptr
GCUUIP_toolInteraction optr
GCUUIP_features word
GCUUIP_toolboxFeatures word
GCUUIP_childBlock hptr
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 11/12/91 Initial version
------------------------------------------------------------------------------@
GrObjStartingGradientColorSelectorUpdateUI method dynamic GrObjStartingGradientColorSelectorClass,
MSG_GEN_CONTROL_UPDATE_UI
mov bx, ss:[bp].GCUUIP_dataBlock ;bx <- notification block
call MemLock
mov es, ax
mov ch, CF_RGB
mov cl, es:[GNAAC_areaAttr].GOBAAE_r
mov dl, es:[GNAAC_areaAttr].GOBAAE_g
mov dh, es:[GNAAC_areaAttr].GOBAAE_b
mov bp, es:[GNAAC_areaAttrDiffs]
call MemUnlock
andnf bp, mask GOBAAD_MULTIPLE_COLORS
mov ax, MSG_COLOR_SELECTOR_SET_COLOR
call ObjCallInstanceNoLock
ret
GrObjStartingGradientColorSelectorUpdateUI endm
GrObjUIControllerCode ends
|
; A015606: a(n) = 11*a(n-1) + 10*a(n-2).
; Submitted by Jamie Morken(s3)
; 0,1,11,131,1551,18371,217591,2577211,30525231,361549651,4282298471,50720779691,600751561311,7115474971331,84277740297751,998209892988571,11823086225851791,140036047414255411,1658627383815327431,19645261696111155851,232684152495375988671,2755978294410247433891,32642602763466481659511,386628413342233772593531,4579338574399236315123951,54239008451813937192298771,642422478713945672266525991,7609037350371541766854773611,90123635641226416158067769631,1067450365557205995407293202051
mov $3,1
lpb $0
sub $0,1
mul $1,10
add $3,$1
mov $2,$3
add $3,$1
mov $1,$2
lpe
mov $0,$1
|
; A239632: Number of parts in all palindromic compositions of n.
; 0,1,3,4,10,12,28,32,72,80,176,192,416,448,960,1024,2176,2304,4864,5120,10752,11264,23552,24576,51200,53248,110592,114688,237568,245760,507904,524288,1081344,1114112,2293760,2359296,4849664,4980736,10223616,10485760,21495808,22020096,45088768,46137344,94371840,96468992,197132288,201326592,411041792,419430400,855638016,872415232,1778384896,1811939328,3690987520,3758096384,7650410496,7784628224,15837691904,16106127360,32749125632,33285996544,67645734912,68719476736,139586437120,141733920768,287762808832,292057776128,592705486848,601295421440,1219770712064,1236950581248,2508260900864,2542620639232,5153960755200,5222680231936,10582799417344,10720238370816,21715354648576,21990232555520,44530220924928,45079976738816,91259465105408,92358976733184,186916976721920,189115999977472,382630046466048,387028092977152,782852278976512,791648371998720,1600888930041856,1618481116086272,3272146604261376,3307330976350208,6685030696878080,6755399441055744,13651536370466816,13792273858822144,27866022694354944,28147497671065600
mov $1,1
mov $2,$0
lpb $2
add $0,$1
mov $1,$0
sub $2,2
lpe
|
; random - sets r to a pseudo random value
random_seed = %t
macro random r
{
random_seed = ((random_seed*214013+2531011) shr 16) and 0xffffffff
r = random_seed
}
; Use this only with procedures returning result in EAX
; or take care of preserving the EAX register otherwise
macro f_call callee
{
local .reference_addr, .out, .ret_addr, .z, .call
; Calculate the reference address
call .call
.call:
add dword[esp], .reference_addr - .call
ret
random .z
dd .z
.reference_addr:
; Calculate the callee address
load .z dword from .reference_addr - 4
mov eax, [esp-4]
mov eax, [eax-4]
xor eax, callee xor .z
; Setup return address
; The return address is within this macro
sub esp, 4
add dword[esp], .ret_addr - .reference_addr
; Jump to callee
jmp eax
random .z
dd .z
random .z
dd .z
; This code is executed upon return
; from the callee
.ret_addr:
sub dword[esp - 4], -(.out - .ret_addr)
sub esp, 4
ret
random .z
dd .z
.out:
}
|
PAGE 75, 132
TITLE Deep291 - Your Name - Current Date
COMMENT %
WordFind
--------------------
ECE291: MP1 - Deep 291
Prof. John W. Lockwood
Unversity of Illinois, Dept. of Electrical & Computer Engineering
Assistant Guest Authors: Pat Spizzo, Neil Kumar
Fall 1998
Revision 1.0
%
;====== Constants =========================================================
CR EQU 13
LF EQU 10
;====== Externals =========================================================
; -- LIB291 Routines (free) --
extrn dspout:near ; See your lab manual for a full description
extrn dspmsg:near ; of the ECE291 lib291 functions
extrn dosxit:near ; Quit to DOS
; -- LIB291 Routines (free) --
extrn mp1xit:near ; Terminate MP1
;====== Stack Segment =====================================================
stkseg segment stack
db 64 dup ('STACK ')
stkseg ends
;====== Code/Data segment =================================================
cseg segment public 'CODE'
assume cs:cseg, ds:cseg, ss:stkseg, es:nothing
;====== Variables =========================================================
INCLUDE wordfile.asm ; Define NumRows & NumCols; Create OrigMatrix
EndMatrix db NumRows*NumCols dup ('.')
RowSize dw NumRows
ColSize dw NumCols
CommandErrorMessage db 'Usage: mp1 WordToFind',CR,LF,'$'
StartMessage db '------------- Original matrix ------------',CR,LF,'$'
EndMessage db '-------------- Final matrix --------------',CR,LF,'$'
crlf db CR,LF,'$' ; Carriage Return / Line Feed String
WordLength dw ? ; Length of search word
RowPos dw ?
ColPos dw ?
offsetPos dw ?
PUBLIC OrigMatrix,RowSize,ColSize,EndMatrix ; Variables visible to LIBMP1
PUBLIC WordLength,RowPos,ColPos,offsetPos ;
; ======== Your Code ======================================================
; -- Write the code for your subroutines below --
; To use your own code,
; comment out the 'extrn' routine from above and
; uncomment your procedure declaration
extrn PrintMatrix:near
; Inputs:
; si = index to matrix to print
; PrintMatrix proc NEAR
; For all letters in origMatrix {
; ..
; MOV DL,[si]
; ..
; Print character to screen
; ..
; }
; PrintMatrix ENDP
extrn CheckLetter:near
; Inputs:
; offsetPos = position of letter in OrigMatrix to check
; Outputs:
; zf = zero if letter matches
; zf = one if letter does not match
extrn CheckRight:near
; Inputs:
; offsetPos = RowPos*NumCols + ColPos
; RowPos = current row position
; ColPos = current column position
; WordLength = length of word to find
; Outputs
; zf = zero if word matches
; zf = one if any letter mismatches
extrn ReplaceRight:near
; Inputs:
; offsetPos = RowPos*NumCols + ColPos
; RowPos = current row position
; ColPos = current column position
; WordLength = length of word to find
; Output
; EndMatrix
extrn CheckDown:near
; Inputs/Ouputs: Same as CheckRight
extrn ReplaceDown:near
; Inputs/Ouputs: Same as ReplaceRight
; Remaining Directions..
extrn CheckLeft:near
extrn ReplaceLeft:near
extrn CheckUp:near
extrn ReplaceUp:near
;====== Main procedure ====================================================
main proc far
; The Main body of the program parses the command
; line and invokes each subroutine. You are given this code.
; Command line arguments can be set in Codeview
; by selecting the (R)un menu, then (S)et args.
mov ax, ds ; DOS reads command line arguments from the PSP
mov es, ax ; (See: Hyde, Section 13.3.11 for details)
mov ax, cseg
mov ds, ax ; set DS=CS
mov cl, byte ptr es:[80h] ; Read Length of Command Line
cmp cl, 1
jbe CommandLineError ; Terminate program for no input
mov ch,0
dec CX
mov SI,0
CheckNextArgumentLetter:
CMP BYTE PTR ES:[82h+SI],' '
JE CommandLineDone ; Determine length of first argument
INC SI ; by scanning for a space
LOOP CheckNextArgumentLetter
CommandLineDone: ; Start MP0
mov WordLength,SI
mov dx, offset StartMessage
call dspmsg
mov si, offset OrigMatrix
call PrintMatrix
mov offsetPos, 0 ; Start scanning at top-left
mov RowPos, 0 ; corner of OrigMatrix.
mov ColPos, 0
LetterScanLoop:
call CheckLetter
jne ProcessNextLetter
; First Letter matches, now check for word match in all four directions
call CheckRight ; Scan for words going right
jne RightChecked
call ReplaceRight ; Copy word to EndMatrix if it matches
RightChecked:
call CheckDown ; Scan for words going down
jne DownChecked
call ReplaceDown
DownChecked:
call CheckLeft ; Scan for words going right
jne LeftChecked
call ReplaceLeft
LeftChecked:
call CheckUp
jne UpChecked ; Scan for words going up
call ReplaceUp
UpChecked:
ProcessNextLetter:
inc offsetPos ; advance to next position
inc ColPos ; advance to next column
cmp ColPos, NumCols
jb LetterScanLoop
ProcessNextRow:
mov ColPos,0
inc RowPos ; advance to next row
cmp RowPos, NumRows
jb LetterScanLoop
; Search has completed
mov dx, offset CRLF
call dspmsg
mov dx, offset EndMessage
call dspmsg
mov si, offset EndMatrix
call PrintMatrix
call mp1xit
CommandLineError:
mov dx, offset CommandErrorMessage
call dspmsg
; Print Error message and quit if program isn't
; called with command line argument
call dosxit
main endp
cseg ends
end main
|
; A239284: a(n) = (15^n - (-1)^n)/16.
; 0,1,14,211,3164,47461,711914,10678711,160180664,2402709961,36040649414,540609741211,8109146118164,121637191772461,1824557876586914,27368368148803711,410525522232055664,6157882833480834961,92368242502212524414,1385523637533187866211,20782854562997817993164,311742818444967269897461,4676142276674509048461914,70142134150117635726928711,1052132012251764535903930664,15781980183776468038558959961,236729702756647020578384399414,3550945541349705308675765991211,53264183120245579630136489868164
mov $1,15
pow $1,$0
add $1,2
mov $0,$1
div $0,16
|
// Copyright 2017 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 "chromecast/browser/cast_web_view.h"
#include <utility>
#include "base/logging.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chromecast/base/metrics/cast_metrics_helper.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "ipc/ipc_message.h"
#include "net/base/net_errors.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "url/gurl.h"
#if defined(OS_ANDROID)
#include "chromecast/browser/android/cast_web_contents_activity.h"
#endif // defined(OS_ANDROID)
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace chromecast {
namespace {
// The time (in milliseconds) we wait for after a page is closed (i.e.
// after an app is stopped) before we delete the corresponding WebContents.
constexpr int kWebContentsDestructionDelayInMs = 50;
std::unique_ptr<content::WebContents> CreateWebContents(
content::BrowserContext* browser_context,
scoped_refptr<content::SiteInstance> site_instance) {
CHECK(display::Screen::GetScreen());
gfx::Size display_size =
display::Screen::GetScreen()->GetPrimaryDisplay().size();
content::WebContents::CreateParams create_params(browser_context, NULL);
create_params.routing_id = MSG_ROUTING_NONE;
create_params.initial_size = display_size;
create_params.site_instance = site_instance;
content::WebContents* web_contents =
content::WebContents::Create(create_params);
return base::WrapUnique(web_contents);
}
} // namespace
CastWebView::CastWebView(Delegate* delegate,
content::BrowserContext* browser_context,
scoped_refptr<content::SiteInstance> site_instance,
bool transparent)
: delegate_(delegate),
browser_context_(browser_context),
site_instance_(std::move(site_instance)),
transparent_(transparent),
web_contents_(CreateWebContents(browser_context_, site_instance_)),
window_(shell::CastContentWindow::Create(delegate)),
did_start_navigation_(false),
weak_factory_(this) {
DCHECK(delegate_);
DCHECK(browser_context_);
DCHECK(window_);
content::WebContentsObserver::Observe(web_contents_.get());
web_contents_->SetDelegate(this);
if (transparent_)
window_->SetTransparent();
}
CastWebView::~CastWebView() {}
void CastWebView::LoadUrl(GURL url) {
web_contents_->GetController().LoadURL(url, content::Referrer(),
ui::PAGE_TRANSITION_TYPED, "");
}
void CastWebView::ClosePage() {
content::WebContentsObserver::Observe(nullptr);
web_contents_->ClosePage();
}
void CastWebView::CloseContents(content::WebContents* source) {
DCHECK_EQ(source, web_contents_.get());
// We need to delay the deletion of web_contents_ to give (and guarantee) the
// renderer enough time to finish 'onunload' handler (but we don't want to
// wait any longer than that to delay the starting of next app).
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&CastWebView::DelayedCloseContents,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kWebContentsDestructionDelayInMs));
}
void CastWebView::DelayedCloseContents() {
// Delete the WebContents object here so that the gfx surface will be
// deleted as part of destroying RenderWidgetHostViewCast object.
// We want to delete the surface before we start the next app because
// the next app could be an external one whose Start() function would
// destroy the primary gfx plane.
window_.reset(); // Window destructor requires live web_contents on Android.
web_contents_.reset();
delegate_->OnPageStopped(net::OK);
}
void CastWebView::Show(CastWindowManager* window_manager) {
DCHECK(window_manager);
window_->ShowWebContents(web_contents_.get(), window_manager);
web_contents_->Focus();
}
content::WebContents* CastWebView::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
LOG(INFO) << "Change url: " << params.url;
// If source is NULL which means current tab, use web_contents_ of this class.
if (!source)
source = web_contents_.get();
DCHECK_EQ(source, web_contents_.get());
// We don't want to create another web_contents. Load url only when source is
// specified.
source->GetController().LoadURL(params.url, params.referrer,
params.transition, params.extra_headers);
return source;
}
void CastWebView::LoadingStateChanged(content::WebContents* source,
bool to_different_document) {
delegate_->OnLoadingStateChanged(source->IsLoading());
}
void CastWebView::ActivateContents(content::WebContents* contents) {
DCHECK_EQ(contents, web_contents_.get());
contents->GetRenderViewHost()->GetWidget()->Focus();
}
#if defined(OS_ANDROID)
base::android::ScopedJavaLocalRef<jobject>
CastWebView::GetContentVideoViewEmbedder() {
DCHECK(web_contents_);
auto* activity = shell::CastWebContentsActivity::Get(web_contents_.get());
return activity->GetContentVideoViewEmbedder();
}
#endif // defined(OS_ANDROID)
void CastWebView::RenderProcessGone(base::TerminationStatus status) {
LOG(INFO) << "APP_ERROR_CHILD_PROCESS_CRASHED";
delegate_->OnPageStopped(net::ERR_UNEXPECTED);
}
void CastWebView::RenderViewCreated(content::RenderViewHost* render_view_host) {
content::RenderWidgetHostView* view =
render_view_host->GetWidget()->GetView();
if (view) {
view->SetBackgroundColor(transparent_ ? SK_ColorTRANSPARENT
: SK_ColorBLACK);
}
}
void CastWebView::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
// If the navigation was not committed, it means either the page was a
// download or error 204/205, or the navigation never left the previous
// URL. Ignore these navigations.
if (!navigation_handle->HasCommitted()) {
LOG(WARNING) << "Navigation did not commit: url="
<< navigation_handle->GetURL();
return;
}
net::Error error_code = navigation_handle->GetNetErrorCode();
if (!navigation_handle->IsErrorPage())
return;
// If we abort errors in an iframe, it can create a really confusing
// and fragile user experience. Rather than create a list of errors
// that are most likely to occur, we ignore all of them for now.
if (!navigation_handle->IsInMainFrame()) {
LOG(ERROR) << "Got error on sub-iframe: url=" << navigation_handle->GetURL()
<< ", error=" << error_code
<< ", description=" << net::ErrorToShortString(error_code);
return;
}
LOG(ERROR) << "Got error on navigation: url=" << navigation_handle->GetURL()
<< ", error_code=" << error_code
<< ", description= " << net::ErrorToShortString(error_code);
delegate_->OnPageStopped(error_code);
}
void CastWebView::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
// Only report an error if we are the main frame. See b/8433611.
if (render_frame_host->GetParent()) {
LOG(ERROR) << "Got error on sub-iframe: url=" << validated_url.spec()
<< ", error=" << error_code;
} else if (error_code == net::ERR_ABORTED) {
// ERR_ABORTED means download was aborted by the app, typically this happens
// when flinging URL for direct playback, the initial URLRequest gets
// cancelled/aborted and then the same URL is requested via the buffered
// data source for media::Pipeline playback.
LOG(INFO) << "Load canceled: url=" << validated_url.spec();
} else {
LOG(ERROR) << "Got error on load: url=" << validated_url.spec()
<< ", error_code=" << error_code;
delegate_->OnPageStopped(error_code);
}
}
void CastWebView::DidFirstVisuallyNonEmptyPaint() {
metrics::CastMetricsHelper::GetInstance()->LogTimeToFirstPaint();
}
void CastWebView::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
if (did_start_navigation_) {
return;
}
did_start_navigation_ = true;
#if defined(USE_AURA)
// Resize window
gfx::Size display_size =
display::Screen::GetScreen()->GetPrimaryDisplay().size();
aura::Window* content_window = web_contents()->GetNativeView();
content_window->SetBounds(
gfx::Rect(display_size.width(), display_size.height()));
#endif
}
void CastWebView::MediaStartedPlaying(const MediaPlayerInfo& media_info,
const MediaPlayerId& id) {
metrics::CastMetricsHelper::GetInstance()->LogMediaPlay();
}
void CastWebView::MediaStoppedPlaying(const MediaPlayerInfo& media_info,
const MediaPlayerId& id) {
metrics::CastMetricsHelper::GetInstance()->LogMediaPause();
}
} // namespace chromecast
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %rbp
push %rcx
push %rdx
// Faulty Load
lea addresses_A+0x17b2d, %r12
nop
nop
nop
nop
nop
sub $14068, %rcx
mov (%r12), %rbp
lea oracles, %r12
and $0xff, %rbp
shlq $12, %rbp
mov (%r12,%rbp,1), %rbp
pop %rdx
pop %rcx
pop %rbp
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_A', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': True, 'size': 8, 'type': 'addresses_A', 'congruent': 0}}
<gen_prepare_buffer>
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r8
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1505f, %rsi
lea addresses_WT_ht+0x1950f, %rdi
nop
nop
nop
sub $24834, %rbp
mov $126, %rcx
rep movsl
nop
nop
nop
nop
xor %rbp, %rbp
lea addresses_WC_ht+0xf133, %rsi
lea addresses_A_ht+0xe063, %rdi
clflush (%rsi)
nop
nop
xor %r8, %r8
mov $96, %rcx
rep movsl
nop
and %r8, %r8
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r8
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_A+0x1c333, %r10
nop
nop
nop
add $39012, %rbx
mov $0x5152535455565758, %r9
movq %r9, %xmm1
vmovups %ymm1, (%r10)
dec %r10
// REPMOV
lea addresses_PSE+0x12723, %rsi
lea addresses_UC+0x9f93, %rdi
nop
nop
add %r10, %r10
mov $13, %rcx
rep movsl
nop
nop
add $8359, %r9
// Faulty Load
lea addresses_UC+0x18133, %r15
nop
nop
nop
nop
nop
and $40774, %r10
vmovaps (%r15), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $1, %xmm0, %rax
lea oracles, %r15
and $0xff, %rax
shlq $12, %rax
mov (%r15,%rax,1), %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_UC', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 9}}
{'src': {'type': 'addresses_PSE', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC', 'congruent': 3, 'same': False}}
[Faulty Load]
{'src': {'type': 'addresses_UC', 'AVXalign': True, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'48': 18, '45': 48, '33': 21628, '35': 3, '9d': 1, '00': 131}
00 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 45 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 45 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 45 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A200998: Triangular numbers, T(m), that are three-quarters of another triangular number: T(m) such that 4*T(m)=3*T(k) for some k.
; 0,21,4095,794430,154115346,29897582715,5799976931385,1125165627105996,218276331681631860,42344483180609474865,8214611460706556491971,1593592278893891349967530,309148687493954215337208870,59973251781548223884068553271,11634501696932861479293962125725,2257033355953193578759144583837400,437852836553222621417794755302329896,84941193257969235361473423384068162445,16478153639209478437504426341753921184455,3196676864813380847640497236876876641621846,620138833620156674963818959527772314553453690
seq $0,82841 ; a(n) = 4*a(n-1) - a(n-2) for n>1, a(0)=3, a(1)=9.
pow $0,2
div $0,6
pow $0,2
div $0,8
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %r9
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x1aa01, %rdx
nop
nop
xor %r9, %r9
movb (%rdx), %bl
nop
and $53048, %rax
lea addresses_WT_ht+0x1c401, %r13
xor $55313, %r14
movw $0x6162, (%r13)
nop
nop
nop
nop
dec %r14
lea addresses_WC_ht+0x14d71, %r14
nop
nop
nop
nop
nop
and $543, %rbp
vmovups (%r14), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $0, %xmm5, %rbx
nop
nop
add $25011, %rax
lea addresses_WT_ht+0x1e371, %rsi
lea addresses_D_ht+0xdbc5, %rdi
clflush (%rsi)
nop
nop
nop
sub %rdx, %rdx
mov $23, %rcx
rep movsq
cmp $2606, %r9
lea addresses_A_ht+0x1ac41, %r14
nop
nop
nop
cmp %rsi, %rsi
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
and $0xffffffffffffffc0, %r14
movaps %xmm3, (%r14)
xor %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_D+0xb701, %rsi
lea addresses_PSE+0x1ca01, %rdi
nop
nop
nop
nop
nop
inc %rbp
mov $24, %rcx
rep movsq
nop
nop
nop
nop
add %r14, %r14
// Store
lea addresses_WC+0x13a01, %r14
nop
add %r10, %r10
mov $0x5152535455565758, %rsi
movq %rsi, (%r14)
nop
nop
nop
xor $48569, %rax
// Store
lea addresses_RW+0x1301d, %rsi
nop
nop
sub %rbp, %rbp
movl $0x51525354, (%rsi)
nop
nop
xor $47158, %rsi
// Store
lea addresses_UC+0x11635, %rax
xor $48079, %rdi
movl $0x51525354, (%rax)
nop
nop
nop
nop
nop
sub $54182, %r10
// Load
mov $0x6088f10000000201, %rax
nop
nop
nop
sub %rbp, %rbp
movb (%rax), %r10b
nop
nop
nop
dec %r14
// Store
lea addresses_PSE+0x1ca01, %rbp
nop
nop
nop
nop
sub $62133, %rsi
mov $0x5152535455565758, %rdi
movq %rdi, (%rbp)
sub $6339, %rax
// Faulty Load
lea addresses_PSE+0x1ca01, %r14
clflush (%r14)
nop
nop
nop
dec %rdi
mov (%r14), %si
lea oracles, %rax
and $0xff, %rsi
shlq $12, %rsi
mov (%rax,%rsi,1), %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_PSE', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_RW', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 4, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_NC', 'same': False, 'size': 1, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_PSE', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_PSE', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 32, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': True, 'AVXalign': True}, 'OP': 'STOR'}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; double scalbn(double x, int n)
SECTION code_clib
SECTION code_fp_math48
PUBLIC am48_scalbn
EXTERN am48_ldexp
; compute AC' * FLT_RADIX^n efficiently
;
; enter : AC' = double x
; HL = n
;
; exit : success
;
; AC' = x * 2^n
; carry reset
;
; fail if overflow
;
; AC' = +-inf
; carry set, errno set
;
; uses : af, bc', de', hl'
defc am48_scalbn = am48_ldexp
|
#include <cstdio>
#include <algorithm>
#include <string>
#include <cassert>
bool is_digit(char chr) {
return static_cast<bool>(isdigit(chr));
}
bool is_minus(char chr) {
return chr == '-';
}
bool is_alpha(char chr) {
return static_cast<bool>(isalpha(chr));
}
bool is_sep(char chr) {
return static_cast<bool>(std::string("(),").find(chr) != std::string::npos);
}
// ignore ' ' and ','
void ignore_unused_char(const std::string& list_str, size_t& pos) {
while(list_str[pos] == ' ' or list_str[pos] == ',') pos++;
}
void parse(const std::string& list_str, size_t& pos, size_t& paren_depth) {
if(list_str[pos] == '(') {
pos++; paren_depth++; // '('
printf("ap ap cons ");
size_t begin_paren_depth = paren_depth, elem_cnt = 0;
while(!(list_str[pos] == ')' and paren_depth == begin_paren_depth)) {
parse(list_str, pos, paren_depth);
// more than 2 blocks in parentheses is forbidden
assert(++elem_cnt <= 2);
ignore_unused_char(list_str, pos);
}
assert(list_str[pos++] == ')'); paren_depth--; // ')'
ignore_unused_char(list_str, pos);
}
// number: [-]?[0-9]*
else if (is_minus(list_str[pos]) or is_digit(list_str[pos])) {
std::string number = "";
number += list_str[pos++]; // the first char
while(is_digit(list_str[pos])) {
// space
if(list_str[pos] == ' ') continue;
number += list_str[pos++];
}
printf("%s ", number.c_str());
ignore_unused_char(list_str, pos);
}
// word: [A-Za-z]+[A-Za-z0-9]*
else if(is_alpha(list_str[pos])) {
std::string word = "";
while(!is_sep(list_str[pos])) {
// space
if(list_str[pos] == ' ') continue;
word += list_str[pos++];
}
printf("%s ", word.c_str());
ignore_unused_char(list_str, pos);
}
else {
// if reached -> bug? the given list is wrong?
assert(false);
}
}
int main(int argc, char** argv) {
if(argc != 2) {
fprintf(stderr, "Usage: %s list_str\n", argv[0]);
return 1;
}
std::string list_str = argv[1];
size_t pos = 0, paren_depth = 0;
while(pos < list_str.size()) {
parse(list_str, pos, paren_depth);
}
puts("");
return 0;
}
|
#ifndef SPIKINGSYNAPSES_H
#define SPIKINGSYNAPSES_H
class SpikingSynapses; // forward definition
#include "Synapses.hpp"
#include "Spike/Models/SpikingModel.hpp"
#include "Spike/Neurons/SpikingNeurons.hpp"
#include <vector>
namespace Backend {
class SpikingSynapses : public virtual Synapses {
public:
SPIKE_ADD_BACKEND_FACTORY(SpikingSynapses);
virtual void copy_weights_to_host() = 0;
virtual void state_update(unsigned int current_time_in_timesteps, float timestep) = 0;
};
}
struct spiking_synapse_parameters_struct : synapse_parameters_struct {
float delay_range[2];
std::vector<float> pairwise_connect_delay;
};
class SpikingSynapses : public Synapses {
public:
SpikingSynapses() : Synapses() {};
SpikingSynapses(int seedval) : Synapses(seedval) {};
~SpikingSynapses() override;
SPIKE_ADD_BACKEND_GETSET(SpikingSynapses, Synapses);
void init_backend(Context* ctx = _global_ctx) override;
void prepare_backend_early() override;
// Host Pointers
int* delays = nullptr;
SpikingModel* model = nullptr;
// For spike array stuff
int minimum_axonal_delay_in_timesteps = pow(10, 6);
int maximum_axonal_delay_in_timesteps = 0;
int neuron_pop_size = 0; // parameter for efficient conductance trace
// In order to group synapses, give them a distinction
int num_syn_labels = 1;
int* syn_labels = nullptr;
// Synapse Functions
int AddGroup(int presynaptic_group_id,
int postsynaptic_group_id,
Neurons * neurons,
Neurons * input_neurons,
float timestep,
synapse_parameters_struct * synapse_params) override;
void increment_number_of_synapses(int increment);
void sort_synapses();
void set_synapse_start(int pre_index, int syn_start);
virtual void state_update(unsigned int current_time_in_timesteps, float timestep);
virtual void save_connectivity_as_txt(std::string path, std::string prefix="", int synapsegroupid=-1) override;
virtual void save_connectivity_as_binary(std::string path, std::string prefix="",int synapsegroupid=-1) override;
private:
std::shared_ptr<::Backend::SpikingSynapses> _backend;
};
#endif
|
; A279561: Number of length n inversion sequences avoiding the patterns 101, 102, 201, and 210.
; 1,1,2,6,21,77,287,1079,4082,15522,59280,227240,873886,3370030,13027730,50469890,195892565,761615285,2965576715,11563073315,45141073925,176423482325,690215089745,2702831489825,10593202603775,41550902139551,163099562175851
lpb $0
mov $2,$0
sub $0,2
add $2,$0
bin $2,$0
add $0,1
add $1,$2
lpe
add $1,1
mov $0,$1
|
/*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/test/unit_test/fixtures/device_fixture.h"
#include "gtest/gtest.h"
namespace NEO {
void DeviceFixture::SetUp() {
hardwareInfo = *defaultHwInfo;
SetUpImpl(&hardwareInfo);
}
void DeviceFixture::SetUpImpl(const NEO::HardwareInfo *hardwareInfo) {
pDevice = MockDevice::createWithNewExecutionEnvironment<MockDevice>(hardwareInfo);
ASSERT_NE(nullptr, pDevice);
auto &commandStreamReceiver = pDevice->getGpgpuCommandStreamReceiver();
pTagMemory = commandStreamReceiver.getTagAddress();
ASSERT_NE(nullptr, const_cast<uint32_t *>(pTagMemory));
}
void DeviceFixture::TearDown() {
delete pDevice;
pDevice = nullptr;
}
MockDevice *DeviceFixture::createWithUsDeviceId(unsigned short usDeviceId) {
hardwareInfo = *defaultHwInfo;
hardwareInfo.platform.usDeviceID = usDeviceId;
return MockDevice::createWithNewExecutionEnvironment<MockDevice>(&hardwareInfo);
}
} // namespace NEO
|
lc r4, 0xfffff90a
lc r5, 0xffff8000
ges r6, r4, r5
halt
#@expected values
#r4 = 0xfffff90a
#r5 = 0xffff8000
#r6 = 0x00000001
#pc = -2147483632
#e0 = 0
#e1 = 0
#e2 = 0
#e3 = 0
|
ALIGN 2
public _prtt,_txtx,_txty,_prttcol
_txtx dw 0
_txty dw 0
_prttcol dw 0
public _font3x5
_font3x5 dw 0,0
truerowsadd dw 0
prtmacro MACRO
local prt41,prt42,prt43,prt44,prt45
push di
out dx,al
mov al,byte ptr cs:_prttcol
rcr bl,1
jnc prt41
mov es:[di],al
prt41: add di,cs:truerowsadd
rcr bh,1
jnc prt42
mov es:[di],al
prt42: add di,cs:truerowsadd
rcr cl,1
jnc prt43
mov es:[di],al
prt43: add di,cs:truerowsadd
rcr ch,1
jnc prt44
mov es:[di],al
prt44: add di,cs:truerowsadd
rcr ah,1
jnc prt45
mov es:[di],al
prt45: pop di
ENDM
_prtt PROC FAR
CBEG
call vidstart
mov ax,ds:_rowlen
mov cs:truerowsadd,ax
mov fs,cs:_font3x5[2]
movpar ds,1
movpar si,0
mov di,cs:_txty
mov ax,cs:truerowsadd
mul di
mov di,ax
mov dx,cs:_txtx
shr dx,2
add di,dx
mov dx,3c4h
mov al,02h
out dx,al
inc dx
xor bp,bp ;cnt
mov cx,256
prt3: lodsb
cmp al,9 ;tab
je prt21
cmp al,0
je prt1x
cmp al,31
ja prt2
prt22: jmp prt10
prt1x: jmp prt1
prt21: inc bp
inc di
test bp,7
jz prt22
jmp prt21
prt2: inc bp
push cx
mov bl,al
xor bh,bh
shl bx,3
mov ah,fs:[bx+4]
mov cx,fs:[bx+2]
mov bx,fs:[bx+0]
mov al,01h
prtmacro
mov al,02h
prtmacro
mov al,04h
prtmacro
inc di
inc cs:_txtx
pop cx
prt10: dec cx
jz prt1
jmp prt3
prt1: CEND
_prtt ENDP
|
PAGE ,132 ;
; SCCSID = @(#)SHARELNK.asm 1.0 87/05/11
TITLE SHARELNK LINK FIX ROUTINES - Routines to resolve SHARE externals
NAME SHARELNK
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1991
; * All Rights Reserved.
; */
.xlist
.xcref
INCLUDE DOSSYM.INC
INCLUDE DEVSYM.INC
.cref
.list
;CODE SEGMENT BYTE PUBLIC 'CODE'
;code ENDS
include dosseg.inc
;dosdata segment
;public swap_area_len
;SWAP_AREA_LEN DW 0
;dosdata ends
doscode SEGMENT BYTE PUBLIC 'code'
ASSUME CS:doscode
PUBLIC IRETT ;, Hash_Temp
IRETT DW 0
;Hash_Temp DW 0
procedure LCRITDEVICE,FAR
NOP
Endproc LCRITDEVICE,FAR
procedure SETMEM,FAR
NOP
endproc SETMEM,FAR
procedure SKIPONE,FAR
NOP
endproc SKIPONE,FAR
procedure TWOESC,FAR
NOP
endproc TWOESC,FAR
procedure $STD_CON_STRING_INPUT_NO_ECHO,FAR
NOP
endproc $STD_CON_STRING_INPUT_NO_ECHO,FAR
procedure $STD_CON_INPUT_NO_ECHO,FAR
NOP
endproc $STD_CON_INPUT_NO_ECHO,FAR
procedure INT2F,FAR
NOP
endproc INT2F,FAR
procedure $dup_pdb,FAR
NOP
endproc $dup_pdb,FAR
procedure LEAVEDOS,FAR
NOP
endproc LEAVEDOS,FAR
procedure GETCH,FAR
NOP
endproc GETCH,FAR
procedure COPYONE,FAR
NOP
endproc COPYONE,FAR
procedure $SETDPB,FAR
NOP
endproc $SETDPB,FAR
procedure CALL_ENTRY,FAR
NOP
endproc CALL_ENTRY,FAR
procedure ECRITDISK,FAR
NOP
endproc ECRITDISK,FAR
procedure COPYLIN,FAR
NOP
endproc COPYLIN,FAR
procedure LCRITDISK,FAR
NOP
endproc LCRITDISK,FAR
procedure QUIT,FAR
NOP
endproc QUIT,FAR
procedure BACKSP,FAR
NOP
endproc BACKSP,FAR
procedure DIVOV,FAR
NOP
endproc DIVOV,FAR
procedure STAY_RESIDENT,FAR
NOP
endproc STAY_RESIDENT,FAR
procedure CTRLZ,FAR
NOP
endproc CTRLZ,FAR
procedure EXITINS,FAR
NOP
endproc EXITINS,FAR
procedure OKCALL,FAR
NOP
endproc OKCALL,FAR
procedure SKIPSTR,FAR
NOP
endproc SKIPSTR,FAR
procedure ABSDWRT,FAR
NOP
endproc ABSDWRT,FAR
procedure BADCALL,FAR
NOP
endproc BADCALL,FAR
procedure REEDIT,FAR
NOP
endproc REEDIT,FAR
;procedure INULDEV,FAR
; NOP
;endproc INULDEV,FAR
procedure ABSDRD,FAR
NOP
endproc ABSDRD,FAR
;procedure SNULDEV,FAR
; NOP
;endproc SNULDEV,FAR
procedure COPYSTR,FAR
NOP
endproc COPYSTR,FAR
procedure ECRITDEVICE,FAR
NOP
endproc ECRITDEVICE,FAR
procedure COMMAND,FAR
NOP
endproc COMMAND,FAR
procedure ENTERINS,FAR
NOP
endproc ENTERINS,FAR
procedure DEVIOCALL2,FAR
NOP
endproc DEVIOCALL2,FAR
;procedure FASTOPENTABLE,FAR
; NOP
;endproc FASTOPENTABLE,FAR
procedure HEADER,FAR
NOP
endproc HEADER,FAR
;procedure SYSINITTABLE,FAR
; NOP
;endproc SYSINITTABLE,FAR
;procedure FETCHI_TAG,FAR
; NOP
;endproc FETCHI_TAG,FAR
procedure IFS_DOSCALL,FAR
NOP
endproc IFS_DOSCALL,FAR
procedure KILNEW,FAR
NOP
endproc KILNEW,FAR
;procedure PACKET_TEMP,FAR
; NOP
;endproc PACKET_TEMP,FAR
;procedure Swap_in_DOS_Len,FAR
; NOP
;endproc Swap_in_DOS_Len,FAR
;procedure swap_always_area,far
; NOP
;endproc swap_always_area,FAR
;procedure swap_always_area_len,FAR
; NOP
;endproc swap_always_area_len,FAR
;procedure swap_in_dos,FAR
; NOP
;endproc swap_in_dos,FAR
ifdef DBCS
procedure IntCNE0,FAR
NOP
endproc IntCNE0,FAR
procedure OUTT,FAR ; MSKK01 07/18/89
NOP
endproc OUTT,FAR
endif
procedure FastRet,FAR
NOP
endproc FastRet,FAR
procedure DOSINIT,NEAR
NOP
endproc DOSINIT,NEAR
doscode ENDS
END
|
* ASSEMBLER SOURCE CODE ALIGNMENT CHECK 22JUL70 9300 ASSEMBLER 7011001
*********I/O AND FILE SET-UP
*****INPUT
* 1001-P: ASSEMBLER SOURCE DECK TO BE CHECKED
*****OUTPUT
* PRINTER: LISTING OF ALL CARDS NOT CONFORMING TO STANDARD
* ALIGNMENT RULES, WITH POSITION NUMBER IN DECK
*
* FOR 360 PROGRAMS, WHEN COMPUTER STOPS WITH X'333' DISPLAY, KEY A 1
* INTO LOCATION 4. (9300 PROGRAMS ARE ADDITIONALLY CHECKED FOR ALL
* BLANKS IN COLS. 5-8 AND NON-BLANK IN COL. 11)
* AT END OF RUN COMPUTER WILL HALT WITH X'1FFF' DISPLAY. FOR A NEW
* RUN, LOAD NEW SOURCE DECK, KEY A 1 INTO LOCATION 4 IF IT IS 360
* SOURCE CODE, AND HIT START.
* IF A CARD JAM OR OTHER FAILURE PRODUCES AN UNRECOVERABLE CONDITION,
* HIT CLEAR AND START. X'1FFF' WILL DISPLAY.
* FOLLOW NORMAL NEW RUN PROCEDURE.
*
* THE FOLLOWING CHECKS ARE PERFORMED:
* COLS. 2-8 MUST BE BLANK IF COL. 1 IS BLANK
* COLS. 5-8 MUST ALWAYS BE BLANK (9300 ONLY)
* COL. 9 MUST ALWAYS BE BLANK
* COL. 10 MUST NEVER BE BLANK
* COL. 11 MUST NEVER BE BLANK (9300 ONLY)
* COL. 15 MUST ALWAYS BE BLANK
* COL. 16 MUST NEVER BE BLANK
* COL. 72 MUST ALWAYS BE BLANK
* ALL CARDS NOT CONFORMING TO THE ABOVE WILL BE PRINTED ALONG WITH
* THEIR POSITION NUMBER IN THE DECK.
*
*
G011 START 0
USING *,0
BEGN MVI XYZ,8 SOURCE DECK IN 1001-P
MVC CARD+81(42),CARD+80 CLEAR REST OF OUTPUT LINE
MVC HDR4+16(116),HDR4+15 CLEAR REMAINDER OF HDR4
RSTRT RSTR FOR SOFTWARE RECOVERY
MSG X'333'
MVC S360,*-1 DETERMINE WHETHER 360 PROGRAM
NRUN OPEN PRNT SUBSEQUENT RUNS START HERE
OPEN READ
REED GET READ,CARD READ SOURCE CARD
CLI CARD,X'61' TEST FOR END OF FILE
BC 8,REOF IF SO, GO TO END OF RUN ROUTINE
AP CT,P1 INCREMENT CARD COUNT
CLI CARD,X'5C' COMMENT CARD?
BC 8,REED IF SO, SKIP IT
CLI CARD,X'40' LABEL PRESENT?
BC 7,SYM YES
CLC CARD(8),BLNK NO LABEL, COLS 1-8 MUST BE BLANK
BC 7,PRIN IF NOT, PRINT CARD
BC 15,B09 GO CHECK COL. 9
SYM CLI S360,1 360 PROGRAM?
BC 8,B09 YES
CLC CARD+4(4),BLNK COLS. 5-8 BLANK (9300 ONLY)
BC 7,PRIN IF NOT, PRINT CARD
B09 CLI CARD+8,X'40' COL. 9 MUST BE BLANK
BC 7,PRIN
CLI CARD+9,X'40' COL. 10 MUST NEVER BE BLANK
BC 8,PRIN
CLI S360,1 360 PROGRAM?
BC 8,B15 YES--GO CHECK COL. 15
CLI CARD+10,X'40' COL. 11 NEVER BLANK (9300 ONLY)
BC 8,PRIN
B15 CLI CARD+14,X'40' COL. 15 MUST BE BLANK
BC 7,PRIN
CLI CARD+15,X'40' COL. 16 MUST NEVER BE BLANK
BC 8,PRIN
CLI CARD+71,X'40' COL. 72 MUST BE BLANK
BC 8,REED
* PRINT OUT CARDS NOT CONFORMING TO STANDARD ALIGNMENT RULES
PRIN MVC OUT(5),ED1
ED OUT-1(6),CT POSITION NUMBER IN DECK
BAL 13,CLER
PUT PRNT,OUT PRINT OFFENDING CARD
AP MCT,P1 COUNT IT
BC 15,REED TRY NEXT ONE
* END OF RUN PROCEDURE
REOF MVC HDR4+16(7),CCHK 'NUMBER OF CARDS CHECKED'
MVC HDR4+25(5),ED1
ED HDR4+24(6),CT NUMBER OF CARDS CHECKED
CNTRL PRNT,SP,2,2
PUT PRNT,HDR4
MVC HDR4+16(7),CPRT 'NUMBER OF CARDS PRINTED'
MVC HDR4+25(5),ED1
ED HDR4+24(6),MCT NUMBER OF CARDS PRINTED
PUT PRNT,HDR4
RSTR CLOSE PRNT RESTART RECOVERY HERE
CLOSE READ
MSG X'1FFF'
MVC S360,*-1 NEW DECK 360 SOURCE CODE?
SP CT,CT CLEAR COUNTERS, ETC.
SP PCT,PCT
SP MCT,MCT
MVI OF,1
BC 15,NRUN START NEXT RUN
* PAGE OVERFLOW TEST
CLER CLI OF,1
BC 7,0(,13)
AP PCT,P1 INCREMENT PAGE COUNTER
MVC HDR1+117(3),ED1+2
ED HDR1+116(4),PCT PAGE NUMBER
CNTRL PRNT,SK,7,0
CNTRL PRNT,SP,0,2
PUT PRNT,HDR1
PUT PRNT,HDR2 COLUMN NUMBER (TENS)
CNTRL PRNT,SP,0,2
PUT PRNT,HDR3 COLUMN NUMBER (UNITS)
MVI OF,0 RESET OVERFLOW INDICATOR
BC 15,0(,13)
* PAGE OVERFLOW DETECTION
FOF MVI OF,1
BC 15,0(,14)
*
***********************************************************************
*
* I/O AREAS AND HEADER LINES
DC C' '
OUT DC CL8' ' OUTPUT LINE STARTS HERE
CARD DS CL80 CARD READ IN HERE
DC C' '
DS CL42 REST OF OUTPUT LINE
HDR1 DC CL16'CHARLES J. GIBBS'
DC CL16' '
DC CL16' PROGRAM 7011-'
DC CL16'-ASSEMBLER SOURC'
DC CL16'E CODE ALIGNMENT'
DC CL16' CHECK'
DC CL16' '
DC CL8'PAGE'
HDR2 DC CL16' ' COLUMN NUMBER (TENS)
DC CL16' 1 2 '
DC CL16' 3 4'
DC CL16' 5 '
DC CL16' 6 7 '
DC CL16' 8'
DC CL16' '
DC CL16' '
DC CL4' '
HDR3 DC CL8' ' COLUMN NUMBER (UNITS)
DC CL16'1234567890123456'
DC CL16'7890123456789012'
DC CL16'3456789012345678'
DC CL16'9012345678901234'
DC CL16'5678901234567890'
DC CL16' '
DC CL16' '
DC CL12' '
HDR4 DC CL16'NUMBER OF CARDS '
DS CL116
CCHK DC CL7'CHECKED'
CPRT DC CL7'PRINTED'
* OTHER STUFF
CT DC XL3'C' CARD COUNT
PCT DC XL2'C' PAGE COUNT
MCT DC XL3'C' MISALIGNED CARD COUNT
P1 DC XL1'1C'
OF DC XL1'1' OVERFLOW INDICATOR
S360 DS CL1 360 PROGRAM INDICATOR
XYZ DS CL1
ED1 DC XL5'2020202120'
BLNK EQU HDR3
RBUF DS CL80 READER IOCS BUFFER
* EXTRNS & ENTRYS
EXTRN PRNT
EXTRN READ
EXTRN TBRD
* EXTRN TXS3
ENTRY FOF
ENTRY REOF
ENTRY XYZ
ENTRY RBUF
ENTRY BEGN
END BEGN
|
.data
result:.space 30
space:.asciiz " "
nl:.asciiz "\n"
.macro readInteger(%val)
li $v0,5
syscall
add %val,$v0,$zero
.end_macro
.macro printInteger(%val)
li $v0,1
add $a0,%val,$zero
syscall
.end_macro
.macro space()
li $v0,4
la $a0,space
syscall
.end_macro
.macro endl()
li $v0,4
la $a0,nl
syscall
.end_macro
.macro exit()
li $v0,10
syscall
.end_macro
.macro saveValue(%value)
addi $sp,$sp,-4
sw %value,4($sp)
.end_macro
.macro loadValue(%value)
addi $sp,$sp,4
lw %value,0($sp)
.end_macro
.macro getVisited(%visited,%index,%value)
srlv %value,%visited,%index
andi %value,%value,1
.end_macro
.macro setVisited(%visited,%index,%temp)
li %temp,1
sllv %temp,%temp,%index
or %visited,%visited,%temp
.end_macro
.macro setNotVisited(%visited,%index,%temp)
li %temp,1
sllv %temp,%temp,%index
nor %temp,%temp,$zero
and %visited,%visited,%temp
.end_macro
.macro appendResult(%addr,%index,%val)
sll %index,%index,2
sw %val,%addr(%index)
srl %index,%index,2
.end_macro
.macro printResult(%addr,%length)
sll %length,%length,2
li $t8,4
printLoop:
lw $t9,%addr($t8)
printInteger($t9)
space()
addi $t8,$t8,4
ble $t8,%length,printLoop
srl %length,%length,2
endl()
.end_macro
.text
readInteger($s0)
li $s1,0
li $s2,0
jal Function
exit()
Function:
beq $s2,$s0,FunctionConstructed
li $t0,1
FunctionLoop:
getVisited($s1,$t0,$t1)
bnez $t1,FunctionLoopNext
setVisited($s1,$t0,$t1)
saveValue($ra)
saveValue($t0)
addi $s2,$s2,1
appendResult(result,$s2,$t0)
jal Function
loadValue($t0)
loadValue($ra)
setNotVisited($s1,$t0,$t1)
FunctionLoopNext:
addi $t0,$t0,1
ble $t0,$s0,FunctionLoop
j FunctionReturn
FunctionConstructed:
printResult(result,$s0)
j FunctionReturn
FunctionReturn:
addi $s2,$s2,-1
jr $ra |
; A081477: Complement of A086377.
; 2,3,5,7,9,10,12,14,15,17,19,20,22,24,26,27,29,31,32,34,36,38,39,41,43,44,46,48,50,51,53,55,56,58,60,61,63,65,67,68,70,72,73,75,77,79,80,82,84,85,87,89,90,92,94,96,97,99,101,102,104,106,108,109,111,113,114,116,118,119,121,123,125,126,128,130,131,133,135,137,138,140,142,143,145,147,149,150,152,154,155,157,159,160,162,164,166,167,169,171
add $0,1
mov $1,$0
seq $0,49473 ; Nearest integer to n/sqrt(2).
add $0,$1
|
* spread Thu, 1992 Apr 30 15:47:09
* - macro window
include win1_mac_menu_long
include win1_keys_colour
include win1_keys_wman
include win1_keys_wwork
include win1_keys_wstatus
include win1_keys_wdef_long
white equ 7
red equ 2
green equ 4
black equ 0
cxs equ 6 ; character x-size
mxs equ 400 ; minimum x-size
mys equ 78 ; y-size
sxs equ 3*cxs ; standard loose item size
fxp equ 1*(sxs+4)+4 ; flag x-position
fxs equ mxs-(2*(sxs+4)+8) ; flag x-size
nxs equ cxs*14+8 ; flag name x-size
nxp equ fxp+(fxs-nxs)/2 ; flag name x-position
ixs equ mxs-8 ; info border x-size
iyp equ 14 ; info border y-size
iys equ mys-iyp-2 ; info border y-position
grnstp equ 92
xref.s met.mctt
xref.s meu.mcn1,meu.mcn2,meu.mcn3,meu.mcn4,meu.mcn5
xref.s meu.ok
section menu
;
; fixed part of window defintion
window macr ; menu macro
size mxs,mys ; window size
origin mxs-cxs,cxs ; initial pointer position
wattr 2 \ shadow width
1,c.mbord \ border width, border colour
c.mback ; paper colour
sprite 0
border 1,c.mhigh
iattr c.mpunav,c.miunav,0,0 ; unavailable
iattr c.mpavbl,c.miavbl,0,0 ; available
iattr c.mpslct,c.mislct,0,0 ; selected
help 0 ; no help window defintion
; repeated part of window definion
size_opt a ; internal layout
size mxs,mys,0,0 ; size
info macr
loos macr
appn 0
s_end
; information window defintion
i_wlst macr
i_windw ; the flag
size fxs,14,0,0
origin fxp,0
wattr 0,0,0,c.mfill
olst 0
i_windw ; the flag name
size nxs,11
origin nxp,2
wattr 0,0,0,c.tback
olst flag
i_windw ; info border
size ixs,iys,0,0
origin 4,iyp
wattr 0,1,c.ibord,c.iback
olst mcnr
i_end
; information object list
i_olst flag
i_item
size met.mctt+met.mctt,10
origin nxs/2-met.mctt,1
type text
ink c.tink
csize 0,0
text mctt
i_end
i_olst mcnr
i_item
size 10,10
origin 2,2
type text-meu.mcn1
ink c.ilow
csize 0,0
text mcn1
i_item
size 10,10
origin 2,14
type text-meu.mcn2
ink c.ilow
csize 0,0
text mcn2
i_item
size 10,10
origin 2,26
type text-meu.mcn3
ink c.ilow
csize 0,0
text mcn3
i_item
size 10,10
origin 2,38
type text-meu.mcn4
ink c.ilow
csize 0,0
text mcn4
i_item
size 10,10
origin 2,50
type text-meu.mcn5
ink c.ilow
csize 0,0
text mcn5
i_end
; loose item list
l_ilst macr
l_item mces,0
size sxs,10
origin 4+(sxs+4)*0,2
justify 0,0
type text
selkey esc
text esc
item mli.mces
action esc
l_item mcok,1
size sxs,10
origin mxs-(sxs+4)*1,2,0,0
justify 0,0
type text-meu.ok
selkey ok
text ok
item mli.mcok
action ok
l_item mcn1,2
size ixs-14,10
origin 16,iyp+2
justify 1,0
type text
selkey mcn1
text 0
item mli.mcn1
action mcnr
l_item mcn2,3
size ixs-14,10
origin 16,iyp+2+12
justify 1,0
type text
selkey mcn2
text 0
item mli.mcn2
action mcnr
l_item mcn3,4
size ixs-14,10
origin 16,iyp+2+24
justify 1,0
type text
selkey mcn3
text 0
item mli.mcn3
action mcnr
l_item mcn4,5
size ixs-14,10
origin 16,iyp+2+36
justify 1,0
type text
selkey mcn4
text 0
item mli.mcn4
action mcnr
l_item mcn5,6
size ixs-14,10
origin 16,iyp+2+48
justify 1,0
type text
selkey mcn5
text 0
item mli.mcn5
action mcnr
l_end
; define symbols and work area size in COMMON
alcstat mcnr,80*5
alcstat mcmd,2
setwrk
end
|
; A180569: The Wiener index of the P_3 x P_n grid, where P_m is the path graph on m nodes. The Wiener index of a connected graph is the sum of distances between all unordered pairs of nodes in the graph.
; 4,25,72,154,280,459,700,1012,1404,1885,2464,3150,3952,4879,5940,7144,8500,10017,11704,13570,15624,17875,20332,23004,25900,29029,32400,36022,39904,44055,48484,53200,58212,63529,69160,75114,81400,88027,95004,102340,110044,118125,126592,135454,144720,154399,164500,175032,186004,197425,209304,221650,234472,247779,261580,275884,290700,306037,321904,338310,355264,372775,390852,409504,428740,448569,469000,490042,511704,533995,556924,580500,604732,629629,655200,681454,708400,736047,764404,793480,823284,853825,885112,917154,949960,983539,1017900,1053052,1089004,1125765,1163344,1201750,1240992,1281079,1322020,1363824,1406500,1450057,1494504,1539850,1586104,1633275,1681372,1730404,1780380,1831309,1883200,1936062,1989904,2044735,2100564,2157400,2215252,2274129,2334040,2394994,2457000,2520067,2584204,2649420,2715724,2783125,2851632,2921254,2992000,3063879,3136900,3211072,3286404,3362905,3440584,3519450,3599512,3680779,3763260,3846964,3931900,4018077,4105504,4194190,4284144,4375375,4467892,4561704,4656820,4753249,4851000,4950082,5050504,5152275,5255404,5359900,5465772,5573029,5681680,5791734,5903200,6016087,6130404,6246160,6363364,6482025,6602152,6723754,6846840,6971419,7097500,7225092,7354204,7484845,7617024,7750750,7886032,8022879,8161300,8301304,8442900,8586097,8730904,8877330,9025384,9175075,9326412,9479404,9634060,9790389,9948400,10108102,10269504,10432615,10597444,10764000,10932292,11102329,11274120,11447674,11623000,11800107,11979004,12159700,12342204,12526525,12712672,12900654,13090480,13282159,13475700,13671112,13868404,14067585,14268664,14471650,14676552,14883379,15092140,15302844,15515500,15730117,15946704,16165270,16385824,16608375,16832932,17059504,17288100,17518729,17751400,17986122,18222904,18461755,18702684,18945700,19190812,19438029,19687360,19938814,20192400,20448127,20706004,20966040,21228244,21492625,21759192,22027954,22298920,22572099,22847500,23125132,23405004,23687125
mov $2,$0
mov $4,$0
lpb $0
sub $0,1
add $1,5
mov $3,0
add $4,6
add $3,$4
add $2,$3
add $1,$2
lpe
add $1,4
add $1,$2
|
; pokemon ids
; indexes for:
; - PokemonNames (see data/pokemon/names.asm)
; - BaseData (see data/pokemon/base_stats.asm)
; - EvosAttacksPointers (see data/pokemon/evos_attacks_pointers.asm)
; - EggMovePointers (see data/pokemon/egg_move_pointers.asm)
; - PokemonCries (see data/pokemon/cries.asm)
; - MonMenuIcons (see data/pokemon/menu_icons.asm)
; - PokemonPicPointers (see data/pokemon/pic_pointers.asm)
; - PokemonPalettes (see data/pokemon/palettes.asm)
; - PokedexDataPointerTable (see data/pokemon/dex_entry_pointers.asm)
; - AlphabeticalPokedexOrder (see data/pokemon/dex_order_alpha.asm)
; - EZChat_SortedPokemon (see data/pokemon/ezchat_order.asm)
; - NewPokedexOrder (see data/pokemon/dex_order_new.asm)
; - Pokered_MonIndices (see data/pokemon/gen1_order.asm)
; - AnimationPointers (see gfx/pokemon/anim_pointers.asm)
; - AnimationIdlePointers (see gfx/pokemon/idle_pointers.asm)
; - BitmasksPointers (see gfx/pokemon/bitmask_pointers.asm)
; - FramesPointers (see gfx/pokemon/frame_pointers.asm)
; - Footprints (see gfx/footprints.asm)
const_def 1
const BULBASAUR ; 01
const IVYSAUR ; 02
const VENUSAUR ; 03
const CHARMANDER ; 04
const CHARMELEON ; 05
const CHARIZARD ; 06
const SQUIRTLE ; 07
const WARTORTLE ; 08
const BLASTOISE ; 09
const CATERPIE ; 0a
const METAPOD ; 0b
const BUTTERFREE ; 0c
const WEEDLE ; 0d
const KAKUNA ; 0e
const BEEDRILL ; 0f
const PIDGEY ; 10
const PIDGEOTTO ; 11
const PIDGEOT ; 12
const RATTATA ; 13
const RATICATE ; 14
const SPEAROW ; 15
const FEAROW ; 16
const EKANS ; 17
const ARBOK ; 18
const PIKACHU ; 19
const RAICHU ; 1a
const SANDSHREW ; 1b
const SANDSLASH ; 1c
const NIDORAN_F ; 1d
const NIDORINA ; 1e
const NIDOQUEEN ; 1f
const NIDORAN_M ; 20
const NIDORINO ; 21
const NIDOKING ; 22
const CLEFAIRY ; 23
const CLEFABLE ; 24
const VULPIX ; 25
const NINETALES ; 26
const JIGGLYPUFF ; 27
const WIGGLYTUFF ; 28
const ZUBAT ; 29
const GOLBAT ; 2a
const ODDISH ; 2b
const GLOOM ; 2c
const VILEPLUME ; 2d
const PARAS ; 2e
const PARASECT ; 2f
const VENONAT ; 30
const VENOMOTH ; 31
const DIGLETT ; 32
const DUGTRIO ; 33
const MEOWTH ; 34
const PERSIAN ; 35
const PSYDUCK ; 36
const GOLDUCK ; 37
const MANKEY ; 38
const PRIMEAPE ; 39
const GROWLITHE ; 3a
const ARCANINE ; 3b
const POLIWAG ; 3c
const POLIWHIRL ; 3d
const POLIWRATH ; 3e
const ABRA ; 3f
const KADABRA ; 40
const ALAKAZAM ; 41
const MACHOP ; 42
const MACHOKE ; 43
const MACHAMP ; 44
const BELLSPROUT ; 45
const WEEPINBELL ; 46
const VICTREEBEL ; 47
const TENTACOOL ; 48
const TENTACRUEL ; 49
const GEODUDE ; 4a
const GRAVELER ; 4b
const GOLEM ; 4c
const PONYTA ; 4d
const RAPIDASH ; 4e
const SLOWPOKE ; 4f
const SLOWBRO ; 50
const MAGNEMITE ; 51
const MAGNETON ; 52
const FARFETCH_D ; 53
const DODUO ; 54
const DODRIO ; 55
const SEEL ; 56
const DEWGONG ; 57
const GRIMER ; 58
const MUK ; 59
const SHELLDER ; 5a
const CLOYSTER ; 5b
const GASTLY ; 5c
const HAUNTER ; 5d
const GENGAR ; 5e
const ONIX ; 5f
const DROWZEE ; 60
const HYPNO ; 61
const KRABBY ; 62
const KINGLER ; 63
const VOLTORB ; 64
const ELECTRODE ; 65
const EXEGGCUTE ; 66
const EXEGGUTOR ; 67
const CUBONE ; 68
const MAROWAK ; 69
const HITMONLEE ; 6a
const HITMONCHAN ; 6b
const LICKITUNG ; 6c
const KOFFING ; 6d
const WEEZING ; 6e
const RHYHORN ; 6f
const RHYDON ; 70
const CHANSEY ; 71
const TANGELA ; 72
const KANGASKHAN ; 73
const HORSEA ; 74
const SEADRA ; 75
const GOLDEEN ; 76
const SEAKING ; 77
const STARYU ; 78
const STARMIE ; 79
const MR__MIME ; 7a
const SCYTHER ; 7b
const JYNX ; 7c
const ELECTABUZZ ; 7d
const MAGMAR ; 7e
const PINSIR ; 7f
const TAUROS ; 80
const MAGIKARP ; 81
const GYARADOS ; 82
const LAPRAS ; 83
const DITTO ; 84
const EEVEE ; 85
const VAPOREON ; 86
const JOLTEON ; 87
const FLAREON ; 88
const PORYGON ; 89
const OMANYTE ; 8a
const OMASTAR ; 8b
const KABUTO ; 8c
const KABUTOPS ; 8d
const AERODACTYL ; 8e
const SNORLAX ; 8f
const ARTICUNO ; 90
const ZAPDOS ; 91
const MOLTRES ; 92
const DRATINI ; 93
const DRAGONAIR ; 94
const DRAGONITE ; 95
const MEWTWO ; 96
const MEW ; 97
JOHTO_POKEMON EQU const_value
const CHIKORITA ; 98
const BAYLEEF ; 99
const MEGANIUM ; 9a
const CYNDAQUIL ; 9b
const QUILAVA ; 9c
const TYPHLOSION ; 9d
const TOTODILE ; 9e
const CROCONAW ; 9f
const FERALIGATR ; a0
const SENTRET ; a1
const FURRET ; a2
const HOOTHOOT ; a3
const NOCTOWL ; a4
const LEDYBA ; a5
const LEDIAN ; a6
const SPINARAK ; a7
const ARIADOS ; a8
const CROBAT ; a9
const CHINCHOU ; aa
const LANTURN ; ab
const PICHU ; ac
const CLEFFA ; ad
const IGGLYBUFF ; ae
const TOGEPI ; af
const TOGETIC ; b0
const NATU ; b1
const XATU ; b2
const MAREEP ; b3
const FLAAFFY ; b4
const AMPHAROS ; b5
const BELLOSSOM ; b6
const MARILL ; b7
const AZUMARILL ; b8
const SUDOWOODO ; b9
const POLITOED ; ba
const HOPPIP ; bb
const SKIPLOOM ; bc
const JUMPLUFF ; bd
const AIPOM ; be
const SUNKERN ; bf
const SUNFLORA ; c0
const YANMA ; c1
const WOOPER ; c2
const QUAGSIRE ; c3
const ESPEON ; c4
const UMBREON ; c5
const MURKROW ; c6
const SLOWKING ; c7
const MISDREAVUS ; c8
const UNOWN ; c9
const WOBBUFFET ; ca
const GIRAFARIG ; cb
const PINECO ; cc
const FORRETRESS ; cd
const DUNSPARCE ; ce
const GLIGAR ; cf
const STEELIX ; d0
const SNUBBULL ; d1
const GRANBULL ; d2
const QWILFISH ; d3
const SCIZOR ; d4
const SHUCKLE ; d5
const HERACROSS ; d6
const SNEASEL ; d7
const TEDDIURSA ; d8
const URSARING ; d9
const SLUGMA ; da
const MAGCARGO ; db
const SWINUB ; dc
const PILOSWINE ; dd
const CORSOLA ; de
const REMORAID ; df
const OCTILLERY ; e0
const DELIBIRD ; e1
const MANTINE ; e2
const SKARMORY ; e3
const HOUNDOUR ; e4
const HOUNDOOM ; e5
const KINGDRA ; e6
const PHANPY ; e7
const DONPHAN ; e8
const PORYGON2 ; e9
const STANTLER ; ea
const SMEARGLE ; eb
const TYROGUE ; ec
const HITMONTOP ; ed
const SMOOCHUM ; ee
const ELEKID ; ef
const MAGBY ; f0
const MILTANK ; f1
const BLISSEY ; f2
const RAIKOU ; f3
const ENTEI ; f4
const SUICUNE ; f5
const LARVITAR ; f6
const PUPITAR ; f7
const TYRANITAR ; f8
const LUGIA ; f9
const HO_OH ; fa
const CELEBI ; fb
const COINPUR ; fc
const KATU ; fd
const ADBARSTORK ; fe
NUM_POKEMON EQU const_value + -1
EGG EQU -3
; limits:
; 999: everything that prints dex counts
; 1407: size of wPokedexOrder
; 4095: hard limit; would require serious redesign to increase
if NUM_POKEMON > 999
fail "Too many Pokémon defined!"
endc
; Unown forms
; indexes for:
; - UnownWords (see data/pokemon/unown_words.asm)
; - UnownPicPointers (see data/pokemon/unown_pic_pointers.asm)
; - UnownAnimationPointers (see gfx/pokemon/unown_anim_pointers.asm)
; - UnownAnimationIdlePointers (see gfx/pokemon/unown_idle_pointers.asm)
; - UnownBitmasksPointers (see gfx/pokemon/unown_bitmask_pointers.asm)
; - UnownFramesPointers (see gfx/pokemon/unown_frame_pointers.asm)
const_def 1
const UNOWN_A ; 1
const UNOWN_B ; 2
const UNOWN_C ; 3
const UNOWN_D ; 4
const UNOWN_E ; 5
const UNOWN_F ; 6
const UNOWN_G ; 7
const UNOWN_H ; 8
const UNOWN_I ; 9
const UNOWN_J ; 10
const UNOWN_K ; 11
const UNOWN_L ; 12
const UNOWN_M ; 13
const UNOWN_N ; 14
const UNOWN_O ; 15
const UNOWN_P ; 16
const UNOWN_Q ; 17
const UNOWN_R ; 18
const UNOWN_S ; 19
const UNOWN_T ; 20
const UNOWN_U ; 21
const UNOWN_V ; 22
const UNOWN_W ; 23
const UNOWN_X ; 24
const UNOWN_Y ; 25
const UNOWN_Z ; 26
NUM_UNOWN EQU const_value + -1 ; 26
|
; void __CALLEE__ *sp1_PreShiftSpr_callee(uchar flag, uchar height, uchar width, void *srcframe, void *destframe, uchar rshift)
; 02.2008 aralbrec, Sprite Pack v3.0
; zx81 hi-res version
XLIB sp1_PreShiftSpr_callee
XDEF ASMDISP_SP1_PRESHIFTSPR_CALLEE
.sp1_PreShiftSpr_callee
pop af
exx
pop bc
exx
pop ix
pop de
pop bc
ld b,c
pop hl
ld c,l
pop hl
push af
ld h,l
ld l,c
exx
ld a,c
exx
.asmentry
; enter : a = right shift amount (0-7)
; b = width in characters (# columns)
; h = zero for 1-byte definition; otherwise 2-byte
; de = source frame graphic
; ix = destination frame address
; l = height in characters
; exit : hl = next available address
; uses : af, bc, de, hl, b', ix
.SP1PreShiftSpr
and $07
inc a
ld c,a ; c = right shift amount + 1
ld a,l
inc h
dec h
ld hl,dummy1byte ; point at two 0 bytes if 1-byte def
jr z, onebyte
add a,a
ld hl,dummy2byte ; point at (255,0) pair if 2-byte def
.onebyte
add a,a
add a,a
add a,a ; a = # bytes in graphic definition in each column
.dofirstcol ; first column has no graphics on left, will use dummy bytes for left
push de ; save top of first column
exx
ld b,a
push bc ; save height of column in bytes
.firstcolloop
exx
push bc ; save width and rotation amount
ld b,c ; b = right shift + 1
ld c,(hl) ; c = graphic byte from col on left
ld a,1
xor l
ld l,a
ld a,(de) ; a = graphic byte in current col
inc de
djnz firstsloop
jp firstdoneshift
.firstsloop
rr c
rra
djnz firstsloop
.firstdoneshift
ld (ix+0),a ; store shifted graphic in destination frame
inc ix
pop bc
exx
djnz firstcolloop
pop bc
exx
pop hl
djnz nextcol
push ix
pop hl
ret
.nextcol ; do rest of columns
push de
exx
push bc
; b' = height in pixels
; de = graphic definition for this column
; hl = graphic definition for column to left
; b = width remaining in characters
; c = right shift amount + 1
.colloop
exx
push bc
ld b,c
ld a,(de)
inc de
ld c,(hl)
inc hl
djnz sloop
jp doneshift
.sloop
rr c
rra
djnz sloop
.doneshift
ld (ix+0),a
inc ix
pop bc
exx
djnz colloop
pop bc
exx
pop hl
djnz nextcol
push ix
pop hl
ret
defb 0
.dummy1byte
defb 0,0
.dummy2byte
defb 255,0
DEFC ASMDISP_SP1_PRESHIFTSPR_CALLEE = asmentry - sp1_PreShiftSpr_callee
|
; A037960: a(n) = (n+2)!*n*(3*n+1)/24.
; Submitted by Christian Krause
; 0,1,14,150,1560,16800,191520,2328480,30240000,419126400,6187104000,97037740800,1612798387200,28332944640000,524813313024000,10226013557760000,209144207720448000,4480594531725312000,100357207837286400000,2345925761384325120000,57136703662028390400000,1447712937377558691840000,38105872673116455567360000,1040543673740120309760000000,29440276662242211397632000000,862035498158119546060800000000,26093360826352511227920384000000,815652543922487505306648576000000,26304241931375613314767257600000000
mov $2,$0
trn $0,1
seq $0,5460 ; a(n) = (3*n+4)*(n+3)!/24.
mul $0,$2
|
.code
main proc
; do check with ESI register
mov rax, gs:[30h]
mov rax, [rax+60h]
movzx rax, byte ptr [rax+2h]
test rax, rax
mov rbx, 0baadc0deh
mov rax, 0cafebabeh
cmove rbx, rax
xor rsi, rbx
; move back to 32 bit
call $+5
mov DWORD PTR [rsp+4h], 23h
add DWORD PTR [rsp], 0Dh
retf
main endp
end |
; A044833: Positive integers having more base-7 runs of even length than odd.
; 8,16,24,32,40,48,392,400,408,416,424,432,440,784,792,800,808,816,824,832,1176,1184,1192,1200,1208,1216,1224,1568,1576,1584,1592,1600,1608,1616,1960,1968,1976,1984,1992,2000,2008,2352
mov $2,$0
add $2,1
mov $3,$0
lpb $2,1
mov $0,$3
sub $2,1
sub $0,$2
gcd $4,1
add $0,$4
add $4,6
gcd $4,$0
mul $4,7
div $4,42
mul $4,336
add $4,8
add $1,$4
lpe
|
.MODEL SMALL
.STACK 100H
.DATA
;variables
.CODE
MAIN PROC
;initialize DS
MOV AX,@DATA
MOV DS,AX
; enter your code here
;setting counter as 0
mov cl , 0
mov ah , 2
mov dl , '*'
start:
cmp cl , 80 ;checking if counter reached 80
je finish
int 21h ;printing *
inc cl ;incrementing counter
jmp start
finish:
;exit to DOS
MOV AX,4C00H
INT 21H
MAIN ENDP
END MAIN |
; A154241: a(n) = ( (9 + sqrt(6))^n - (9 - sqrt(6))^n )/(2*sqrt(6)).
; Submitted by Jamie Morken(s4)
; 1,18,249,3132,37701,443718,5159349,59589432,685658601,7872647418,90283258449,1034650095732,11852457339501,135745474931118,1554484248297549,17799805849522032,203810186669080401,2333597921329294818,26718998583746276649,305922130407735868332,3502673453558274881301,40103962383468757738518,459170813885567023195749,5257277471180049587134632,60193183439823365828742201,689181491578316865882262218,7890778090422951148725054849,90345393759239355735881320932,1034408730884587067091484663101
add $0,1
mov $2,1
mov $3,$0
lpb $3
mul $1,$3
mul $2,$3
add $1,$2
mul $2,5
mul $4,3
cmp $6,0
add $5,$6
div $1,$5
div $2,$5
add $2,$1
add $4,$1
mul $1,6
sub $3,1
mov $6,0
lpe
mov $0,$4
|
; A178067: Triangle read by rows: T(n,k) = (n^2 + k)*(n - k + 1)/2.
; Submitted by Jamie Morken(w1)
; 1,5,3,15,11,6,34,27,19,10,65,54,42,29,15,111,95,78,60,41,21,175,153,130,106,81,55,28,260,231,201,170,138,105,71,36,369,332,294,255,215,174,132,89,45,505,459,412,364,315,265,214,162,109,55,671,615,558,500,441,381,320,258,195,131,66,870,803,735,666,596,525,453,380,306,231,155,78,1105,1026,946,865,783,700,616,531,445,358,270,181,91,1379,1287,1194,1100,1005,909,812,714,615
lpb $0
add $1,1
sub $0,$1
add $2,1
lpe
add $1,2
mul $1,$2
sub $2,$0
add $0,1
add $1,$0
add $1,1
mul $2,$1
add $2,$1
mov $0,$2
div $0,2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r8
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x9bcc, %rsi
lea addresses_WT_ht+0x39cc, %rdi
clflush (%rsi)
nop
nop
nop
nop
cmp %r8, %r8
mov $48, %rcx
rep movsw
nop
nop
nop
nop
nop
dec %rdi
pop %rsi
pop %rdi
pop %rcx
pop %r8
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r14
push %rcx
// Faulty Load
lea addresses_A+0x183cc, %r14
nop
xor $17024, %r11
mov (%r14), %r13d
lea oracles, %r14
and $0xff, %r13
shlq $12, %r13
mov (%r14,%r13,1), %r13
pop %rcx
pop %r14
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 11, 'type': 'addresses_D_ht'}}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC cpm_00_output_cons_ochar_msg_putc
EXTERN __CPM_WCON
EXTERN asm_cpm_bdos_alt
cpm_00_output_cons_ochar_msg_putc:
; enter : c = char
; exit : carry set if error
; can use : af, bc, de, hl, af'
ld e,c
ld c,__CPM_WCON
call asm_cpm_bdos_alt
or a
ret
|
; A253368: a(n) = F(12*n)/(12^2) with the Fibonacci numbers F = A000045.
; 1,322,103683,33385604,10750060805,3461486193606,1114587804280327,358893811492071688,115562692712642803209,37210828159659490561610,11981771104717643318035211,3858093084890921488916776332,1242293991563772001787883943693,400014807190449693654209713092814,128803525621333237584653739731942415,41474335235262112052564849983972364816,13354607142228778747688297041099369528337,4300142025462431494643579082384013015759698,1384632377591760712496484776230611091705094419
mul $0,3
add $0,2
seq $0,290903 ; p-INVERT of the positive integers, where p(S) = 1 - 5*S.
div $0,40
mul $0,6
sub $0,30
div $0,36
add $0,1
|
/* file: gbt_classification_training_result.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of gradient boosted trees algorithm classes.
//--
*/
#include "algorithms/gradient_boosted_trees/gbt_classification_training_types.h"
#include "serialization_utils.h"
#include "daal_strings.h"
using namespace daal::data_management;
using namespace daal::services;
namespace daal
{
namespace algorithms
{
namespace gbt
{
namespace training { Status checkImpl(const gbt::training::Parameter& prm); }
namespace classification
{
namespace training
{
namespace interface1
{
__DAAL_REGISTER_SERIALIZATION_CLASS(Result, SERIALIZATION_GBT_CLASSIFICATION_TRAINING_RESULT_ID);
Result::Result() : algorithms::classifier::training::Result(classifier::training::lastResultId + 1) {};
gbt::classification::ModelPtr Result::get(classifier::training::ResultId id) const
{
return gbt::classification::Model::cast(algorithms::classifier::training::Result::get(id));
}
void Result::set(classifier::training::ResultId id, const gbt::classification::ModelPtr &value)
{
algorithms::classifier::training::Result::set(id, value);
}
services::Status Result::check(const daal::algorithms::Input *input, const daal::algorithms::Parameter *par, int method) const
{
return algorithms::classifier::training::Result::check(input, par, method);
}
Status Parameter::check() const
{
return gbt::training::checkImpl(*this);
}
} // namespace interface1
namespace interface2
{
Status Parameter::check() const
{
return gbt::training::checkImpl(*this);
}
}
} // namespace training
} // namespace classification
} // namespace gbt
} // namespace algorithms
} // namespace daal
|
%ifndef EXE_LENGTH
%include "../UltimaPatcher.asm"
%include "include/uw1.asm"
%include "include/uw1-eop.asm"
defineAddress 12, 0x0018, tryHandlersInMainLoop
%endif
[bits 16]
startPatch EXE_LENGTH, \
call eop tryKeyAndMouseBindings to respond to multiple simultaneous keys
startBlockAt addr_tryHandlersInMainLoop
push varArgsEopArg(tryKeyAndMouseBindings, 0)
callFromLoadModule varArgsEopDispatcher
add sp, 2
endBlockOfLength 11
endPatch
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_SnowHitImpact_Emitter_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function SnowHitImpact_Emitter.SnowHitImpact_Emitter_C.UserConstructionScript
struct ASnowHitImpact_Emitter_C_UserConstructionScript_Params
{
};
// Function SnowHitImpact_Emitter.SnowHitImpact_Emitter_C.ExecuteUbergraph_SnowHitImpact_Emitter
struct ASnowHitImpact_Emitter_C_ExecuteUbergraph_SnowHitImpact_Emitter_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
;generated via makeasms.bat
include raster.i
include rastlib.i
CGROUP group code
code segment dword 'CODE'
assume cs:CGROUP,ds:CGROUP
RASTMASK_JUMP pj__mask2blit RL_MASK2BLIT
code ends
end
|
#include "Platform.inc"
#include "FarCalls.inc"
#include "PowerOnReset.inc"
#include "TestFixture.inc"
radix decimal
BorPorBitsSetTest code
global testArrange
testArrange:
banksel PCON
clrf PCON
testAct:
fcall initialiseAfterPowerOnReset
testAssert:
banksel PCON
.assert "(pcon & 0x03) == 0x03, 'BOR / POR bits were not set.'"
return
end
|
// Copyright (c) 2012-2013 The Bitcoin Core developers
// Copyright (c) 2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "scheduler.h"
#if defined(HAVE_CONFIG_H)
#include "config/mxdum-config.h"
#else
#define HAVE_WORKING_BOOST_SLEEP_FOR
#endif
#include <boost/bind.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime)
{
{
boost::unique_lock<boost::mutex> lock(mutex);
counter += delta;
}
boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f = boost::bind(µTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
static void MicroSleep(uint64_t n)
{
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::microseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::microseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
BOOST_AUTO_TEST_CASE(manythreads)
{
seed_insecure_rand(false);
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts from one of the counters a
// random amount, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
boost::mutex counterMutex[10];
int counter[10] = { 0 };
boost::random::mt19937 rng(insecure_rand());
boost::random::uniform_int_distribution<> zeroToNine(0, 9);
boost::random::uniform_int_distribution<> randomMsec(-11, 1000);
boost::random::uniform_int_distribution<> randomDelta(-1000, 1000);
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
boost::chrono::system_clock::time_point now = start;
boost::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
MicroSleep(600);
now = boost::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
microThreads.join_all(); // ... wait until all the threads are done
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_SUITE_END()
|
; A206545: Period length 16: repeat 1, 3, 5, 7, 9, 11, 13, 15, 15, 13, 11, 9, 7, 5, 3, 1.
; 1,3,5,7,9,11,13,15,15,13,11,9,7,5,3,1,1,3,5,7,9,11,13,15,15,13,11,9,7,5,3,1,1,3,5,7,9,11,13,15,15,13,11,9,7,5,3,1,1,3,5,7,9,11,13,15,15,13,11,9,7,5,3,1,1,3,5,7,9,11,13,15,15,13,11,9,7,5,3,1
mul $0,2
lpb $0
mov $1,$0
sub $1,31
mov $2,0
gcd $2,$1
sub $2,1
mov $0,$2
lpe
add $0,1
|
; A052994: Expansion of 2x(1-x)/(1-2x-x^2+x^3).
; 0,2,2,6,12,28,62,140,314,706,1586,3564,8008,17994,40432,90850,204138,458694,1030676,2315908,5203798,11692828,26273546,59036122,132652962,298068500,669753840,1504923218,3381531776,7598232930,17073074418
seq $0,106803 ; Expansion of x*(1-x)/(1-2*x-x^2+x^3).
mul $0,2
|
%ifdef CONFIG
{
"RegData": {
"MM0": ["0x8000000000000000", "0x4007"],
"MM1": ["0x8000000000000000", "0x4006"],
"MM2": ["0x8000000000000000", "0x4005"],
"MM3": ["0x8000000000000000", "0x4004"],
"MM4": ["0x8000000000000000", "0x4003"],
"MM5": ["0x8000000000000000", "0x4002"],
"MM6": ["0x8000000000000000", "0x4000"],
"MM7": ["0x8000000000000000", "0x3FFF"]
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x3ff0000000000000 ; 1.0
mov [rdx + 8 * 0], rax
mov rax, 0x4000000000000000 ; 2.0
mov [rdx + 8 * 1], rax
mov rax, 0x4020000000000000 ; 4.0
mov [rdx + 8 * 2], rax
mov rax, 0x4030000000000000
mov [rdx + 8 * 3], rax
mov rax, 0x4040000000000000
mov [rdx + 8 * 4], rax
mov rax, 0x4050000000000000
mov [rdx + 8 * 5], rax
mov rax, 0x4060000000000000
mov [rdx + 8 * 6], rax
mov rax, 0x4070000000000000
mov [rdx + 8 * 7], rax
fld qword [rdx + 8 * 0]
fld qword [rdx + 8 * 1]
fld qword [rdx + 8 * 2]
fld qword [rdx + 8 * 3]
fld qword [rdx + 8 * 4]
fld qword [rdx + 8 * 5]
fld qword [rdx + 8 * 6]
fld qword [rdx + 8 * 7]
fincstp
hlt
|
object_const_def ; object_event constants
const KARENSROOM_KAREN
KarensRoom_MapScripts:
db 2 ; scene scripts
scene_script .LockDoor ; SCENE_DEFAULT
scene_script .DummyScene ; SCENE_FINISHED
db 1 ; callbacks
callback MAPCALLBACK_TILES, .KarensRoomDoors
.LockDoor:
prioritysjump .KarensDoorLocksBehindYou
end
.DummyScene:
end
.KarensRoomDoors:
checkevent EVENT_KARENS_ROOM_ENTRANCE_CLOSED
iffalse .KeepEntranceOpen
changeblock 4, 14, $2a ; wall
.KeepEntranceOpen:
checkevent EVENT_KARENS_ROOM_EXIT_OPEN
iffalse .KeepExitClosed
changeblock 4, 2, $16 ; open door
.KeepExitClosed:
return
.KarensDoorLocksBehindYou:
applymovement PLAYER, KarensRoom_EnterMovement
refreshscreen $86
playsound SFX_STRENGTH
earthquake 80
changeblock 4, 14, $2a ; wall
reloadmappart
closetext
setscene SCENE_FINISHED
setevent EVENT_KARENS_ROOM_ENTRANCE_CLOSED
waitsfx
end
KarenScript_Battle:
faceplayer
opentext
checkevent EVENT_BEAT_ELITE_4_KAREN
iftrue KarenScript_AfterBattle
writetext KarenScript_KarenBeforeText
waitbutton
closetext
winlosstext KarenScript_KarenBeatenText, 0
loadtrainer KAREN, KAREN1
startbattle
reloadmapafterbattle
setevent EVENT_BEAT_ELITE_4_KAREN
opentext
writetext KarenScript_KarenDefeatText
waitbutton
closetext
playsound SFX_ENTER_DOOR
changeblock 4, 2, $16 ; open door
reloadmappart
closetext
setevent EVENT_KARENS_ROOM_EXIT_OPEN
waitsfx
end
KarenScript_AfterBattle:
writetext KarenScript_KarenDefeatText
waitbutton
closetext
end
KarensRoom_EnterMovement:
step UP
step UP
step UP
step UP
step_end
KarenScript_KarenBeforeText:
text "I am KAREN of the"
line "ELITE FOUR."
para "You're <PLAYER>?"
line "How amusing."
para "I love dark-type"
line "#MON."
para "I find their wild,"
line "tough image to be"
para "so appealing. And"
line "they're so strong."
para "Think you can take"
line "them? Just try to"
cont "entertain me."
para "Let's go."
done
KarenScript_KarenBeatenText:
text "Well, aren't you"
line "good. I like that"
cont "in a trainer."
done
KarenScript_KarenDefeatText:
text "Strong #MON."
para "Weak #MON."
para "That is only the"
line "selfish perception"
cont "of people."
para "Truly skilled"
line "trainers should"
para "try to win with"
line "their favorites."
para "I like your style."
line "You understand"
cont "what's important."
para "Go on--the CHAM-"
line "PION is waiting."
done
KarensRoom_MapEvents:
db 0, 0 ; filler
db 4 ; warp events
warp_event 4, 17, BRUNOS_ROOM, 3
warp_event 5, 17, BRUNOS_ROOM, 4
warp_event 4, 2, LANCES_ROOM, 1
warp_event 5, 2, LANCES_ROOM, 2
db 0 ; coord events
db 0 ; bg events
db 1 ; object events
object_event 5, 7, SPRITE_KAREN, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, KarenScript_Battle, -1
|
// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md
#include "py_oiio.h"
#include <memory>
#include <OpenImageIO/platform.h>
namespace PyOpenImageIO {
py::tuple
ImageBuf_getpixel(const ImageBuf& buf, int x, int y, int z = 0,
const std::string& wrapname = "black")
{
ImageBuf::WrapMode wrap = ImageBuf::WrapMode_from_string(wrapname);
int nchans = buf.nchannels();
float* pixel = OIIO_ALLOCA(float, nchans);
buf.getpixel(x, y, z, pixel, nchans, wrap);
return C_to_tuple(pixel, nchans);
}
py::tuple
ImageBuf_interppixel(const ImageBuf& buf, float x, float y,
const std::string& wrapname = "black")
{
ImageBuf::WrapMode wrap = ImageBuf::WrapMode_from_string(wrapname);
int nchans = buf.nchannels();
float* pixel = OIIO_ALLOCA(float, nchans);
buf.interppixel(x, y, pixel, wrap);
return C_to_tuple(pixel, nchans);
}
py::tuple
ImageBuf_interppixel_NDC(const ImageBuf& buf, float x, float y,
const std::string& wrapname = "black")
{
ImageBuf::WrapMode wrap = ImageBuf::WrapMode_from_string(wrapname);
int nchans = buf.nchannels();
float* pixel = OIIO_ALLOCA(float, nchans);
buf.interppixel_NDC(x, y, pixel, wrap);
return C_to_tuple(pixel, nchans);
}
py::tuple
ImageBuf_interppixel_bicubic(const ImageBuf& buf, float x, float y,
const std::string& wrapname = "black")
{
ImageBuf::WrapMode wrap = ImageBuf::WrapMode_from_string(wrapname);
int nchans = buf.nchannels();
float* pixel = OIIO_ALLOCA(float, nchans);
buf.interppixel_bicubic(x, y, pixel, wrap);
return C_to_tuple(pixel, nchans);
}
py::tuple
ImageBuf_interppixel_bicubic_NDC(const ImageBuf& buf, float x, float y,
const std::string& wrapname = "black")
{
ImageBuf::WrapMode wrap = ImageBuf::WrapMode_from_string(wrapname);
int nchans = buf.nchannels();
float* pixel = OIIO_ALLOCA(float, nchans);
buf.interppixel_bicubic_NDC(x, y, pixel, wrap);
return C_to_tuple(pixel, nchans);
}
void
ImageBuf_setpixel(ImageBuf& buf, int x, int y, int z, py::object p)
{
std::vector<float> pixel;
py_to_stdvector(pixel, p);
if (pixel.size())
buf.setpixel(x, y, z, pixel);
}
void
ImageBuf_setpixel2(ImageBuf& buf, int x, int y, py::object p)
{
ImageBuf_setpixel(buf, x, y, 0, p);
}
void
ImageBuf_setpixel1(ImageBuf& buf, int i, py::object p)
{
std::vector<float> pixel;
py_to_stdvector(pixel, p);
if (pixel.size())
buf.setpixel(i, pixel);
}
py::object
ImageBuf_get_pixels(const ImageBuf& buf, TypeDesc format, ROI roi = ROI::All())
{
// Allocate our own temp buffer and try to read the image into it.
// If the read fails, return None.
if (!roi.defined())
roi = buf.roi();
roi.chend = std::min(roi.chend, buf.nchannels());
size_t size = (size_t)roi.npixels() * roi.nchannels() * format.size();
std::unique_ptr<char[]> data(new char[size]);
if (buf.get_pixels(roi, format, &data[0]))
return make_numpy_array(format, data.release(),
buf.spec().depth > 1 ? 4 : 3, roi.nchannels(),
roi.width(), roi.height(), roi.depth());
else
return py::none();
}
void
ImageBuf_set_deep_value(ImageBuf& buf, int x, int y, int z, int c, int s,
float value)
{
buf.set_deep_value(x, y, z, c, s, value);
}
void
ImageBuf_set_deep_value_uint(ImageBuf& buf, int x, int y, int z, int c, int s,
uint32_t value)
{
buf.set_deep_value(x, y, z, c, s, value);
}
bool
ImageBuf_set_pixels_buffer(ImageBuf& self, ROI roi, py::buffer& buffer)
{
if (!roi.defined())
roi = self.roi();
roi.chend = std::min(roi.chend, self.nchannels());
size_t size = (size_t)roi.npixels() * roi.nchannels();
if (size == 0) {
return true; // done
}
oiio_bufinfo buf(buffer.request(), roi.nchannels(), roi.width(),
roi.height(), roi.depth(), self.spec().depth > 1 ? 3 : 2);
if (!buf.data || buf.error.size()) {
self.errorfmt("set_pixels error: {}",
buf.error.size() ? buf.error.c_str() : "unspecified");
return false; // failed sanity checks
}
if (!buf.data || buf.size != size) {
self.errorfmt(
"ImageBuf.set_pixels: array size ({}) did not match ROI size w={} h={} d={} ch={} (total {})",
buf.size, roi.width(), roi.height(), roi.depth(), roi.nchannels(),
size);
return false;
}
py::gil_scoped_release gil;
return self.set_pixels(roi, buf.format, buf.data, buf.xstride, buf.ystride,
buf.zstride);
}
void
ImageBuf_set_write_format(ImageBuf& self, const py::object& py_channelformats)
{
std::vector<TypeDesc> formats;
py_to_stdvector(formats, py_channelformats);
self.set_write_format(formats);
}
void
declare_imagebuf(py::module& m)
{
using namespace pybind11::literals;
py::class_<ImageBuf>(m, "ImageBuf")
.def(py::init<>())
.def(py::init<const std::string&>())
.def(py::init<const std::string&, int, int>())
.def(py::init<const ImageSpec&>())
.def(py::init([](const ImageSpec& spec, bool zero) {
auto z = zero ? InitializePixels::Yes : InitializePixels::No;
return ImageBuf(spec, z);
}))
.def(py::init([](const std::string& name, int subimage, int miplevel,
const ImageSpec& config) {
return ImageBuf(name, subimage, miplevel, nullptr, &config);
}),
"name"_a, "subimage"_a, "miplevel"_a, "config"_a)
.def("clear", &ImageBuf::clear)
.def(
"reset",
[](ImageBuf& self, const std::string& name, int subimage,
int miplevel) { self.reset(name, subimage, miplevel); },
"name"_a, "subimage"_a = 0, "miplevel"_a = 0)
.def(
"reset",
[](ImageBuf& self, const std::string& name, int subimage,
int miplevel, const ImageSpec& config) {
self.reset(name, subimage, miplevel, nullptr, &config);
},
"name"_a, "subimage"_a = 0, "miplevel"_a = 0,
"config"_a = ImageSpec())
.def(
"reset",
[](ImageBuf& self, const ImageSpec& spec, bool zero) {
auto z = zero ? InitializePixels::Yes : InitializePixels::No;
self.reset(spec, z);
},
"spec"_a, "zero"_a = true)
.def_property_readonly("initialized",
[](const ImageBuf& self) {
return self.initialized();
})
.def(
"init_spec",
[](ImageBuf& self, std::string filename, int subimage,
int miplevel) {
py::gil_scoped_release gil;
self.init_spec(filename, subimage, miplevel);
},
"filename"_a, "subimage"_a = 0, "miplevel"_a = 0)
.def(
"read",
[](ImageBuf& self, int subimage, int miplevel, int chbegin,
int chend, bool force, TypeDesc convert) {
py::gil_scoped_release gil;
return self.read(subimage, miplevel, chbegin, chend, force,
convert);
},
"subimage"_a, "miplevel"_a, "chbegin"_a, "chend"_a, "force"_a,
"convert"_a)
.def(
"read",
[](ImageBuf& self, int subimage, int miplevel, bool force,
TypeDesc convert) {
py::gil_scoped_release gil;
return self.read(subimage, miplevel, force, convert);
},
"subimage"_a = 0, "miplevel"_a = 0, "force"_a = false,
"convert"_a = TypeUnknown)
.def(
"write",
[](ImageBuf& self, const std::string& filename, TypeDesc dtype,
const std::string& fileformat) {
py::gil_scoped_release gil;
return self.write(filename, dtype, fileformat);
},
"filename"_a, "dtype"_a = TypeUnknown, "fileformat"_a = "")
.def(
"write",
[](ImageBuf& self, ImageOutput& out) {
py::gil_scoped_release gil;
return self.write(&out);
},
"out"_a)
.def(
"make_writable",
[](ImageBuf& self, bool keep_cache_type) {
py::gil_scoped_release gil;
return self.make_writable(keep_cache_type);
},
"keep_cache_type"_a = false)
// DEPRECATED(2.2): nonstandard spelling
.def(
"make_writeable",
[](ImageBuf& self, bool keep_cache_type) {
py::gil_scoped_release gil;
return self.make_writable(keep_cache_type);
},
"keep_cache_type"_a = false)
.def("set_write_format", &ImageBuf_set_write_format)
// FIXME -- write(ImageOut&)
.def("set_write_tiles", &ImageBuf::set_write_tiles, "width"_a = 0,
"height"_a = 0, "depth"_a = 0)
.def("spec", &ImageBuf::spec,
py::return_value_policy::reference_internal)
.def("nativespec", &ImageBuf::nativespec,
py::return_value_policy::reference_internal)
.def("specmod", &ImageBuf::specmod,
py::return_value_policy::reference_internal)
.def_property_readonly("has_thumbnail",
[](const ImageBuf& self) {
return self.has_thumbnail();
})
.def("clear_thumbnail", &ImageBuf::clear_thumbnail)
.def("set_thumbnail", &ImageBuf::set_thumbnail, "thumb"_a)
.def("get_thumbnail",
[](const ImageBuf& self) { return *self.get_thumbnail(); })
.def_property_readonly("name",
[](const ImageBuf& self) {
return PY_STR(self.name());
})
.def_property_readonly("file_format_name",
[](const ImageBuf& self) {
return PY_STR(self.file_format_name());
})
.def_property_readonly("subimage", &ImageBuf::subimage)
.def_property_readonly("nsubimages", &ImageBuf::nsubimages)
.def_property_readonly("miplevel", &ImageBuf::miplevel)
.def_property_readonly("nmiplevels", &ImageBuf::nmiplevels)
.def_property_readonly("nchannels", &ImageBuf::nchannels)
.def_property("orientation", &ImageBuf::orientation,
&ImageBuf::set_orientation)
.def_property_readonly("oriented_width", &ImageBuf::oriented_width)
.def_property_readonly("oriented_height", &ImageBuf::oriented_height)
.def_property_readonly("oriented_x", &ImageBuf::oriented_x)
.def_property_readonly("oriented_y", &ImageBuf::oriented_y)
.def_property_readonly("oriented_full_width",
&ImageBuf::oriented_full_width)
.def_property_readonly("oriented_full_height",
&ImageBuf::oriented_full_height)
.def_property_readonly("oriented_full_x", &ImageBuf::oriented_full_x)
.def_property_readonly("oriented_full_y", &ImageBuf::oriented_full_y)
.def_property_readonly("xbegin", &ImageBuf::xbegin)
.def_property_readonly("xend", &ImageBuf::xend)
.def_property_readonly("ybegin", &ImageBuf::ybegin)
.def_property_readonly("yend", &ImageBuf::yend)
.def_property_readonly("zbegin", &ImageBuf::zbegin)
.def_property_readonly("zend", &ImageBuf::zend)
.def_property_readonly("xmin", &ImageBuf::xmin)
.def_property_readonly("xmax", &ImageBuf::xmax)
.def_property_readonly("ymin", &ImageBuf::ymin)
.def_property_readonly("ymax", &ImageBuf::ymax)
.def_property_readonly("zmin", &ImageBuf::zmin)
.def_property_readonly("zmax", &ImageBuf::zmax)
.def_property_readonly("roi", &ImageBuf::roi)
.def_property("roi_full", &ImageBuf::roi_full, &ImageBuf::set_roi_full)
.def("set_origin", &ImageBuf::set_origin, "x"_a, "y"_a, "z"_a = 0)
.def("set_full", &ImageBuf::set_full)
.def_property_readonly("pixels_valid", &ImageBuf::pixels_valid)
.def_property_readonly("pixeltype", &ImageBuf::pixeltype)
.def_property_readonly("has_error", &ImageBuf::has_error)
.def(
"geterror",
[](const ImageBuf& self, bool clear) {
return PY_STR(self.geterror(clear));
},
"clear"_a = true)
.def("pixelindex", &ImageBuf::pixelindex, "x"_a, "y"_a, "z"_a,
"check_range"_a = false)
.def("copy_metadata", &ImageBuf::copy_metadata)
.def("copy_pixels", &ImageBuf::copy_pixels)
.def(
"copy",
[](ImageBuf& self, const ImageBuf& src, TypeDesc format) {
py::gil_scoped_release gil;
return self.copy(src, format);
},
"src"_a, "format"_a = TypeUnknown)
.def(
"copy",
[](const ImageBuf& src, TypeDesc format) {
py::gil_scoped_release gil;
return src.copy(format);
},
"format"_a = TypeUnknown)
.def("swap", &ImageBuf::swap)
.def("getchannel", &ImageBuf::getchannel, "x"_a, "y"_a, "z"_a, "c"_a,
"wrap"_a = "black")
.def("getpixel", &ImageBuf_getpixel, "x"_a, "y"_a, "z"_a = 0,
"wrap"_a = "black")
.def("interppixel", &ImageBuf_interppixel, "x"_a, "y"_a,
"wrap"_a = "black")
.def("interppixel_NDC", &ImageBuf_interppixel_NDC, "x"_a, "y"_a,
"wrap"_a = "black")
.def("interppixel_NDC_full", &ImageBuf_interppixel_NDC, "x"_a, "y"_a,
"wrap"_a = "black")
.def("interppixel_bicubic", &ImageBuf_interppixel_bicubic, "x"_a, "y"_a,
"wrap"_a = "black")
.def("interppixel_bicubic_NDC", &ImageBuf_interppixel_bicubic_NDC,
"x"_a, "y"_a, "wrap"_a = "black")
.def("setpixel", &ImageBuf_setpixel, "x"_a, "y"_a, "z"_a, "pixel"_a)
.def("setpixel", &ImageBuf_setpixel2, "x"_a, "y"_a, "pixel"_a)
.def("setpixel", &ImageBuf_setpixel1, "i"_a, "pixel"_a)
.def("get_pixels", &ImageBuf_get_pixels, "format"_a = TypeFloat,
"roi"_a = ROI::All())
.def("set_pixels", &ImageBuf_set_pixels_buffer, "roi"_a, "pixels"_a)
.def_property_readonly("deep", &ImageBuf::deep)
.def("deep_samples", &ImageBuf::deep_samples, "x"_a, "y"_a, "z"_a = 0)
.def("set_deep_samples", &ImageBuf::set_deep_samples, "x"_a, "y"_a,
"z"_a = 0, "nsamples"_a = 1)
.def("deep_insert_samples", &ImageBuf::deep_insert_samples, "x"_a,
"y"_a, "z"_a = 0, "samplepos"_a, "nsamples"_a = 1)
.def("deep_erase_samples", &ImageBuf::deep_erase_samples, "x"_a, "y"_a,
"z"_a = 0, "samplepos"_a, "nsamples"_a = 1)
.def("deep_value", &ImageBuf::deep_value, "x"_a, "y"_a, "z"_a,
"channel"_a, "sample"_a)
.def("deep_value_uint", &ImageBuf::deep_value_uint, "x"_a, "y"_a, "z"_a,
"channel"_a, "sample"_a)
.def("set_deep_value", &ImageBuf_set_deep_value, "x"_a, "y"_a, "z"_a,
"channel"_a, "sample"_a, "value"_a = 0.0f)
.def("set_deep_value_uint", &ImageBuf_set_deep_value_uint, "x"_a, "y"_a,
"z"_a, "channel"_a, "sample"_a, "value"_a = 0)
.def(
"deepdata", [](ImageBuf& self) { return *self.deepdata(); },
py::return_value_policy::reference_internal)
// FIXME -- do we want to provide pixel iterators?
;
}
} // namespace PyOpenImageIO
|
SECTION code_fp_math48
PUBLIC atanh
EXTERN cm48_sccz80_atanh
defc atanh = cm48_sccz80_atanh
|
%include "common.inc"
global i.cpuvendor:function
global cpuinfo:function
global i.cpufeature_available:function
section .text
i.cpuvendor:
push rbx ; Save registers used to stack.
push rcx
push rdx
xor rax, rax ; Set RAX = 0.
cpuid ; CPUID with RAX = 0, get CPU vendor.
mov qword [rdi], rbx ; Record vendor to first argument.
mov qword [rdi + 4], rdx
mov qword [rdi + 8], rcx
pop rdx ; Antisave registers used.
pop rcx
pop rbx
ret
cpuinfo:
push rcx
push rbx
push r9
xor rax, rax ; Set RAX = 0.
inc rax ; Actually, set RAX = 1.
mov r9, rdx
cpuid ; CPUID with RAX = 1, get CPU information.
mov dword [rdi], edx
mov dword [rsi], ecx
mov dword [r9], ebx
mov rdx, r9
pop r9
pop rcx
pop rdx
ret
i.cpufeature_available:
push rdx ; Save registers used to stack.
push rbx
push rcx
xor rax, rax
inc rax ; Set RAX = 1.
cpuid ; CPUID with RAX = 1, get CPU information.
cmp rsi, 1 ; ECX feature set?
cmove rdx, rcx ; If so, RDX = RCX.
%ifdef level3 ; If AMD64-v3
shrx rax, rdx, rdi ; RAX = RDX >> RDI, RDI is first argument, RAX is return.
%else ; If less than AMD64-v3
mov rcx, rdi ; Set RCX to value of first argument.
mov rax, rdx ; Set return register to RDX, the feature set.
shr rax, cl ; Shift the feature set by first argument
%endif
pop rcx ; Antisave registers used.
pop rbx
pop rdx
ret
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "vectorise/fixed_point/fixed_point.hpp"
#include "gtest/gtest.h"
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
using namespace fetch::fixed_point;
TEST(FixedPointTest, Conversion_16_16)
{
// Positive
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
EXPECT_EQ(static_cast<int>(one), 1);
EXPECT_EQ(static_cast<int>(two), 2);
EXPECT_EQ(static_cast<float>(one), 1.0f);
EXPECT_EQ(static_cast<float>(two), 2.0f);
EXPECT_EQ(static_cast<double>(one), 1.0);
EXPECT_EQ(static_cast<double>(two), 2.0);
// Negative
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one), -1);
EXPECT_EQ(static_cast<int>(m_two), -2);
EXPECT_EQ(static_cast<float>(m_one), -1.0f);
EXPECT_EQ(static_cast<float>(m_two), -2.0f);
EXPECT_EQ(static_cast<double>(m_one), -1.0);
EXPECT_EQ(static_cast<double>(m_two), -2.0);
// _0
FixedPoint<16, 16> zero(0);
FixedPoint<16, 16> m_zero(-0);
EXPECT_EQ(static_cast<int>(zero), 0);
EXPECT_EQ(static_cast<int>(m_zero), 0);
EXPECT_EQ(static_cast<float>(zero), 0.0f);
EXPECT_EQ(static_cast<float>(m_zero), 0.0f);
EXPECT_EQ(static_cast<double>(zero), 0.0);
EXPECT_EQ(static_cast<double>(m_zero), 0.0);
// Get raw value
FixedPoint<16, 16> zero_point_five(0.5);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> two_point_five(2.5);
FixedPoint<16, 16> m_one_point_five(-1.5);
EXPECT_EQ(zero_point_five.Data(), 0x08000);
EXPECT_EQ(one.Data(), 0x10000);
EXPECT_EQ(one_point_five.Data(), 0x18000);
EXPECT_EQ(two_point_five.Data(), 0x28000);
// Convert from raw value
FixedPoint<16, 16> two_point_five_raw(2, 0x08000);
FixedPoint<16, 16> m_two_point_five_raw(-2, 0x08000);
EXPECT_EQ(two_point_five, two_point_five_raw);
EXPECT_EQ(m_one_point_five, m_two_point_five_raw);
// Extreme cases:
// smallest possible double representable to a FixedPoint
FixedPoint<16, 16> infinitesimal(0.00002);
// Largest fractional closest to one, representable to a FixedPoint
FixedPoint<16, 16> almost_one(0.99999);
// Largest fractional closest to one, representable to a FixedPoint
FixedPoint<16, 16> largest_int(std::numeric_limits<int16_t>::max());
// Smallest possible integer, increase by one, in order to allow for the fractional part.
FixedPoint<16, 16> smallest_int(std::numeric_limits<int16_t>::min());
// Largest possible Fixed Point number.
FixedPoint<16, 16> largest_fixed_point = largest_int + almost_one;
// Smallest possible Fixed Point number.
FixedPoint<16, 16> smallest_fixed_point = smallest_int + almost_one;
EXPECT_EQ(infinitesimal.Data(), fp32_t::SMALLEST_FRACTION);
EXPECT_EQ(almost_one.Data(), fp32_t::LARGEST_FRACTION);
EXPECT_EQ(largest_int.Data(), fp32_t::MAX_INT);
EXPECT_EQ(smallest_int.Data(), fp32_t::MIN_INT);
EXPECT_EQ(largest_fixed_point.Data(), fp32_t::MAX);
EXPECT_EQ(smallest_fixed_point.Data(), fp32_t::MIN);
EXPECT_EQ(fp32_t::MIN, 0x8000ffff);
EXPECT_EQ(fp32_t::MAX, 0x7fffffff);
// We cannot be smaller than the actual negative integer of the actual type
EXPECT_TRUE(smallest_fixed_point.Data() > std::numeric_limits<int32_t>::min());
// On the other hand we expect to be exactly the same as the largest positive integer of int64_t
EXPECT_TRUE(largest_fixed_point.Data() == std::numeric_limits<int32_t>::max());
EXPECT_EQ(sizeof(one), 4);
EXPECT_EQ(static_cast<int>(one), 1);
EXPECT_EQ(static_cast<unsigned>(one), 1);
EXPECT_EQ(static_cast<int32_t>(one), 1);
EXPECT_EQ(static_cast<uint32_t>(one), 1);
EXPECT_EQ(static_cast<long>(one), 1);
EXPECT_EQ(static_cast<unsigned long>(one), 1);
EXPECT_EQ(static_cast<int64_t>(one), 1);
EXPECT_EQ(static_cast<uint64_t>(one), 1);
EXPECT_EQ(fp32_t::TOLERANCE.Data(), 0x15);
EXPECT_EQ(fp32_t::DECIMAL_DIGITS, 4);
}
TEST(FixedPointTest, Conversion_32_32)
{
// Positive
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
EXPECT_EQ(static_cast<int>(one), 1);
EXPECT_EQ(static_cast<int>(two), 2);
EXPECT_EQ(static_cast<float>(one), 1.0f);
EXPECT_EQ(static_cast<float>(two), 2.0f);
EXPECT_EQ(static_cast<double>(one), 1.0);
EXPECT_EQ(static_cast<double>(two), 2.0);
// Negative
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one), -1);
EXPECT_EQ(static_cast<int>(m_two), -2);
EXPECT_EQ(static_cast<float>(m_one), -1.0f);
EXPECT_EQ(static_cast<float>(m_two), -2.0f);
EXPECT_EQ(static_cast<double>(m_one), -1.0);
EXPECT_EQ(static_cast<double>(m_two), -2.0);
// _0
FixedPoint<32, 32> zero(0);
FixedPoint<32, 32> m_zero(-0);
EXPECT_EQ(static_cast<int>(zero), 0);
EXPECT_EQ(static_cast<int>(m_zero), 0);
EXPECT_EQ(static_cast<float>(zero), 0.0f);
EXPECT_EQ(static_cast<float>(m_zero), 0.0f);
EXPECT_EQ(static_cast<double>(zero), 0.0);
EXPECT_EQ(static_cast<double>(m_zero), 0.0);
// Get raw value
FixedPoint<32, 32> zero_point_five(0.5);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> two_point_five(2.5);
FixedPoint<32, 32> m_one_point_five(-1.5);
EXPECT_EQ(zero_point_five.Data(), 0x080000000);
EXPECT_EQ(one.Data(), 0x100000000);
EXPECT_EQ(one_point_five.Data(), 0x180000000);
EXPECT_EQ(two_point_five.Data(), 0x280000000);
// Convert from raw value
FixedPoint<32, 32> two_point_five_raw(2, 0x080000000);
FixedPoint<32, 32> m_two_point_five_raw(-2, 0x080000000);
EXPECT_EQ(two_point_five, two_point_five_raw);
EXPECT_EQ(m_one_point_five, m_two_point_five_raw);
// Extreme cases:
// smallest possible double representable to a FixedPoint
FixedPoint<32, 32> infinitesimal(0.0000000004);
// Largest fractional closest to one, representable to a FixedPoint
FixedPoint<32, 32> almost_one(0.9999999998);
// Largest fractional closest to one, representable to a FixedPoint
FixedPoint<32, 32> largest_int(std::numeric_limits<int32_t>::max());
// Smallest possible integer, increase by one, in order to allow for the fractional part.
FixedPoint<32, 32> smallest_int(std::numeric_limits<int32_t>::min());
// Largest possible Fixed Point number.
FixedPoint<32, 32> largest_fixed_point = largest_int + almost_one;
// Smallest possible Fixed Point number.
FixedPoint<32, 32> smallest_fixed_point = smallest_int + almost_one;
EXPECT_EQ(infinitesimal.Data(), fp64_t::SMALLEST_FRACTION);
EXPECT_EQ(almost_one.Data(), fp64_t::LARGEST_FRACTION);
EXPECT_EQ(largest_int.Data(), fp64_t::MAX_INT);
EXPECT_EQ(smallest_int.Data(), fp64_t::MIN_INT);
EXPECT_EQ(largest_fixed_point.Data(), fp64_t::MAX);
EXPECT_EQ(smallest_fixed_point.Data(), fp64_t::MIN);
EXPECT_EQ(fp64_t::MIN, 0x80000000ffffffff);
EXPECT_EQ(fp64_t::MAX, 0x7fffffffffffffff);
// We cannot be smaller than the actual negative integer of the actual type
EXPECT_TRUE(smallest_fixed_point.Data() > std::numeric_limits<int64_t>::min());
// On the other hand we expect to be exactly the same as the largest positive integer of int64_t
EXPECT_TRUE(largest_fixed_point.Data() == std::numeric_limits<int64_t>::max());
EXPECT_EQ(sizeof(one), 8);
EXPECT_EQ(static_cast<int>(one), 1);
EXPECT_EQ(static_cast<unsigned>(one), 1);
EXPECT_EQ(static_cast<int32_t>(one), 1);
EXPECT_EQ(static_cast<uint32_t>(one), 1);
EXPECT_EQ(static_cast<long>(one), 1);
EXPECT_EQ(static_cast<uint64_t>(one), 1);
EXPECT_EQ(static_cast<int64_t>(one), 1);
EXPECT_EQ(static_cast<uint64_t>(one), 1);
EXPECT_EQ(fp64_t::TOLERANCE.Data(), 0x200);
EXPECT_EQ(fp64_t::DECIMAL_DIGITS, 9);
}
TEST(FixedPointTest, Addition_16_16)
{
// Positive
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
EXPECT_EQ(static_cast<int>(one + two), 3);
EXPECT_EQ(static_cast<float>(one + two), 3.0f);
EXPECT_EQ(static_cast<double>(one + two), 3.0);
// Negative
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one + one), 0);
EXPECT_EQ(static_cast<int>(m_one + m_two), -3);
EXPECT_EQ(static_cast<float>(m_one + one), 0.0f);
EXPECT_EQ(static_cast<float>(m_one + m_two), -3.0f);
EXPECT_EQ(static_cast<double>(m_one + one), 0.0);
EXPECT_EQ(static_cast<double>(m_one + m_two), -3.0);
FixedPoint<16, 16> another{one};
++another;
EXPECT_EQ(another, two);
// _0
FixedPoint<16, 16> zero(0);
FixedPoint<16, 16> m_zero(-0);
EXPECT_EQ(static_cast<int>(zero), 0);
EXPECT_EQ(static_cast<int>(m_zero), 0);
EXPECT_EQ(static_cast<float>(zero), 0.0f);
EXPECT_EQ(static_cast<float>(m_zero), 0.0f);
EXPECT_EQ(static_cast<double>(zero), 0.0);
EXPECT_EQ(static_cast<double>(m_zero), 0.0);
// Infinitesimal additions
FixedPoint<16, 16> almost_one(0, fp64_t::LARGEST_FRACTION);
FixedPoint<16, 16> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
// Largest possible fraction and smallest possible fraction should make us the value of 1
EXPECT_EQ(almost_one + infinitesimal, one);
// The same for negative
EXPECT_EQ(-almost_one - infinitesimal, m_one);
}
TEST(FixedPointTest, Addition_32_32)
{
// Positive
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
EXPECT_EQ(static_cast<int>(one + two), 3);
EXPECT_EQ(static_cast<float>(one + two), 3.0f);
EXPECT_EQ(static_cast<double>(one + two), 3.0);
// Negative
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one + one), 0);
EXPECT_EQ(static_cast<int>(m_one + m_two), -3);
EXPECT_EQ(static_cast<float>(m_one + one), 0.0f);
EXPECT_EQ(static_cast<float>(m_one + m_two), -3.0f);
EXPECT_EQ(static_cast<double>(m_one + one), 0.0);
EXPECT_EQ(static_cast<double>(m_one + m_two), -3.0);
// _0
FixedPoint<32, 32> zero(0);
FixedPoint<32, 32> m_zero(-0);
EXPECT_EQ(static_cast<int>(zero), 0);
EXPECT_EQ(static_cast<int>(m_zero), 0);
EXPECT_EQ(static_cast<float>(zero), 0.0f);
EXPECT_EQ(static_cast<float>(m_zero), 0.0f);
EXPECT_EQ(static_cast<double>(zero), 0.0);
EXPECT_EQ(static_cast<double>(m_zero), 0.0);
// Infinitesimal additions
FixedPoint<32, 32> almost_one(0, fp64_t::LARGEST_FRACTION);
FixedPoint<32, 32> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
// Largest possible fraction and smallest possible fraction should make us the value of 1
EXPECT_EQ(almost_one + infinitesimal, one);
// The same for negative
EXPECT_EQ(-almost_one - infinitesimal, m_one);
}
TEST(FixedPointTest, Subtraction_16_16)
{
// Positive
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
EXPECT_EQ(static_cast<int>(two - one), 1);
EXPECT_EQ(static_cast<float>(two - one), 1.0f);
EXPECT_EQ(static_cast<double>(two - one), 1.0);
EXPECT_EQ(static_cast<int>(one - two), -1);
EXPECT_EQ(static_cast<float>(one - two), -1.0f);
EXPECT_EQ(static_cast<double>(one - two), -1.0);
// Negative
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one - one), -2);
EXPECT_EQ(static_cast<int>(m_one - m_two), 1);
EXPECT_EQ(static_cast<float>(m_one - one), -2.0f);
EXPECT_EQ(static_cast<float>(m_one - m_two), 1.0f);
EXPECT_EQ(static_cast<double>(m_one - one), -2.0);
EXPECT_EQ(static_cast<double>(m_one - m_two), 1.0);
// Fractions
FixedPoint<16, 16> almost_three(2, fp32_t::LARGEST_FRACTION);
FixedPoint<16, 16> almost_two(1, fp32_t::LARGEST_FRACTION);
EXPECT_EQ(almost_three - almost_two, one);
}
TEST(FixedPointTest, Subtraction_32_32)
{
// Positive
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
EXPECT_EQ(static_cast<int>(two - one), 1);
EXPECT_EQ(static_cast<float>(two - one), 1.0f);
EXPECT_EQ(static_cast<double>(two - one), 1.0);
EXPECT_EQ(static_cast<int>(one - two), -1);
EXPECT_EQ(static_cast<float>(one - two), -1.0f);
EXPECT_EQ(static_cast<double>(one - two), -1.0);
// Negative
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> m_two(-2);
EXPECT_EQ(static_cast<int>(m_one - one), -2);
EXPECT_EQ(static_cast<int>(m_one - m_two), 1);
EXPECT_EQ(static_cast<float>(m_one - one), -2.0f);
EXPECT_EQ(static_cast<float>(m_one - m_two), 1.0f);
EXPECT_EQ(static_cast<double>(m_one - one), -2.0);
EXPECT_EQ(static_cast<double>(m_one - m_two), 1.0);
// Fractions
FixedPoint<32, 32> almost_three(2, fp64_t::LARGEST_FRACTION);
FixedPoint<32, 32> almost_two(1, fp64_t::LARGEST_FRACTION);
EXPECT_EQ(almost_three - almost_two, one);
}
TEST(FixedPointTest, Multiplication_16_16)
{
// Positive
FixedPoint<16, 16> zero(0);
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
FixedPoint<16, 16> three(3);
FixedPoint<16, 16> m_one(-1);
EXPECT_EQ(two * one, two);
EXPECT_EQ(one * 2, 2);
EXPECT_EQ(m_one * zero, zero);
EXPECT_EQ(m_one * one, m_one);
EXPECT_EQ(static_cast<float>(two * 2.0f), 4.0f);
EXPECT_EQ(static_cast<double>(three * 2.0), 6.0);
EXPECT_EQ(static_cast<int>(one * two), 2);
EXPECT_EQ(static_cast<float>(one * two), 2.0f);
EXPECT_EQ(static_cast<double>(one * two), 2.0);
EXPECT_EQ(static_cast<int>(two * zero), 0);
EXPECT_EQ(static_cast<float>(two * zero), 0.0f);
EXPECT_EQ(static_cast<double>(two * zero), 0.0);
// Extreme cases
FixedPoint<16, 16> almost_one(0, fp64_t::LARGEST_FRACTION);
FixedPoint<16, 16> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<16, 16> huge(0x4000, 0);
FixedPoint<16, 16> small(0, 0x4000);
EXPECT_EQ(almost_one * almost_one, almost_one - infinitesimal);
EXPECT_EQ(almost_one * infinitesimal, zero);
EXPECT_EQ(huge * infinitesimal, small);
// (One of) largest possible multiplications
}
TEST(FixedPointTest, Multiplication_32_32)
{
// Positive
FixedPoint<32, 32> zero(0);
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
FixedPoint<32, 32> three(3);
FixedPoint<32, 32> m_one(-1);
EXPECT_EQ(two * one, two);
EXPECT_EQ(one * 2, 2);
EXPECT_EQ(m_one * zero, zero);
EXPECT_EQ(m_one * one, m_one);
EXPECT_EQ(static_cast<float>(two * 2.0f), 4.0f);
EXPECT_EQ(static_cast<double>(three * 2.0), 6.0);
EXPECT_EQ(static_cast<int>(one * two), 2);
EXPECT_EQ(static_cast<float>(one * two), 2.0f);
EXPECT_EQ(static_cast<double>(one * two), 2.0);
EXPECT_EQ(static_cast<int>(two * zero), 0);
EXPECT_EQ(static_cast<float>(two * zero), 0.0f);
EXPECT_EQ(static_cast<double>(two * zero), 0.0);
// Extreme cases
FixedPoint<32, 32> almost_one(0, fp64_t::LARGEST_FRACTION);
FixedPoint<32, 32> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<32, 32> huge(0x40000000, 0);
FixedPoint<32, 32> small(0, 0x40000000);
EXPECT_EQ(almost_one * almost_one, almost_one - infinitesimal);
EXPECT_EQ(almost_one * infinitesimal, zero);
EXPECT_EQ(huge * infinitesimal, small);
}
TEST(FixedPointTest, Division_16_16)
{
// Positive
FixedPoint<16, 16> zero(0);
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
EXPECT_EQ(static_cast<int>(two / one), 2);
EXPECT_EQ(static_cast<float>(two / one), 2.0f);
EXPECT_EQ(static_cast<double>(two / one), 2.0);
EXPECT_EQ(static_cast<int>(one / two), 0);
EXPECT_EQ(static_cast<float>(one / two), 0.5f);
EXPECT_EQ(static_cast<double>(one / two), 0.5);
// Extreme cases
FixedPoint<16, 16> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<16, 16> huge(0x4000, 0);
FixedPoint<16, 16> small(0, 0x4000);
EXPECT_EQ(small / infinitesimal, huge);
EXPECT_EQ(infinitesimal / one, infinitesimal);
EXPECT_EQ(one / huge, infinitesimal * 4);
EXPECT_EQ(huge / infinitesimal, zero);
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(two / zero));
EXPECT_TRUE(fp32_t::IsStateDivisionByZero());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(zero / zero));
EXPECT_TRUE(fp32_t::IsStateNaN());
}
TEST(FixedPointTest, Division_32_32)
{
// Positive
FixedPoint<32, 32> zero(0);
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
EXPECT_EQ(static_cast<int>(two / one), 2);
EXPECT_EQ(static_cast<float>(two / one), 2.0f);
EXPECT_EQ(static_cast<double>(two / one), 2.0);
EXPECT_EQ(static_cast<int>(one / two), 0);
EXPECT_EQ(static_cast<float>(one / two), 0.5f);
EXPECT_EQ(static_cast<double>(one / two), 0.5);
// Extreme cases
FixedPoint<32, 32> infinitesimal(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<32, 32> huge(0x40000000, 0);
FixedPoint<32, 32> small(0, 0x40000000);
EXPECT_EQ(small / infinitesimal, huge);
EXPECT_EQ(infinitesimal / one, infinitesimal);
EXPECT_EQ(one / huge, infinitesimal * 4);
EXPECT_EQ(huge / infinitesimal, zero);
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(two / zero));
EXPECT_TRUE(fp64_t::IsStateDivisionByZero());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(zero / zero));
EXPECT_TRUE(fp64_t::IsStateNaN());
}
TEST(FixedPointTest, Comparison_16_16)
{
FixedPoint<16, 16> zero(0);
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
EXPECT_TRUE(zero < one);
EXPECT_TRUE(zero < two);
EXPECT_TRUE(one < two);
EXPECT_FALSE(zero > one);
EXPECT_FALSE(zero > two);
EXPECT_FALSE(one > two);
EXPECT_FALSE(zero == one);
EXPECT_FALSE(zero == two);
EXPECT_FALSE(one == two);
EXPECT_TRUE(zero == zero);
EXPECT_TRUE(one == one);
EXPECT_TRUE(two == two);
EXPECT_TRUE(zero >= zero);
EXPECT_TRUE(one >= one);
EXPECT_TRUE(two >= two);
EXPECT_TRUE(zero <= zero);
EXPECT_TRUE(one <= one);
EXPECT_TRUE(two <= two);
FixedPoint<16, 16> zero_point_five(0.5);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> two_point_five(2.5);
EXPECT_TRUE(zero_point_five < one);
EXPECT_TRUE(zero_point_five < two);
EXPECT_TRUE(one_point_five < two);
EXPECT_FALSE(zero_point_five > one);
EXPECT_FALSE(zero_point_five > two);
EXPECT_FALSE(one_point_five > two);
EXPECT_FALSE(zero_point_five == one);
EXPECT_FALSE(zero_point_five == two);
EXPECT_FALSE(one_point_five == two);
EXPECT_TRUE(zero_point_five == zero_point_five);
EXPECT_TRUE(one_point_five == one_point_five);
EXPECT_TRUE(two_point_five == two_point_five);
EXPECT_TRUE(zero_point_five >= zero_point_five);
EXPECT_TRUE(one_point_five >= one_point_five);
EXPECT_TRUE(two_point_five >= two_point_five);
EXPECT_TRUE(zero_point_five <= zero_point_five);
EXPECT_TRUE(one_point_five <= one_point_five);
EXPECT_TRUE(two_point_five <= two_point_five);
FixedPoint<16, 16> m_zero(-0);
FixedPoint<16, 16> m_one(-1.0);
FixedPoint<16, 16> m_two(-2);
EXPECT_TRUE(m_zero > m_one);
EXPECT_TRUE(m_zero > m_two);
EXPECT_TRUE(m_one > m_two);
EXPECT_FALSE(m_zero < m_one);
EXPECT_FALSE(m_zero < m_two);
EXPECT_FALSE(m_one < m_two);
EXPECT_FALSE(m_zero == m_one);
EXPECT_FALSE(m_zero == m_two);
EXPECT_FALSE(m_one == m_two);
EXPECT_TRUE(zero == m_zero);
EXPECT_TRUE(m_zero == m_zero);
EXPECT_TRUE(m_one == m_one);
EXPECT_TRUE(m_two == m_two);
EXPECT_TRUE(m_zero >= m_zero);
EXPECT_TRUE(m_one >= m_one);
EXPECT_TRUE(m_two >= m_two);
EXPECT_TRUE(m_zero <= m_zero);
EXPECT_TRUE(m_one <= m_one);
EXPECT_TRUE(m_two <= m_two);
EXPECT_TRUE(zero > m_one);
EXPECT_TRUE(zero > m_two);
EXPECT_TRUE(one > m_two);
EXPECT_TRUE(m_two < one);
EXPECT_TRUE(m_one < two);
EXPECT_TRUE(fp32_t::CONST_E == 2.718281828459045235360287471352662498);
EXPECT_TRUE(fp32_t::CONST_LOG2E == 1.442695040888963407359924681001892137);
EXPECT_TRUE(fp32_t::CONST_LOG10E == 0.434294481903251827651128918916605082);
EXPECT_TRUE(fp32_t::CONST_LN2 == 0.693147180559945309417232121458176568);
EXPECT_TRUE(fp32_t::CONST_LN10 == 2.302585092994045684017991454684364208);
EXPECT_TRUE(fp32_t::CONST_PI == 3.141592653589793238462643383279502884);
EXPECT_TRUE(fp32_t::CONST_PI_2 == 1.570796326794896619231321691639751442);
EXPECT_TRUE(fp32_t::CONST_PI_4 == 0.785398163397448309615660845819875721);
EXPECT_TRUE(fp32_t::CONST_INV_PI == 0.318309886183790671537767526745028724);
EXPECT_TRUE(fp32_t::CONST_TWO_INV_PI == 0.636619772367581343075535053490057448);
EXPECT_TRUE(fp32_t::CONST_TWO_INV_SQRTPI == 1.128379167095512573896158903121545172);
EXPECT_TRUE(fp32_t::CONST_SQRT2 == 1.414213562373095048801688724209698079);
EXPECT_TRUE(fp32_t::CONST_INV_SQRT2 == 0.707106781186547524400844362104849039);
EXPECT_EQ(fp32_t::MAX_INT, 0x7fff0000);
EXPECT_EQ(fp32_t::MIN_INT, 0x80000000);
EXPECT_EQ(fp32_t::MAX, 0x7fffffff);
EXPECT_EQ(fp32_t::MIN, 0x8000ffff);
EXPECT_EQ(fp32_t::MAX_EXP.Data(), 0x000a65b9);
EXPECT_EQ(fp32_t::MIN_EXP.Data(), 0xfff59a47);
}
TEST(FixedPointTest, Comparison_32_32)
{
FixedPoint<32, 32> zero(0);
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
EXPECT_LT(zero, one);
EXPECT_LT(zero, two);
EXPECT_LT(one, two);
EXPECT_FALSE(zero > one);
EXPECT_FALSE(zero > two);
EXPECT_FALSE(one > two);
EXPECT_FALSE(zero == one);
EXPECT_FALSE(zero == two);
EXPECT_FALSE(one == two);
EXPECT_EQ(zero, zero);
EXPECT_EQ(one, one);
EXPECT_EQ(two, two);
EXPECT_GE(zero, zero);
EXPECT_GE(one, one);
EXPECT_GE(two, two);
EXPECT_LE(zero, zero);
EXPECT_LE(one, one);
EXPECT_LE(two, two);
FixedPoint<32, 32> zero_point_five(0.5);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> two_point_five(2.5);
EXPECT_LT(zero_point_five, one);
EXPECT_LT(zero_point_five, two);
EXPECT_LT(one_point_five, two);
EXPECT_FALSE(zero_point_five > one);
EXPECT_FALSE(zero_point_five > two);
EXPECT_FALSE(one_point_five > two);
EXPECT_FALSE(zero_point_five == one);
EXPECT_FALSE(zero_point_five == two);
EXPECT_FALSE(one_point_five == two);
EXPECT_EQ(zero_point_five, zero_point_five);
EXPECT_EQ(one_point_five, one_point_five);
EXPECT_EQ(two_point_five, two_point_five);
EXPECT_GE(zero_point_five, zero_point_five);
EXPECT_GE(one_point_five, one_point_five);
EXPECT_GE(two_point_five, two_point_five);
EXPECT_LE(zero_point_five, zero_point_five);
EXPECT_LE(one_point_five, one_point_five);
EXPECT_LE(two_point_five, two_point_five);
FixedPoint<32, 32> m_zero(-0);
FixedPoint<32, 32> m_one(-1.0);
FixedPoint<32, 32> m_two(-2);
EXPECT_GT(m_zero, m_one);
EXPECT_GT(m_zero, m_two);
EXPECT_GT(m_one, m_two);
EXPECT_FALSE(m_zero < m_one);
EXPECT_FALSE(m_zero < m_two);
EXPECT_FALSE(m_one < m_two);
EXPECT_FALSE(m_zero == m_one);
EXPECT_FALSE(m_zero == m_two);
EXPECT_FALSE(m_one == m_two);
EXPECT_EQ(zero, m_zero);
EXPECT_EQ(m_zero, m_zero);
EXPECT_EQ(m_one, m_one);
EXPECT_EQ(m_two, m_two);
EXPECT_GE(m_zero, m_zero);
EXPECT_GE(m_one, m_one);
EXPECT_GE(m_two, m_two);
EXPECT_LE(m_zero, m_zero);
EXPECT_LE(m_one, m_one);
EXPECT_LE(m_two, m_two);
EXPECT_GT(zero, m_one);
EXPECT_GT(zero, m_two);
EXPECT_GT(one, m_two);
EXPECT_LT(m_two, one);
EXPECT_LT(m_one, two);
EXPECT_TRUE(fp64_t::CONST_E == 2.718281828459045235360287471352662498);
EXPECT_TRUE(fp64_t::CONST_LOG2E == 1.442695040888963407359924681001892137);
EXPECT_TRUE(fp64_t::CONST_LOG10E == 0.434294481903251827651128918916605082);
EXPECT_TRUE(fp64_t::CONST_LN2 == 0.693147180559945309417232121458176568);
EXPECT_TRUE(fp64_t::CONST_LN10 == 2.302585092994045684017991454684364208);
EXPECT_TRUE(fp64_t::CONST_PI == 3.141592653589793238462643383279502884);
EXPECT_TRUE(fp64_t::CONST_PI / 2 == fp64_t::CONST_PI_2);
EXPECT_TRUE(fp64_t::CONST_PI_4 == 0.785398163397448309615660845819875721);
EXPECT_TRUE(one / fp64_t::CONST_PI == fp64_t::CONST_INV_PI);
EXPECT_TRUE(fp64_t::CONST_TWO_INV_PI == 0.636619772367581343075535053490057448);
EXPECT_TRUE(fp64_t::CONST_TWO_INV_SQRTPI == 1.128379167095512573896158903121545172);
EXPECT_TRUE(fp64_t::CONST_SQRT2 == 1.414213562373095048801688724209698079);
EXPECT_TRUE(fp64_t::CONST_INV_SQRT2 == 0.707106781186547524400844362104849039);
EXPECT_EQ(fp64_t::MAX_INT, 0x7fffffff00000000);
EXPECT_EQ(fp64_t::MIN_INT, 0x8000000000000000);
EXPECT_EQ(fp64_t::MAX, 0x7fffffffffffffff);
EXPECT_EQ(fp64_t::MIN, 0x80000000ffffffff);
EXPECT_EQ(fp64_t::MAX_EXP.Data(), 0x000000157cd0e714);
EXPECT_EQ(fp64_t::MIN_EXP.Data(), 0xffffffea832f18ec);
}
TEST(FixedPointTest, Exponential_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> two(2);
FixedPoint<16, 16> negative{-0.40028143};
FixedPoint<16, 16> e1 = fp32_t::Exp(one);
FixedPoint<16, 16> e2 = fp32_t::Exp(two);
FixedPoint<16, 16> e3 = fp32_t::Exp(negative);
FixedPoint<16, 16> e_max = fp32_t::Exp(fp32_t::MAX_EXP);
EXPECT_NEAR(static_cast<double>(e1) / std::exp(1.0), 1.0, static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2) / std::exp(2.0), 1.0, static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR((static_cast<double>(e3) - std::exp(static_cast<double>(negative))) /
std::exp(static_cast<double>(negative)),
0, static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e_max) / std::exp(static_cast<double>(fp32_t::MAX_EXP)), 1.0,
static_cast<double>(fp32_t::TOLERANCE));
fp32_t::StateClear();
EXPECT_EQ(fp32_t::Exp(fp32_t::MAX_EXP + 1), fp32_t::FP_MAX);
EXPECT_TRUE(fp32_t::IsStateOverflow());
fp32_t step{0.001};
fp32_t x{-10.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp32_t e = fp32_t::Exp(x);
double r = std::exp(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, 10 * tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Exp: max error = " << max_error << std::endl;
// std::cout << "Exp: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Exponential_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> two(2);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> small(0.0001);
FixedPoint<32, 32> tiny(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<32, 32> negative{-0.40028143};
FixedPoint<32, 32> e1 = fp64_t::Exp(one);
FixedPoint<32, 32> e2 = fp64_t::Exp(two);
FixedPoint<32, 32> e3 = fp64_t::Exp(small);
FixedPoint<32, 32> e4 = fp64_t::Exp(tiny);
FixedPoint<32, 32> e5 = fp64_t::Exp(negative);
FixedPoint<32, 32> e6 = fp64_t::Exp(ten);
EXPECT_NEAR(static_cast<double>(e1) - std::exp(static_cast<double>(one)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2) - std::exp(static_cast<double>(two)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e3) - std::exp(static_cast<double>(small)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e4) - std::exp(static_cast<double>(tiny)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e5) - std::exp(static_cast<double>(negative)), 0,
static_cast<double>(fp64_t::TOLERANCE));
// For bigger values check relative error
EXPECT_NEAR((static_cast<double>(e6) - std::exp(static_cast<double>(ten))) /
std::exp(static_cast<double>(ten)),
0, static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR((static_cast<double>(fp64_t::Exp(fp64_t::MAX_EXP)) -
std::exp(static_cast<double>(fp64_t::MAX_EXP))) /
std::exp(static_cast<double>(fp64_t::MAX_EXP)),
0, static_cast<double>(fp64_t::TOLERANCE));
// Out of range
fp64_t::StateClear();
EXPECT_EQ(fp64_t::Exp(fp64_t::MAX_EXP + 1), fp64_t::FP_MAX);
EXPECT_TRUE(fp64_t::IsStateOverflow());
// Negative values
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(-one)) - std::exp(-static_cast<double>(one)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(-two)) - std::exp(-static_cast<double>(two)), 0,
static_cast<double>(fp64_t::TOLERANCE));
// This particular error produces more than 1e-6 error failing the test
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(-ten)) - std::exp(-static_cast<double>(ten)), 0,
static_cast<double>(fp64_t::TOLERANCE));
// The rest pass with fp64_t::TOLERANCE
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(-small)) - std::exp(-static_cast<double>(small)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(-tiny)) - std::exp(-static_cast<double>(tiny)), 0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(fp64_t::Exp(fp64_t::MIN_EXP)) -
std::exp(static_cast<double>(fp64_t::MIN_EXP)),
0, static_cast<double>(fp64_t::TOLERANCE));
fp64_t step{0.0001};
fp64_t x{-10.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::Exp(x);
double r = std::exp(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, 10 * tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Exp: max error = " << max_error << std::endl;
// std::cout << "Exp: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Pow_16_16_positive_x)
{
FixedPoint<16, 16> a{-1.6519711627625};
FixedPoint<16, 16> two{2};
FixedPoint<16, 16> three{3};
FixedPoint<16, 16> b{1.8464393615723};
FixedPoint<16, 16> e1 = fp32_t::Pow(a, two);
FixedPoint<16, 16> e2 = fp32_t::Pow(a, three);
FixedPoint<16, 16> e3 = fp32_t::Pow(two, b);
EXPECT_NEAR(static_cast<double>(e1 / std::pow(-1.6519711627625, 2)), 1.0,
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2 / std::pow(-1.6519711627625, 3)), 1.0,
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e3 / std::pow(2, 1.8464393615723)), 1.0,
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Pow(a, a)));
fp32_t step{0.001};
fp32_t x{0.001};
fp32_t y{0.001};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 100.0; x += step)
{
for (; y < 10.5; y += step)
{
fp32_t e = fp32_t::Pow(x, y);
double r = std::pow(static_cast<double>(x), static_cast<double>(y));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Pow: max error = " << max_error << std::endl;
// std::cout << "Pow: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Pow_16_16_negative_x)
{
fp32_t step{0.01};
fp32_t x{-10};
fp32_t y{-4};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 10.0; x += step)
{
for (; y < 4; ++y)
{
fp32_t e = fp32_t::Pow(x, y);
double r = std::pow(static_cast<double>(x), static_cast<double>(y));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Pow: max error = " << max_error << std::endl;
// std::cout << "Pow: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Pow_32_32_positive_x)
{
FixedPoint<32, 32> a{-1.6519711627625};
FixedPoint<32, 32> two{2};
FixedPoint<32, 32> three{3};
FixedPoint<32, 32> b{1.8464393615723};
FixedPoint<32, 32> e1 = fp64_t::Pow(a, two);
FixedPoint<32, 32> e2 = fp64_t::Pow(a, three);
FixedPoint<32, 32> e3 = fp64_t::Pow(two, b);
EXPECT_NEAR(static_cast<double>(e1 / std::pow(-1.6519711627625, 2)), 1.0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2 / std::pow(-1.6519711627625, 3)), 1.0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e3 / std::pow(2, 1.8464393615723)), 1.0,
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Pow(a, a)));
fp64_t step{0.0001};
fp64_t x{0.0001};
fp64_t y{0.001};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 100.0; x += step)
{
for (; y < 40.5; y += step)
{
fp64_t e = fp64_t::Pow(x, y);
double r = std::pow(static_cast<double>(x), static_cast<double>(y));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Pow: max error = " << max_error << std::endl;
// std::cout << "Pow: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Pow_32_32_negative_x)
{
fp64_t step{0.01};
fp64_t x{-10};
fp64_t y{-9};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 10.0; x += step)
{
for (; y < 9; ++y)
{
fp64_t e = fp64_t::Pow(x, y);
double r = std::pow(static_cast<double>(x), static_cast<double>(y));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Pow: max error = " << max_error << std::endl;
// std::cout << "Pow: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Logarithm_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> ten(10);
FixedPoint<16, 16> huge(10000);
FixedPoint<16, 16> small(0.001);
FixedPoint<16, 16> tiny(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<16, 16> e1 = fp32_t::Log2(one);
FixedPoint<16, 16> e2 = fp32_t::Log2(one_point_five);
FixedPoint<16, 16> e3 = fp32_t::Log2(ten);
FixedPoint<16, 16> e4 = fp32_t::Log2(huge);
FixedPoint<16, 16> e5 = fp32_t::Log2(small);
FixedPoint<16, 16> e6 = fp32_t::Log2(tiny);
EXPECT_NEAR(static_cast<double>(e1), std::log2(static_cast<double>(one)),
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2), std::log2(static_cast<double>(one_point_five)),
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e3), std::log2(static_cast<double>(ten)),
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e4), std::log2(static_cast<double>(huge)),
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e5), std::log2(static_cast<double>(small)),
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e6), std::log2(static_cast<double>(tiny)),
static_cast<double>(fp32_t::TOLERANCE));
fp32_t step{0.001};
fp32_t x{tiny};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp32_t e = fp32_t::Log(x);
double r = std::log(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Log: max error = " << max_error << std::endl;
// std::cout << "Log: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Logarithm_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> huge(1000000000);
FixedPoint<32, 32> small(0.0001);
FixedPoint<32, 32> tiny(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<32, 32> e1 = fp64_t::Log2(one);
FixedPoint<32, 32> e2 = fp64_t::Log2(one_point_five);
FixedPoint<32, 32> e3 = fp64_t::Log2(ten);
FixedPoint<32, 32> e4 = fp64_t::Log2(huge);
FixedPoint<32, 32> e5 = fp64_t::Log2(small);
FixedPoint<32, 32> e6 = fp64_t::Log2(tiny);
EXPECT_NEAR(static_cast<double>(e1), std::log2(static_cast<double>(one)),
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e2), std::log2(static_cast<double>(one_point_five)),
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e3), std::log2(static_cast<double>(ten)),
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e4), std::log2(static_cast<double>(huge)),
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e5), std::log2(static_cast<double>(small)),
static_cast<double>(fp64_t::TOLERANCE));
EXPECT_NEAR(static_cast<double>(e6), std::log2(static_cast<double>(tiny)),
static_cast<double>(fp64_t::TOLERANCE));
fp64_t step{0.0001};
fp64_t x{tiny};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::Log(x);
double r = std::log(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
if (delta > tolerance)
{
// std::cout << "delta = " << delta << std::endl;
// std::cout << "e = " << e << std::endl;
// std::cout << "r = " << r << std::endl;
// std::cout << "x = " << x << std::endl;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Log: max error = " << max_error << std::endl;
// std::cout << "Log: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Abs_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> m_one_point_five(-1.5);
FixedPoint<16, 16> ten(10);
FixedPoint<16, 16> m_ten(-10);
FixedPoint<16, 16> e1 = fp32_t::Abs(one);
FixedPoint<16, 16> e2 = fp32_t::Abs(m_one);
FixedPoint<16, 16> e3 = fp32_t::Abs(one_point_five);
FixedPoint<16, 16> e4 = fp32_t::Abs(m_one_point_five);
FixedPoint<16, 16> e5 = fp32_t::Abs(ten);
FixedPoint<16, 16> e6 = fp32_t::Abs(m_ten);
EXPECT_EQ(e1, one);
EXPECT_EQ(e2, one);
EXPECT_EQ(e3, one_point_five);
EXPECT_EQ(e4, one_point_five);
EXPECT_EQ(e5, ten);
EXPECT_EQ(e6, ten);
}
TEST(FixedPointTest, Abs_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> m_one_point_five(-1.5);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> m_ten(-10);
FixedPoint<32, 32> huge(999999999.0);
FixedPoint<32, 32> e1 = fp64_t::Abs(one);
FixedPoint<32, 32> e2 = fp64_t::Abs(m_one);
FixedPoint<32, 32> e3 = fp64_t::Abs(one_point_five);
FixedPoint<32, 32> e4 = fp64_t::Abs(m_one_point_five);
FixedPoint<32, 32> e5 = fp64_t::Abs(ten);
FixedPoint<32, 32> e6 = fp64_t::Abs(m_ten);
FixedPoint<32, 32> e7 = fp64_t::Abs(huge);
EXPECT_EQ(e1, one);
EXPECT_EQ(e2, one);
EXPECT_EQ(e3, one_point_five);
EXPECT_EQ(e4, one_point_five);
EXPECT_EQ(e5, ten);
EXPECT_EQ(e6, ten);
EXPECT_EQ(e7, huge);
}
TEST(FixedPointTest, Remainder_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> m_one_point_five(-1.5);
FixedPoint<16, 16> ten(10);
FixedPoint<16, 16> m_ten(-10);
FixedPoint<16, 16> x{1.6519711627625};
FixedPoint<16, 16> huge(1000);
FixedPoint<16, 16> e1 = fp32_t::Remainder(ten, one);
FixedPoint<16, 16> e2 = fp32_t::Remainder(ten, m_one);
FixedPoint<16, 16> e3 = fp32_t::Remainder(ten, one_point_five);
FixedPoint<16, 16> e4 = fp32_t::Remainder(ten, m_one_point_five);
FixedPoint<16, 16> e5 = fp32_t::Remainder(ten, x);
FixedPoint<16, 16> e6 = fp32_t::Remainder(m_ten, x);
FixedPoint<16, 16> e7 = fp32_t::Remainder(huge, fp32_t::CONST_PI);
EXPECT_EQ(e1, std::remainder(static_cast<double>(ten), static_cast<double>(one)));
EXPECT_EQ(e2, std::remainder(static_cast<double>(ten), static_cast<double>(m_one)));
EXPECT_EQ(e3, std::remainder(static_cast<double>(ten), static_cast<double>(one_point_five)));
EXPECT_EQ(e4, std::remainder(static_cast<double>(ten), static_cast<double>(m_one_point_five)));
EXPECT_EQ(e5, std::remainder(static_cast<double>(ten), static_cast<double>(x)));
EXPECT_EQ(e6, std::remainder(static_cast<double>(m_ten), static_cast<double>(x)));
EXPECT_EQ(e7, std::remainder(static_cast<double>(huge), static_cast<double>(fp32_t::CONST_PI)));
}
TEST(FixedPointTest, Remainder_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> m_one_point_five(-1.5);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> m_ten(-10);
FixedPoint<32, 32> x{1.6519711627625};
FixedPoint<32, 32> huge(1000000000);
FixedPoint<32, 32> e1 = fp64_t::Remainder(ten, one);
FixedPoint<32, 32> e2 = fp64_t::Remainder(ten, m_one);
FixedPoint<32, 32> e3 = fp64_t::Remainder(ten, one_point_five);
FixedPoint<32, 32> e4 = fp64_t::Remainder(ten, m_one_point_five);
FixedPoint<32, 32> e5 = fp64_t::Remainder(ten, x);
FixedPoint<32, 32> e6 = fp64_t::Remainder(m_ten, x);
FixedPoint<32, 32> e7 = fp64_t::Remainder(huge, x);
EXPECT_EQ(e1, std::remainder(static_cast<double>(ten), static_cast<double>(one)));
EXPECT_EQ(e2, std::remainder(static_cast<double>(ten), static_cast<double>(m_one)));
EXPECT_EQ(e3, std::remainder(static_cast<double>(ten), static_cast<double>(one_point_five)));
EXPECT_EQ(e4, std::remainder(static_cast<double>(ten), static_cast<double>(m_one_point_five)));
EXPECT_EQ(e5, std::remainder(static_cast<double>(ten), static_cast<double>(x)));
EXPECT_EQ(e6, std::remainder(static_cast<double>(m_ten), static_cast<double>(x)));
EXPECT_EQ(e7, std::remainder(static_cast<double>(huge), static_cast<double>(x)));
}
TEST(FixedPointTest, Fmod_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> m_one(-1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> m_one_point_five(-1.5);
FixedPoint<16, 16> ten(10);
FixedPoint<16, 16> m_ten(-10);
FixedPoint<16, 16> x{1.6519711627625};
FixedPoint<16, 16> e1 = fp32_t::Fmod(ten, one);
FixedPoint<16, 16> e2 = fp32_t::Fmod(ten, m_one);
FixedPoint<16, 16> e3 = fp32_t::Fmod(ten, one_point_five);
FixedPoint<16, 16> e4 = fp32_t::Fmod(ten, m_one_point_five);
FixedPoint<16, 16> e5 = fp32_t::Fmod(ten, x);
FixedPoint<16, 16> e6 = fp32_t::Fmod(m_ten, x);
EXPECT_EQ(e1, std::fmod(static_cast<double>(ten), static_cast<double>(one)));
EXPECT_EQ(e2, std::fmod(static_cast<double>(ten), static_cast<double>(m_one)));
EXPECT_EQ(e3, std::fmod(static_cast<double>(ten), static_cast<double>(one_point_five)));
EXPECT_EQ(e4, std::fmod(static_cast<double>(ten), static_cast<double>(m_one_point_five)));
EXPECT_EQ(e5, std::fmod(static_cast<double>(ten), static_cast<double>(x)));
EXPECT_EQ(e6, std::fmod(static_cast<double>(m_ten), static_cast<double>(x)));
}
TEST(FixedPointTest, Fmod_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> m_one(-1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> m_one_point_five(-1.5);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> m_ten(-10);
FixedPoint<32, 32> x{1.6519711627625};
FixedPoint<32, 32> e1 = fp64_t::Fmod(ten, one);
FixedPoint<32, 32> e2 = fp64_t::Fmod(ten, m_one);
FixedPoint<32, 32> e3 = fp64_t::Fmod(ten, one_point_five);
FixedPoint<32, 32> e4 = fp64_t::Fmod(ten, m_one_point_five);
FixedPoint<32, 32> e5 = fp64_t::Fmod(ten, x);
FixedPoint<32, 32> e6 = fp64_t::Fmod(m_ten, x);
EXPECT_EQ(e1, std::fmod(static_cast<double>(ten), static_cast<double>(one)));
EXPECT_EQ(e2, std::fmod(static_cast<double>(ten), static_cast<double>(m_one)));
EXPECT_EQ(e3, std::fmod(static_cast<double>(ten), static_cast<double>(one_point_five)));
EXPECT_EQ(e4, std::fmod(static_cast<double>(ten), static_cast<double>(m_one_point_five)));
EXPECT_EQ(e5, std::fmod(static_cast<double>(ten), static_cast<double>(x)));
EXPECT_EQ(e6, std::fmod(static_cast<double>(m_ten), static_cast<double>(x)));
}
TEST(FixedPointTest, SQRT_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> two(2);
FixedPoint<16, 16> four(4);
FixedPoint<16, 16> ten(10);
FixedPoint<16, 16> huge(10000);
FixedPoint<16, 16> small(0.0001);
FixedPoint<16, 16> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<16, 16> e1 = fp32_t::Sqrt(one);
FixedPoint<16, 16> e2 = fp32_t::Sqrt(one_point_five);
FixedPoint<16, 16> e3 = fp32_t::Sqrt(two);
FixedPoint<16, 16> e4 = fp32_t::Sqrt(four);
FixedPoint<16, 16> e5 = fp32_t::Sqrt(ten);
FixedPoint<16, 16> e6 = fp32_t::Sqrt(huge);
FixedPoint<16, 16> e7 = fp32_t::Sqrt(small);
FixedPoint<16, 16> e8 = fp32_t::Sqrt(tiny);
double delta = static_cast<double>(e1) - std::sqrt(static_cast<double>(one));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(one)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e2) - std::sqrt(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e3) - std::sqrt(static_cast<double>(two));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(two)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e3 - fp32_t::CONST_SQRT2);
EXPECT_NEAR(delta / static_cast<double>(fp32_t::CONST_SQRT2), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e4) - std::sqrt(static_cast<double>(four));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(four)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e5) - std::sqrt(static_cast<double>(ten));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(ten)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e6) - std::sqrt(static_cast<double>(huge));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(huge)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e7) - std::sqrt(static_cast<double>(small));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(small)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e8) - std::sqrt(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
// Sqrt of a negative
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Sqrt(-one)));
fp32_t step{0.01};
fp32_t x{tiny}, max{huge};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 4 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < max; x += step)
{
fp32_t e = fp32_t::Sqrt(x);
double r = std::sqrt(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, 5 * tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Sqrt: max error = " << max_error << std::endl;
// std::cout << "Sqrt: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, SQRT_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> two(2);
FixedPoint<32, 32> four(4);
FixedPoint<32, 32> ten(10);
FixedPoint<32, 32> huge(1000000000);
FixedPoint<32, 32> small(0.0001);
FixedPoint<32, 32> tiny(0, fp64_t::SMALLEST_FRACTION);
FixedPoint<32, 32> e1 = fp64_t::Sqrt(one);
FixedPoint<32, 32> e2 = fp64_t::Sqrt(one_point_five);
FixedPoint<32, 32> e3 = fp64_t::Sqrt(two);
FixedPoint<32, 32> e4 = fp64_t::Sqrt(four);
FixedPoint<32, 32> e5 = fp64_t::Sqrt(ten);
FixedPoint<32, 32> e6 = fp64_t::Sqrt(huge);
FixedPoint<32, 32> e7 = fp64_t::Sqrt(small);
FixedPoint<32, 32> e8 = fp64_t::Sqrt(tiny);
double delta = static_cast<double>(e1) - std::sqrt(static_cast<double>(one));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(one)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e2) - std::sqrt(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e3) - std::sqrt(static_cast<double>(two));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(two)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e3 - fp64_t::CONST_SQRT2);
EXPECT_NEAR(delta / static_cast<double>(fp64_t::CONST_SQRT2), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e4) - std::sqrt(static_cast<double>(four));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(four)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e5) - std::sqrt(static_cast<double>(ten));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(ten)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e6) - std::sqrt(static_cast<double>(huge));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(huge)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e7) - std::sqrt(static_cast<double>(small));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(small)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e8) - std::sqrt(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::sqrt(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
// Sqrt of a negative
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Sqrt(-one)));
fp64_t step{0.001};
fp64_t x{tiny}, max{huge};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::Sqrt(x);
double r = std::sqrt(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, 10 * tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Sqrt: max error = " << max_error << std::endl;
// std::cout << "Sqrt: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Sin_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> huge(2000);
FixedPoint<16, 16> small(0.0001);
FixedPoint<16, 16> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<16, 16> e1 = fp32_t::Sin(one);
FixedPoint<16, 16> e2 = fp32_t::Sin(one_point_five);
FixedPoint<16, 16> e3 = fp32_t::Sin(fp32_t::_0);
FixedPoint<16, 16> e4 = fp32_t::Sin(huge);
FixedPoint<16, 16> e5 = fp32_t::Sin(small);
FixedPoint<16, 16> e6 = fp32_t::Sin(tiny);
FixedPoint<16, 16> e7 = fp32_t::Sin(fp32_t::CONST_PI);
FixedPoint<16, 16> e8 = fp32_t::Sin(-fp32_t::CONST_PI);
FixedPoint<16, 16> e9 = fp32_t::Sin(fp32_t::CONST_PI * 2);
FixedPoint<16, 16> e10 = fp32_t::Sin(fp32_t::CONST_PI * 4);
FixedPoint<16, 16> e11 = fp32_t::Sin(fp32_t::CONST_PI * 100);
FixedPoint<16, 16> e12 = fp32_t::Sin(fp32_t::CONST_PI_2);
FixedPoint<16, 16> e13 = fp32_t::Sin(-fp32_t::CONST_PI_2);
FixedPoint<16, 16> e14 = fp32_t::Sin(fp32_t::CONST_PI_4);
FixedPoint<16, 16> e15 = fp32_t::Sin(-fp32_t::CONST_PI_4);
FixedPoint<16, 16> e16 = fp32_t::Sin(fp32_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::sin(static_cast<double>(one));
EXPECT_NEAR(delta / std::sin(static_cast<double>(one)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e2) - std::sin(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::sin(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e3) - std::sin(static_cast<double>(fp32_t::_0));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e4) - std::sin(static_cast<double>(huge));
EXPECT_NEAR(delta / std::sin(static_cast<double>(huge)), 0.0,
0.002); // Sin for larger arguments loses precision
delta = static_cast<double>(e5) - std::sin(static_cast<double>(small));
EXPECT_NEAR(delta / std::sin(static_cast<double>(small)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e6) - std::sin(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::sin(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e7) - std::sin(static_cast<double>(fp32_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e8) - std::sin(static_cast<double>((-fp32_t::CONST_PI)));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e9) - std::sin(static_cast<double>((fp32_t::CONST_PI * 2)));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e10) - std::sin(static_cast<double>((fp32_t::CONST_PI * 4)));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e11) - std::sin(static_cast<double>((fp32_t::CONST_PI * 100)));
EXPECT_NEAR(delta, 0.0, 0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e12) - std::sin(static_cast<double>((fp32_t::CONST_PI_2)));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp32_t::CONST_PI_2)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e13) - std::sin(static_cast<double>((-fp32_t::CONST_PI_2)));
EXPECT_NEAR(delta / std::sin(static_cast<double>(-fp32_t::CONST_PI_2)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e14) - std::sin(static_cast<double>((fp32_t::CONST_PI_4)));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp32_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e15) - std::sin(static_cast<double>((-fp32_t::CONST_PI_4)));
EXPECT_NEAR(delta / std::sin(static_cast<double>(-fp32_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e16) - std::sin(static_cast<double>((fp32_t::CONST_PI_4 * 3)));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp32_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
fp32_t step{0.1};
fp32_t x{-fp32_t::CONST_PI * 10};
for (; x < fp32_t::CONST_PI * 10; x += step)
{
fp32_t e = fp32_t::Sin(x);
delta = static_cast<double>(e) - std::sin(static_cast<double>(x));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
}
}
TEST(FixedPointTest, Sin_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> huge(20000000);
FixedPoint<32, 32> small(0.0000001);
FixedPoint<32, 32> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<32, 32> e1 = fp64_t::Sin(one);
FixedPoint<32, 32> e2 = fp64_t::Sin(one_point_five);
FixedPoint<32, 32> e3 = fp64_t::Sin(fp64_t::_0);
FixedPoint<32, 32> e4 = fp64_t::Sin(huge);
FixedPoint<32, 32> e5 = fp64_t::Sin(small);
FixedPoint<32, 32> e6 = fp64_t::Sin(tiny);
FixedPoint<32, 32> e7 = fp64_t::Sin(fp64_t::CONST_PI);
FixedPoint<32, 32> e8 = fp64_t::Sin(-fp64_t::CONST_PI);
FixedPoint<32, 32> e9 = fp64_t::Sin(fp64_t::CONST_PI * 2);
FixedPoint<32, 32> e10 = fp64_t::Sin(fp64_t::CONST_PI * 4);
FixedPoint<32, 32> e11 = fp64_t::Sin(fp64_t::CONST_PI * 100);
FixedPoint<32, 32> e12 = fp64_t::Sin(fp64_t::CONST_PI_2);
FixedPoint<32, 32> e13 = fp64_t::Sin(-fp64_t::CONST_PI_2);
FixedPoint<32, 32> e14 = fp64_t::Sin(fp64_t::CONST_PI_4);
FixedPoint<32, 32> e15 = fp64_t::Sin(-fp64_t::CONST_PI_4);
FixedPoint<32, 32> e16 = fp64_t::Sin(fp64_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::sin(static_cast<double>(one));
EXPECT_NEAR(delta / std::sin(static_cast<double>(one)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e2) - std::sin(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::sin(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e3) - std::sin(static_cast<double>(fp64_t::_0));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e4) - std::sin(static_cast<double>(huge));
EXPECT_NEAR(delta / std::sin(static_cast<double>(huge)), 0.0,
0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e5) - std::sin(static_cast<double>(small));
EXPECT_NEAR(delta / std::sin(static_cast<double>(small)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e6) - std::sin(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::sin(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e7) - std::sin(static_cast<double>(fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e8) - std::sin(static_cast<double>(-fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e9) - std::sin(static_cast<double>(fp64_t::CONST_PI * 2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e10) - std::sin(static_cast<double>(fp64_t::CONST_PI * 4));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e11) - std::sin(static_cast<double>(fp64_t::CONST_PI * 100));
EXPECT_NEAR(delta, 0.0,
static_cast<double>(fp64_t::TOLERANCE)); // Sin for larger arguments loses precision
delta = static_cast<double>(e12) - std::sin(static_cast<double>(fp64_t::CONST_PI_2));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp64_t::CONST_PI_2)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e13) - std::sin(static_cast<double>(-fp64_t::CONST_PI_2));
EXPECT_NEAR(delta / std::sin(static_cast<double>(-fp64_t::CONST_PI_2)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e14) - std::sin(static_cast<double>(fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e15) - std::sin(static_cast<double>(-fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::sin(static_cast<double>(-fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e16) - std::sin(static_cast<double>(fp64_t::CONST_PI_4 * 3));
EXPECT_NEAR(delta / std::sin(static_cast<double>(fp64_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
fp64_t step{0.001};
fp64_t x{-fp64_t::CONST_PI * 100};
for (; x < fp64_t::CONST_PI * 100; x += step)
{
fp64_t e = fp64_t::Sin(x);
delta = static_cast<double>(e) - std::sin(static_cast<double>(x));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
}
}
TEST(FixedPointTest, Cos_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> huge(2000);
FixedPoint<16, 16> small(0.0001);
FixedPoint<16, 16> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<16, 16> e1 = fp32_t::Cos(one);
FixedPoint<16, 16> e2 = fp32_t::Cos(one_point_five);
FixedPoint<16, 16> e3 = fp32_t::Cos(fp32_t::_0);
FixedPoint<16, 16> e4 = fp32_t::Cos(huge);
FixedPoint<16, 16> e5 = fp32_t::Cos(small);
FixedPoint<16, 16> e6 = fp32_t::Cos(tiny);
FixedPoint<16, 16> e7 = fp32_t::Cos(fp32_t::CONST_PI);
FixedPoint<16, 16> e8 = fp32_t::Cos(-fp32_t::CONST_PI);
FixedPoint<16, 16> e9 = fp32_t::Cos(fp32_t::CONST_PI * 2);
FixedPoint<16, 16> e10 = fp32_t::Cos(fp32_t::CONST_PI * 4);
FixedPoint<16, 16> e11 = fp32_t::Cos(fp32_t::CONST_PI * 100);
FixedPoint<16, 16> e12 = fp32_t::Cos(fp32_t::CONST_PI_2);
FixedPoint<16, 16> e13 = fp32_t::Cos(-fp32_t::CONST_PI_2);
FixedPoint<16, 16> e14 = fp32_t::Cos(fp32_t::CONST_PI_4);
FixedPoint<16, 16> e15 = fp32_t::Cos(-fp32_t::CONST_PI_4);
FixedPoint<16, 16> e16 = fp32_t::Cos(fp32_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::cos(static_cast<double>(one));
EXPECT_NEAR(delta / std::cos(static_cast<double>(one)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e2) - std::cos(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::cos(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e3) - std::cos(static_cast<double>(fp32_t::_0));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp32_t::_0)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e4) - std::cos(static_cast<double>(huge));
EXPECT_NEAR(delta / std::cos(static_cast<double>(huge)), 0.0,
0.012); // Sin for larger arguments loses precision
delta = static_cast<double>(e5) - std::cos(static_cast<double>(small));
EXPECT_NEAR(delta / std::cos(static_cast<double>(small)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e6) - std::cos(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::cos(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e7) - std::cos(static_cast<double>(fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e8) - std::cos(static_cast<double>(-fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e9) - std::cos(static_cast<double>(fp64_t::CONST_PI * 2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e10) - std::cos(static_cast<double>(fp64_t::CONST_PI * 4));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e11) - std::cos(static_cast<double>(fp64_t::CONST_PI * 100));
EXPECT_NEAR(delta, 0.0, 0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e12) - std::cos(static_cast<double>(fp64_t::CONST_PI_2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e13) - std::cos(static_cast<double>(-fp64_t::CONST_PI_2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e14) - std::cos(static_cast<double>(fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e15) - std::cos(static_cast<double>(-fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::cos(static_cast<double>(-fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e16) - std::cos(static_cast<double>(fp64_t::CONST_PI_4 * 3));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp64_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
fp32_t step{0.1};
fp32_t x{-fp32_t::CONST_PI * 10};
for (; x < fp32_t::CONST_PI * 10; x += step)
{
fp32_t e = fp32_t::Cos(x);
delta = static_cast<double>(e) - std::cos(static_cast<double>(x));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
}
}
TEST(FixedPointTest, Cos_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> huge(2000);
FixedPoint<32, 32> small(0.0001);
FixedPoint<32, 32> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<32, 32> e1 = fp64_t::Cos(one);
FixedPoint<32, 32> e2 = fp64_t::Cos(one_point_five);
FixedPoint<32, 32> e3 = fp64_t::Cos(fp64_t::_0);
FixedPoint<32, 32> e4 = fp64_t::Cos(huge);
FixedPoint<32, 32> e5 = fp64_t::Cos(small);
FixedPoint<32, 32> e6 = fp64_t::Cos(tiny);
FixedPoint<32, 32> e7 = fp64_t::Cos(fp64_t::CONST_PI);
FixedPoint<32, 32> e8 = fp64_t::Cos(-fp64_t::CONST_PI);
FixedPoint<32, 32> e9 = fp64_t::Cos(fp64_t::CONST_PI * 2);
FixedPoint<32, 32> e10 = fp64_t::Cos(fp64_t::CONST_PI * 4);
FixedPoint<32, 32> e11 = fp64_t::Cos(fp64_t::CONST_PI * 100);
FixedPoint<32, 32> e12 = fp64_t::Cos(fp64_t::CONST_PI_2);
FixedPoint<32, 32> e13 = fp64_t::Cos(-fp64_t::CONST_PI_2);
FixedPoint<32, 32> e14 = fp64_t::Cos(fp64_t::CONST_PI_4);
FixedPoint<32, 32> e15 = fp64_t::Cos(-fp64_t::CONST_PI_4);
FixedPoint<32, 32> e16 = fp64_t::Cos(fp64_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::cos(static_cast<double>(one));
EXPECT_NEAR(delta / std::cos(static_cast<double>(one)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e2) - std::cos(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::cos(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e3) - std::cos(static_cast<double>(fp64_t::_0));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp64_t::_0)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e4) - std::cos(static_cast<double>(huge));
EXPECT_NEAR(delta / std::cos(static_cast<double>(huge)), 0.0,
0.002); // Sin for larger arguments loses precision
delta = static_cast<double>(e5) - std::cos(static_cast<double>(small));
EXPECT_NEAR(delta / std::cos(static_cast<double>(small)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e6) - std::cos(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::cos(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e7) - std::cos(static_cast<double>(fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e8) - std::cos(static_cast<double>(-fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e9) - std::cos(static_cast<double>(fp64_t::CONST_PI * 2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e10) - std::cos(static_cast<double>(fp64_t::CONST_PI * 4));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e11) - std::cos(static_cast<double>(fp64_t::CONST_PI * 100));
EXPECT_NEAR(delta, 0.0, 0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e12) - std::cos(static_cast<double>(fp64_t::CONST_PI_2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e13) - std::cos(static_cast<double>(-fp64_t::CONST_PI_2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e14) - std::cos(static_cast<double>(fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e15) - std::cos(static_cast<double>(-fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::cos(static_cast<double>(-fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e16) - std::cos(static_cast<double>(fp64_t::CONST_PI_4 * 3));
EXPECT_NEAR(delta / std::cos(static_cast<double>(fp64_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
fp64_t step{0.1};
fp64_t x{-fp64_t::CONST_PI * 100};
for (; x < fp64_t::CONST_PI * 100; x += step)
{
fp64_t e = fp64_t::Cos(x);
delta = static_cast<double>(e) - std::cos(static_cast<double>(x));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
}
}
TEST(FixedPointTest, Tan_16_16)
{
FixedPoint<16, 16> one(1);
FixedPoint<16, 16> one_point_five(1.5);
FixedPoint<16, 16> huge(2000);
FixedPoint<16, 16> small(0.0001);
FixedPoint<16, 16> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<16, 16> e1 = fp32_t::Tan(one);
FixedPoint<16, 16> e2 = fp32_t::Tan(one_point_five);
FixedPoint<16, 16> e3 = fp32_t::Tan(fp32_t::_0);
FixedPoint<16, 16> e4 = fp32_t::Tan(huge);
FixedPoint<16, 16> e5 = fp32_t::Tan(small);
FixedPoint<16, 16> e6 = fp32_t::Tan(tiny);
FixedPoint<16, 16> e7 = fp32_t::Tan(fp32_t::CONST_PI);
FixedPoint<16, 16> e8 = fp32_t::Tan(-fp32_t::CONST_PI);
FixedPoint<16, 16> e9 = fp32_t::Tan(fp32_t::CONST_PI * 2);
FixedPoint<16, 16> e10 = fp32_t::Tan(fp32_t::CONST_PI * 4);
FixedPoint<16, 16> e11 = fp32_t::Tan(fp32_t::CONST_PI * 100);
FixedPoint<16, 16> e12 = fp32_t::Tan(fp32_t::CONST_PI_4);
FixedPoint<16, 16> e13 = fp32_t::Tan(-fp32_t::CONST_PI_4);
FixedPoint<16, 16> e14 = fp32_t::Tan(fp32_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::tan(static_cast<double>(one));
EXPECT_NEAR(delta / std::tan(static_cast<double>(one)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e2) - std::tan(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::tan(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e3) - std::tan(static_cast<double>(fp32_t::_0));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e4) - std::tan(static_cast<double>(huge));
// Tan for larger arguments loses precision
EXPECT_NEAR(delta / std::tan(static_cast<double>(huge)), 0.0, 0.012);
delta = static_cast<double>(e5) - std::tan(static_cast<double>(small));
EXPECT_NEAR(delta / std::tan(static_cast<double>(small)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e6) - std::tan(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::tan(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e7) - std::tan(static_cast<double>(fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e8) - std::tan(static_cast<double>(-fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e9) - std::tan(static_cast<double>(fp64_t::CONST_PI * 2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e10) - std::tan(static_cast<double>(fp64_t::CONST_PI * 4));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e11) - std::tan(static_cast<double>(fp64_t::CONST_PI * 100));
EXPECT_NEAR(delta, 0.0, 0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e12) - std::tan(static_cast<double>(fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::tan(static_cast<double>(fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e13) - std::tan(static_cast<double>(-fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::tan(static_cast<double>(-fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
delta = static_cast<double>(e14) - std::tan(static_cast<double>(fp64_t::CONST_PI_4 * 3));
EXPECT_NEAR(delta / std::tan(static_cast<double>(fp64_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp32_t::TOLERANCE));
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Tan(fp32_t::CONST_PI_2)));
EXPECT_TRUE(fp32_t::IsNegInfinity(fp32_t::Tan(-fp32_t::CONST_PI_2)));
fp32_t step{0.001}, offset{step * 10};
fp32_t x{-fp32_t::CONST_PI_2}, max{fp32_t::CONST_PI_2};
x += offset;
max -= offset;
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < max; x += step)
{
fp32_t e = fp32_t::Tan(x);
double r = std::tan(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
// EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Tan: max error = " << max_error << std::endl;
// std::cout << "Tan: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, Tan_32_32)
{
FixedPoint<32, 32> one(1);
FixedPoint<32, 32> one_point_five(1.5);
FixedPoint<32, 32> huge(2000);
FixedPoint<32, 32> tiny(0, fp32_t::SMALLEST_FRACTION);
FixedPoint<32, 32> e1 = fp64_t::Tan(one);
FixedPoint<32, 32> e2 = fp64_t::Tan(one_point_five);
FixedPoint<32, 32> e3 = fp64_t::Tan(fp64_t::_0);
FixedPoint<32, 32> e4 = fp64_t::Tan(huge);
FixedPoint<32, 32> e5 = fp64_t::Tan(tiny);
FixedPoint<32, 32> e6 = fp64_t::Tan(fp64_t::CONST_PI);
FixedPoint<32, 32> e7 = fp64_t::Tan(-fp64_t::CONST_PI);
FixedPoint<32, 32> e8 = fp64_t::Tan(fp64_t::CONST_PI * 2);
FixedPoint<32, 32> e9 = fp64_t::Tan(fp64_t::CONST_PI * 4);
FixedPoint<32, 32> e10 = fp64_t::Tan(fp64_t::CONST_PI * 100);
FixedPoint<32, 32> e11 = fp64_t::Tan(fp64_t::CONST_PI_4);
FixedPoint<32, 32> e12 = fp64_t::Tan(-fp64_t::CONST_PI_4);
FixedPoint<32, 32> e13 = fp64_t::Tan(fp64_t::CONST_PI_4 * 3);
double delta = static_cast<double>(e1) - std::tan(static_cast<double>(one));
EXPECT_NEAR(delta / std::tan(static_cast<double>(one)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e2) - std::tan(static_cast<double>(one_point_five));
EXPECT_NEAR(delta / std::tan(static_cast<double>(one_point_five)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e3) - std::tan(static_cast<double>(fp64_t::_0));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e4) - std::tan(static_cast<double>(huge));
EXPECT_NEAR(delta / std::tan(static_cast<double>(huge)), 0.0, 0.012);
delta = static_cast<double>(e5) - std::tan(static_cast<double>(tiny));
EXPECT_NEAR(delta / std::tan(static_cast<double>(tiny)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e6) - std::tan(static_cast<double>(fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e7) - std::tan(static_cast<double>(-fp64_t::CONST_PI));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e8) - std::tan(static_cast<double>(fp64_t::CONST_PI * 2));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e9) - std::tan(static_cast<double>(fp64_t::CONST_PI * 4));
EXPECT_NEAR(delta, 0.0, static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e10) - std::tan(static_cast<double>(fp64_t::CONST_PI * 100));
EXPECT_NEAR(delta, 0.0, 0.001); // Sin for larger arguments loses precision
delta = static_cast<double>(e11) - std::tan(static_cast<double>(fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::tan(static_cast<double>(fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e12) - std::tan(static_cast<double>(-fp64_t::CONST_PI_4));
EXPECT_NEAR(delta / std::tan(static_cast<double>(-fp64_t::CONST_PI_4)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
delta = static_cast<double>(e13) - std::tan(static_cast<double>(fp64_t::CONST_PI_4 * 3));
EXPECT_NEAR(delta / std::tan(static_cast<double>(fp64_t::CONST_PI_4 * 3)), 0.0,
static_cast<double>(fp64_t::TOLERANCE));
// (843, private) Replace with IsInfinity()
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Tan(fp64_t::CONST_PI_2)));
EXPECT_TRUE(fp64_t::IsNegInfinity(fp64_t::Tan(-fp64_t::CONST_PI_2)));
fp64_t step{0.0001}, offset{step * 100};
fp64_t x{-fp64_t::CONST_PI_2}, max{fp64_t::CONST_PI_2};
x += offset;
max -= offset;
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp64_t::TOLERANCE);
for (; x < max; x += step)
{
fp64_t e = fp64_t::Tan(x);
double r = std::tan(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
// EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "Tan: max error = " << max_error << std::endl;
// std::cout << "Tan: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ASin_16_16)
{
fp32_t step{0.001};
fp32_t x{-0.99};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 1.0; x += step)
{
fp32_t e = fp32_t::ASin(x);
double r = std::asin(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ASin: max error = " << max_error << std::endl;
// std::cout << "ASin: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ASin_32_32)
{
fp64_t step{0.0001};
fp64_t x{-0.999};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 1.0; x += step)
{
fp64_t e = fp64_t::ASin(x);
double r = std::asin(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ASin: max error = " << max_error << std::endl;
// std::cout << "ASin: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ACos_16_16)
{
fp32_t step{0.001};
fp32_t x{-0.99};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 1.0; x += step)
{
fp32_t e = fp32_t::ACos(x);
double r = std::acos(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ACos: max error = " << max_error << std::endl;
// std::cout << "ACos: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ACos_32_32)
{
fp64_t step{0.0001};
fp64_t x{-1.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 1.0; x += step)
{
fp64_t e = fp64_t::ACos(x);
double r = std::acos(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ACos: max error = " << max_error << std::endl;
// std::cout << "ACos: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATan_16_16)
{
fp32_t step{0.001};
fp32_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp32_t e = fp32_t::ATan(x);
double r = std::atan(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATan: max error = " << max_error << std::endl;
// std::cout << "ATan: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATan_32_32)
{
fp64_t step{0.0001};
fp64_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::ATan(x);
double r = std::atan(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATan: max error = " << max_error << std::endl;
// std::cout << "ATan: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATan2_16_16)
{
fp32_t step{0.01};
fp32_t x{-2.0};
fp32_t y{-2.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 2.0; x += step)
{
for (; y < 2.0; y += step)
{
fp32_t e = fp32_t::ATan2(y, x);
double r = std::atan2(static_cast<double>(y), static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATan2: max error = " << max_error << std::endl;
// std::cout << "ATan2: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATan2_32_32)
{
fp64_t step{0.0001};
fp64_t x{-2.0};
fp64_t y{-2.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 2.0; x += step)
{
for (; y < 2.0; y += step)
{
fp64_t e = fp64_t::ATan2(y, x);
double r = std::atan2(static_cast<double>(y), static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATan2: max error = " << max_error << std::endl;
// std::cout << "ATan2: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, SinH_16_16)
{
fp32_t step{0.001};
fp32_t x{-3.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2.0 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < 3.0; x += step)
{
fp32_t e = fp32_t::SinH(x);
double r = std::sinh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "SinH: max error = " << max_error << std::endl;
// std::cout << "SinH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, SinH_32_32)
{
fp64_t step{0.0001};
fp64_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::SinH(x);
double r = std::sinh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "SinH: max error = " << max_error << std::endl;
// std::cout << "SinH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, CosH_16_16)
{
fp32_t step{0.001};
fp32_t x{-3.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2.0 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < 3.0; x += step)
{
fp32_t e = fp32_t::CosH(x);
double r = std::cosh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "CosH: max error = " << max_error << std::endl;
// std::cout << "CosH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, CosH_32_32)
{
fp64_t step{0.0001};
fp64_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::CosH(x);
double r = std::cosh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "CosH: max error = " << max_error << std::endl;
// std::cout << "CosH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, TanH_16_16)
{
fp32_t step{0.001};
fp32_t x{-3.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp32_t::TOLERANCE);
for (; x < 3.0; x += step)
{
fp32_t e = fp32_t::TanH(x);
double r = std::tanh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "TanH: max error = " << max_error << std::endl;
// std::cout << "TanH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, TanH_32_32)
{
fp64_t step{0.0001};
fp64_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::TanH(x);
double r = std::tanh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "TanH: max error = " << max_error << std::endl;
// std::cout << "TanH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ASinH_16_16)
{
fp32_t step{0.001};
fp32_t x{-3.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < 3.0; x += step)
{
fp32_t e = fp32_t::ASinH(x);
double r = std::asinh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ASinH: max error = " << max_error << std::endl;
// std::cout << "ASinH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ASinH_32_32)
{
fp64_t step{0.0001};
fp64_t x{-5.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::ASinH(x);
double r = std::asinh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ASinH: max error = " << max_error << std::endl;
// std::cout << "ASinH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ACosH_16_16)
{
fp32_t step{0.001};
fp32_t x{1.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < 3.0; x += step)
{
fp32_t e = fp32_t::ACosH(x);
double r = std::acosh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ACosH: max error = " << max_error << std::endl;
// std::cout << "ACosH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ACosH_32_32)
{
fp64_t step{0.0001};
fp64_t x{1.0};
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp64_t::TOLERANCE);
for (; x < 5.0; x += step)
{
fp64_t e = fp64_t::ACosH(x);
double r = std::acosh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ACosH: max error = " << max_error << std::endl;
// std::cout << "ACosH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATanH_16_16)
{
fp32_t step{0.001}, offset{step * 10};
fp32_t x{-1.0}, max{1.0};
x += offset;
max -= offset;
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp32_t::TOLERANCE);
for (; x < max; x += step)
{
fp32_t e = fp32_t::ATanH(x);
double r = std::atanh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, 2 * tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATamH: max error = " << max_error << std::endl;
// std::cout << "ATanH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, ATanH_32_32)
{
fp64_t step{0.0001}, offset{step * 10};
fp64_t x{-1.0}, max{1.0};
x += offset;
max -= offset;
double max_error = 0, avg_error = 0;
std::size_t iterations = 0;
double tolerance = 2 * static_cast<double>(fp64_t::TOLERANCE);
for (; x < max; x += step)
{
fp64_t e = fp64_t::ATanH(x);
double r = std::atanh(static_cast<double>(x));
double delta = std::abs(static_cast<double>(e - r));
max_error = std::max(max_error, delta);
avg_error += delta;
iterations++;
}
avg_error /= static_cast<double>(iterations);
EXPECT_NEAR(max_error, 0.0, tolerance);
EXPECT_NEAR(avg_error, 0.0, tolerance);
// std::cout << "ATanH: max error = " << max_error << std::endl;
// std::cout << "ATanH: avg error = " << avg_error << std::endl;
}
TEST(FixedPointTest, NanInfinity_16_16)
{
fp32_t m_inf{fp32_t::NEGATIVE_INFINITY};
fp32_t p_inf{fp32_t::POSITIVE_INFINITY};
// Basic checks
EXPECT_TRUE(fp32_t::IsInfinity(m_inf));
EXPECT_TRUE(fp32_t::IsNegInfinity(m_inf));
EXPECT_TRUE(fp32_t::IsInfinity(p_inf));
EXPECT_TRUE(fp32_t::IsPosInfinity(p_inf));
EXPECT_FALSE(fp32_t::IsNegInfinity(p_inf));
EXPECT_FALSE(fp32_t::IsPosInfinity(m_inf));
// Absolute value
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Abs(m_inf)));
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Abs(p_inf)));
EXPECT_EQ(fp32_t::Sign(m_inf), -fp32_t::_1);
EXPECT_EQ(fp32_t::Sign(p_inf), fp32_t::_1);
// Comparison checks
EXPECT_FALSE(m_inf < m_inf);
EXPECT_TRUE(m_inf <= m_inf);
EXPECT_TRUE(m_inf < p_inf);
EXPECT_TRUE(m_inf < fp32_t::_0);
EXPECT_TRUE(m_inf < fp32_t::FP_MIN);
EXPECT_TRUE(m_inf < fp32_t::FP_MAX);
EXPECT_TRUE(m_inf < fp32_t::FP_MAX);
EXPECT_FALSE(p_inf > p_inf);
EXPECT_TRUE(p_inf >= p_inf);
EXPECT_TRUE(p_inf > m_inf);
EXPECT_TRUE(p_inf > fp32_t::_0);
EXPECT_TRUE(p_inf > fp32_t::FP_MIN);
EXPECT_TRUE(p_inf > fp32_t::FP_MAX);
// Addition checks
// (-∞) + (-∞) = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(m_inf + m_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) + (+∞) = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(p_inf + p_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (-∞) + (+∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(m_inf + p_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// (+∞) + (-∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(p_inf + m_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Subtraction checks
// (-∞) - (+∞) = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(m_inf - p_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) - (-∞) = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(p_inf - m_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (-∞) - (-∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(m_inf - m_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// (+∞) - (+∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(p_inf - p_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Multiplication checks
// (-∞) * (+∞) = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(m_inf * p_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) * (+∞) = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(p_inf * p_inf));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// 0 * (+∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::_0 * p_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// 0 * (-∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::_0 * m_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Division checks
// 0 / (+∞) = 0
fp32_t::StateClear();
EXPECT_EQ(fp32_t::_0 / p_inf, fp32_t::_0);
// 0 * (-∞) = 0
EXPECT_EQ(fp32_t::_0 / m_inf, fp32_t::_0);
// (-∞) / MAX_INT = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(m_inf / fp32_t::FP_MAX));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) / MAX_INT = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(p_inf / fp32_t::FP_MAX));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (-∞) / MIN_INT = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(m_inf / fp32_t::FP_MIN));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) / MIN_INT = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(p_inf / fp32_t::FP_MIN));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) / (+∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(p_inf / p_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// (-∞) / (+∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(m_inf / p_inf));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Exponential checks
// e ^ (0/0) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Exp(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// e ^ (+∞) = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Exp(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// this is actually normal operation, does not modify the state
// e ^ (-∞) = 0
fp32_t::StateClear();
EXPECT_EQ(fp32_t::Exp(m_inf), fp32_t::_0);
// x^y checks
// (-∞) ^ (-∞) = 0
fp32_t::StateClear();
EXPECT_EQ(fp32_t::Pow(m_inf, m_inf), fp32_t::_0);
// (-∞) ^ 0 = 1
fp32_t::StateClear();
EXPECT_EQ(fp32_t::Pow(m_inf, fp32_t::_0), fp32_t::_1);
// (+∞) ^ 0 = 1
EXPECT_EQ(fp32_t::Pow(p_inf, fp32_t::_0), fp32_t::_1);
// 0 ^ 0 = 1
EXPECT_EQ(fp32_t::Pow(fp32_t::_0, fp32_t::_0), fp32_t::_1);
// 0 ^ (-1) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Pow(fp32_t::_0, -fp32_t::_1)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// (-∞) ^ 1 = -∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(fp32_t::Pow(m_inf, fp32_t::_1)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// (+∞) ^ 1 = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Pow(p_inf, fp32_t::_1)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// x ^ (+∞) = +∞, |x| > 1
fp32_t x1{1.5};
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Pow(x1, p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// x ^ (-∞) = 0, |x| > 1
EXPECT_EQ(fp32_t::Pow(x1, m_inf), fp32_t::_0);
// x ^ (+∞) = 0, |x| < 1
fp32_t x2{0.5};
EXPECT_EQ(fp32_t::Pow(x2, p_inf), fp32_t::_0);
// x ^ (-∞) = 0, |x| < 1
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::Pow(x2, m_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// 1 ^ (-∞) = 1
EXPECT_EQ(fp32_t::Pow(fp32_t::_1, m_inf), fp32_t::_1);
// 1 ^ (-∞) = 1
EXPECT_EQ(fp32_t::Pow(fp32_t::_1, p_inf), fp32_t::_1);
// (-1) ^ (-∞) = 1
EXPECT_EQ(fp32_t::Pow(-fp32_t::_1, m_inf), fp32_t::_1);
// (-1) ^ (-∞) = 1
EXPECT_EQ(fp32_t::Pow(-fp32_t::_1, p_inf), fp32_t::_1);
// Logarithm checks
// Log(NaN) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Log(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Log(-∞) = NaN
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Log(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Log(+∞) = +∞
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsInfinity(fp32_t::Log(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// Trigonometry checks
// Sin/Cos/Tan(NaN)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Sin(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Cos(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Tan(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// Sin/Cos/Tan(+/-∞)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Sin(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Sin(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Cos(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Cos(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Tan(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::Tan(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// ASin/ACos/ATan/ATan2(NaN)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ASin(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ACos(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATan(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATan2(fp32_t::_0 / fp32_t::_0, fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATan2(fp32_t::_0, fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// ASin/ACos/ATan(+/-∞)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ASin(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ASin(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ACos(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ACos(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// ATan2(+/-∞)
fp32_t::StateClear();
EXPECT_EQ(fp32_t::ATan(m_inf), -fp32_t::CONST_PI_2);
EXPECT_EQ(fp32_t::ATan(p_inf), fp32_t::CONST_PI_2);
EXPECT_EQ(fp32_t::ATan2(fp32_t::_1, m_inf), fp32_t::CONST_PI);
EXPECT_EQ(fp32_t::ATan2(-fp32_t::_1, m_inf), -fp32_t::CONST_PI);
EXPECT_EQ(fp32_t::ATan2(fp32_t::_1, p_inf), fp32_t::_0);
EXPECT_EQ(fp32_t::ATan2(m_inf, m_inf), -fp32_t::CONST_PI_4 * 3);
EXPECT_EQ(fp32_t::ATan2(p_inf, m_inf), fp32_t::CONST_PI_4 * 3);
EXPECT_EQ(fp32_t::ATan2(m_inf, p_inf), -fp32_t::CONST_PI_4);
EXPECT_EQ(fp32_t::ATan2(p_inf, p_inf), fp32_t::CONST_PI_4);
EXPECT_EQ(fp32_t::ATan2(m_inf, fp32_t::_1), -fp32_t::CONST_PI_2);
EXPECT_EQ(fp32_t::ATan2(p_inf, fp32_t::_1), fp32_t::CONST_PI_2);
// SinH/CosH/TanH(NaN)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::SinH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::CosH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::TanH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// SinH/CosH/TanH(+/-∞)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(fp32_t::SinH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::SinH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::CosH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::CosH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(fp32_t::TanH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::TanH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
// ASinH/ACosH/ATanH(NaN)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ASinH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ACosH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATanH(fp32_t::_0 / fp32_t::_0)));
EXPECT_TRUE(fp32_t::IsStateNaN());
// SinH/CosH/TanH(+/-∞)
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNegInfinity(fp32_t::ASinH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::ASinH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ACosH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsPosInfinity(fp32_t::ACosH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateInfinity());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATanH(m_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
fp32_t::StateClear();
EXPECT_TRUE(fp32_t::IsNaN(fp32_t::ATanH(p_inf)));
EXPECT_TRUE(fp32_t::IsStateNaN());
}
TEST(FixedPointTest, NanInfinity_32_32)
{
fp64_t m_inf{fp64_t::NEGATIVE_INFINITY};
fp64_t p_inf{fp64_t::POSITIVE_INFINITY};
// Basic checks
EXPECT_TRUE(fp64_t::IsInfinity(m_inf));
EXPECT_TRUE(fp64_t::IsNegInfinity(m_inf));
EXPECT_TRUE(fp64_t::IsInfinity(p_inf));
EXPECT_TRUE(fp64_t::IsPosInfinity(p_inf));
EXPECT_FALSE(fp64_t::IsNegInfinity(p_inf));
EXPECT_FALSE(fp64_t::IsPosInfinity(m_inf));
// Absolute value
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Abs(m_inf)));
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Abs(p_inf)));
EXPECT_EQ(fp64_t::Sign(m_inf), -fp64_t::_1);
EXPECT_EQ(fp64_t::Sign(p_inf), fp64_t::_1);
// Comparison checks
EXPECT_FALSE(m_inf < m_inf);
EXPECT_TRUE(m_inf <= m_inf);
EXPECT_TRUE(m_inf < p_inf);
EXPECT_TRUE(m_inf < fp64_t::_0);
EXPECT_TRUE(m_inf < fp64_t::FP_MIN);
EXPECT_TRUE(m_inf < fp64_t::FP_MAX);
EXPECT_TRUE(m_inf < fp64_t::FP_MAX);
EXPECT_FALSE(p_inf > p_inf);
EXPECT_TRUE(p_inf >= p_inf);
EXPECT_TRUE(p_inf > m_inf);
EXPECT_TRUE(p_inf > fp64_t::_0);
EXPECT_TRUE(p_inf > fp64_t::FP_MIN);
EXPECT_TRUE(p_inf > fp64_t::FP_MAX);
// Addition checks
// (-∞) + (-∞) = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(m_inf + m_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) + (+∞) = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(p_inf + p_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (-∞) + (+∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(m_inf + p_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// (+∞) + (-∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(p_inf + m_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Subtraction checks
// (-∞) - (+∞) = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(m_inf - p_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) - (-∞) = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(p_inf - m_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (-∞) - (-∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(m_inf - m_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// (+∞) - (+∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(p_inf - p_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Multiplication checks
// (-∞) * (+∞) = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(m_inf * p_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) * (+∞) = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(p_inf * p_inf));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// 0 * (+∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::_0 * p_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// 0 * (-∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::_0 * m_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Division checks
// 0 / (+∞) = 0
fp64_t::StateClear();
EXPECT_EQ(fp64_t::_0 / p_inf, fp64_t::_0);
// 0 * (-∞) = 0
EXPECT_EQ(fp64_t::_0 / m_inf, fp64_t::_0);
// (-∞) / MAX_INT = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(m_inf / fp64_t::FP_MAX));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) / MAX_INT = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(p_inf / fp64_t::FP_MAX));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (-∞) / MIN_INT = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(m_inf / fp64_t::FP_MIN));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) / MIN_INT = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(p_inf / fp64_t::FP_MIN));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) / (+∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(p_inf / p_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// (-∞) / (+∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(m_inf / p_inf));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Exponential checks
// e ^ (0/0) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Exp(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// e ^ (+∞) = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Exp(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// this is actually normal operation, does not modify the state
// e ^ (-∞) = 0
fp64_t::StateClear();
EXPECT_EQ(fp64_t::Exp(m_inf), fp64_t::_0);
// x^y checks
// (-∞) ^ (-∞) = 0
fp64_t::StateClear();
EXPECT_EQ(fp64_t::Pow(m_inf, m_inf), fp64_t::_0);
// (-∞) ^ 0 = 1
fp64_t::StateClear();
EXPECT_EQ(fp64_t::Pow(m_inf, fp64_t::_0), fp64_t::_1);
// (+∞) ^ 0 = 1
EXPECT_EQ(fp64_t::Pow(p_inf, fp64_t::_0), fp64_t::_1);
// 0 ^ 0 = 1
EXPECT_EQ(fp64_t::Pow(fp64_t::_0, fp64_t::_0), fp64_t::_1);
// 0 ^ (-1) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Pow(fp64_t::_0, -fp64_t::_1)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// (-∞) ^ 1 = -∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(fp64_t::Pow(m_inf, fp64_t::_1)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// (+∞) ^ 1 = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Pow(p_inf, fp64_t::_1)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// x ^ (+∞) = +∞, |x| > 1
fp64_t x1{1.5};
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Pow(x1, p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// x ^ (-∞) = 0, |x| > 1
EXPECT_EQ(fp64_t::Pow(x1, m_inf), fp64_t::_0);
// x ^ (+∞) = 0, |x| < 1
fp64_t x2{0.5};
EXPECT_EQ(fp64_t::Pow(x2, p_inf), fp64_t::_0);
// x ^ (-∞) = 0, |x| < 1
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::Pow(x2, m_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// 1 ^ (-∞) = 1
EXPECT_EQ(fp64_t::Pow(fp64_t::_1, m_inf), fp64_t::_1);
// 1 ^ (-∞) = 1
EXPECT_EQ(fp64_t::Pow(fp64_t::_1, p_inf), fp64_t::_1);
// (-1) ^ (-∞) = 1
EXPECT_EQ(fp64_t::Pow(-fp64_t::_1, m_inf), fp64_t::_1);
// (-1) ^ (-∞) = 1
EXPECT_EQ(fp64_t::Pow(-fp64_t::_1, p_inf), fp64_t::_1);
// Logarithm checks
// Log(NaN) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Log(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Log(-∞) = NaN
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Log(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Log(+∞) = +∞
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsInfinity(fp64_t::Log(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// Trigonometry checks
// Sin/Cos/Tan(NaN)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Sin(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Cos(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Tan(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// Sin/Cos/Tan(+/-∞)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Sin(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Sin(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Cos(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Cos(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Tan(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::Tan(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// ASin/ACos/ATan/ATan2(NaN)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ASin(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ACos(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATan(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATan2(fp64_t::_0 / fp64_t::_0, fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATan2(fp64_t::_0, fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// ASin/ACos/ATan(+/-∞)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ASin(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ASin(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ACos(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ACos(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// ATan2(+/-∞)
fp64_t::StateClear();
EXPECT_EQ(fp64_t::ATan(m_inf), -fp64_t::CONST_PI_2);
EXPECT_EQ(fp64_t::ATan(p_inf), fp64_t::CONST_PI_2);
EXPECT_EQ(fp64_t::ATan2(fp64_t::_1, m_inf), fp64_t::CONST_PI);
EXPECT_EQ(fp64_t::ATan2(-fp64_t::_1, m_inf), -fp64_t::CONST_PI);
EXPECT_EQ(fp64_t::ATan2(fp64_t::_1, p_inf), fp64_t::_0);
EXPECT_EQ(fp64_t::ATan2(m_inf, m_inf), -fp64_t::CONST_PI_4 * 3);
EXPECT_EQ(fp64_t::ATan2(p_inf, m_inf), fp64_t::CONST_PI_4 * 3);
EXPECT_EQ(fp64_t::ATan2(m_inf, p_inf), -fp64_t::CONST_PI_4);
EXPECT_EQ(fp64_t::ATan2(p_inf, p_inf), fp64_t::CONST_PI_4);
EXPECT_EQ(fp64_t::ATan2(m_inf, fp64_t::_1), -fp64_t::CONST_PI_2);
EXPECT_EQ(fp64_t::ATan2(p_inf, fp64_t::_1), fp64_t::CONST_PI_2);
// SinH/CosH/TanH(NaN)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::SinH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::CosH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::TanH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// SinH/CosH/TanH(+/-∞)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(fp64_t::SinH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::SinH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::CosH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::CosH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(fp64_t::TanH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::TanH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
// ASinH/ACosH/ATanH(NaN)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ASinH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ACosH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATanH(fp64_t::_0 / fp64_t::_0)));
EXPECT_TRUE(fp64_t::IsStateNaN());
// SinH/CosH/TanH(+/-∞)
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNegInfinity(fp64_t::ASinH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::ASinH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ACosH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsPosInfinity(fp64_t::ACosH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateInfinity());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATanH(m_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
fp64_t::StateClear();
EXPECT_TRUE(fp64_t::IsNaN(fp64_t::ATanH(p_inf)));
EXPECT_TRUE(fp64_t::IsStateNaN());
}
|
; double copysign(double x, double y)
SECTION code_fp_math48
PUBLIC cm48_sccz80_copysign
EXTERN am48_copysign, cm48_sccz80p_dparam2
cm48_sccz80_copysign:
call cm48_sccz80p_dparam2
; AC'= y
; AC = x
exx
jp am48_copysign
|
db 0 ; species ID placeholder
db 90, 90, 85, 100, 125, 90
; hp atk def spd sat sdf
db ELECTRIC, FLYING ; type
db 3 ; catch rate
db 216 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_UNKNOWN ; gender ratio
db 100 ; unknown 1
db 80 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/zapdos/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_NONE, EGG_NONE ; egg groups
; tm/hm learnset
tmhm CURSE, ROAR, TOXIC, ZAP_CANNON, ROCK_SMASH, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, RAIN_DANCE, THUNDER, RETURN, FEATHERDANCE, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, SWIFT, PURSUIT, REST, STEEL_WING, FLY, FLASH, THUNDERBOLT
; end
|
; A071214: Number of labeled ordered trees with n nodes such that the root is smaller than all its children.
; Submitted by Jon Maiga
; 1,5,46,614,10716,230712,5903472,174942000,5890370400,222069752640,9265980286080,423888544154880,21094789126924800,1134492559101619200,65567415318776985600,4052502049455940147200,266725354163752808755200,18624661769541550593024000
mov $1,2
add $1,$0
mov $3,1
lpb $0
sub $0,1
gcd $2,$1
add $2,1
mul $3,$2
add $3,$1
mul $1,$2
lpe
sub $1,$3
mov $0,$1
|
; A138524: a(n) = Sum_{k=1..n} (2*k)!.
; Submitted by Jamie Morken(w3)
; 2,26,746,41066,3669866,482671466,87660962666,21010450850666,6423384156578666,2439325392333218666,1126440053169940898666,621574841786409380258666,403913035968392044964258666,305292257647682252546468258666,265558152069838740888854948258666,263396395085763368908106867108258666,295496195434689904216526716510628258666,372288822985335907372215974867345828258666,523394906289586447667379440074941637028258666,816438678154187320793278649036190835909028258666
mov $1,1
mov $2,$0
add $2,2
add $2,$0
lpb $2
mul $1,$2
sub $2,1
mul $1,$2
add $1,1
sub $2,1
lpe
mov $0,$1
sub $0,1
|
; A131973: Period 8: repeat 121, 242, 363, 484, 605, 726, 847, 968.
; 121,242,363,484,605,726,847,968,121,242,363,484,605,726,847,968,121,242,363,484,605,726,847,968,121,242,363,484,605,726,847,968,121,242,363,484,605,726,847,968,121,242,363,484,605,726,847,968
mov $1,$0
mod $1,8
mul $1,121
add $1,121
|
bits 64
default rel
section .text
global pal_execute_vmptrld
pal_execute_vmptrld :
vmptrld [rdi]
ret
|
#include <Switch/Switch>
using namespace System;
namespace Examples {
class Program {
public:
// The main entry point for the application.
static void Main() {
Array<Boolean > hasServiceCharges = {true, false};
double subtotal = 120.62;
double shippingCharge = 2.50;
double serviceCharge = 5.00;
for (Boolean hasServiceCharge : hasServiceCharges) {
double total = subtotal + shippingCharge + (hasServiceCharge ? serviceCharge : 0);
Console::WriteLine("hasServiceCharge = {0}: The total is ${1}.", hasServiceCharge, total);
}
}
};
}
startup_(Examples::Program);
// This code produces the following output:
//
// hasServiceCharge = True: The total is $128.12.
// hasServiceCharge = False: The total is $123.12.
|
; A198969: (11*9^n-1)/2.
; 5,49,445,4009,36085,324769,2922925,26306329,236756965,2130812689,19177314205,172595827849,1553362450645,13980262055809,125822358502285,1132401226520569,10191611038685125,91724499348166129,825520494133495165,7429684447201456489,66867160024813108405,601804440223317975649,5416239962009861780845,48746159658088756027609,438715436922798804248485,3948438932305189238236369,35535950390746703144127325,319823553516720328297145929,2878411981650482954674313365,25905707834854346592068820289
mov $1,9
pow $1,$0
mul $1,11
sub $1,6
div $1,2
add $1,3
mov $0,$1
|
; ==========================================================
; COMMODORE 64 - Examples in 6502 Assembly language
; © Digitsensitive; digit.sensitivee@gmail.com
; Snake
; ==========================================================
.include "src/include/constants.asm"
; ----------------------------------------------------------
; Labels
; ----------------------------------------------------------
; each sprite is 3 bytes wide with 21 lines = 63 bytes required for shape
; but it actually uses 64 bytes
; the value @ the pointer times 64 equals
; the starting location of the sprite shape data table
spr0ShapeData = $0340 ; = 13 * 64 = 832
; snake properties
; current direction (up = 1, down = 3, left = 5, right = 7)
currentDir = 7
; up (1+2 byte), down (3+4 byte), left (5+6 byte), right (7+8 byte)
dirs .byte $00,$02,$00,$01,$02,$00,$01,$00
; input keys
ENTER = 13
KEY_W = 87
KEY_A = 65
KEY_S = 83
KEY_D = 68
; ----------------------------------------------------------
; Init and create sprite
; ----------------------------------------------------------
*=$4000 ; sys 16384
init jsr $e544 ; clear the screen
lda #%00001101 ; use block 13 for sprite 0
sta SPRITE_POINTERS
lda #%00000001 ; load accumulator with value 1
sta SPRITE_ENABLE_REGISTER ; enable sprite 0
lda #CYAN ; use cyan for sprite 0
sta SPRITE_0_COLOR_REGISTER ; load cyan to color register 0
ldx #0
lda #0
build lda spr0,x ; get byte from sprite0+x
sta spr0ShapeData,x ; store byte at spr0ShapeData+x
inx
cpx #63
bne build
; set position
lda #%00000000 ; restrict horizontal position to 0-255
sta MSIGX
; starting sprite location
ldx #100
ldy #70
stx SP0X
sty SP0Y
; ----------------------------------------------------------
; Main Loop
; ----------------------------------------------------------
loop jsr input
jmp loop
; ----------------------------------------------------------
; Evaluate Input
; ----------------------------------------------------------
input ; TODO: Is "lda $ff" a better alternative?
jsr SCNKEY ; jump to scan keyboard
jsr GETIN ; jump to get a character
; cmp (short for "CoMPare")
; compares contents of accumulator against the specified operand
cmp #KEY_W
beq upKey
cmp #KEY_S
beq downKey
cmp #KEY_A
beq leftKey
cmp #KEY_D
beq rightKey
cmp #ENTER
beq end
rts
upKey ldy SP0Y
dey
sty SP0Y
rts
downKey ldy SP0Y
iny
sty SP0Y
rts
leftKey ldx SP0X
dex
stx SP0X
cpx #255
rts
lda #0
sta MSIGX
rts
rightKey ldx SP0X
inx
stx SP0X
rts
; ----------------------------------------------------------
; Clean up at the end
; ----------------------------------------------------------
end jsr CLEAR
lda #0
sta SPRITE_ENABLE_REGISTER
rts
; ----------------------------------------------------------
; Data
; ----------------------------------------------------------
; snake sprite
spr0 .byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
.byte $FF, $FF, $FF
|
;**********************************************************************
;Led headlamp
;PIC 16F616
;internal 8MHz
;------------------------------
; Jakub Kaderka
; jakub.kaderka@gmail.com
; 2015
;------------------------------
; pwm.asm
;------------------------------
; Pwm generator uses tmr0 interrupt which sets the pwm frequency (2048Hz),
; After the timer overflow, pwm outputs are driven to high or low, based
; on the pwm duties:
; duty <= 50% : set pin to high
; duty >= 50% : set pin to low
;
; Then after time given by pwm_time1 toggles pin which corresponds to
; shorted pulse and wait for pwm_time2 loops. Finally, the second pin
; is toggled and the interrupt routine ends.
;
; This design takes up to 50% of the processing (pwm at 50%) time without
; depending ; on precise timing of other system jobs.
;
;
; To make interrupt routine as short as possible, the necessary pin
; output values and timing variables are calculated by pwm_update routine
; only once per pwm duty update.
;
; As the voltage drops with battery closing to end of it's capacity,
; the voltage generated by pwm is also decreasing. Therefore the AD
; task measures voltage few times a second and calculates necessary
; correction to pwm duty to keep the voltage stable.
;**********************************************************************
;---------------------------
; set outputs to values from pwm_data
; par1 and par2 defines bits to read
;---------------------------
PWM_SET macro par1, par2
bcf pwm1
btfsc pwm_data, par1
bsf pwm1
bcf pwm2
btfsc pwm_data, par2
bsf pwm2
endm
;---------------------------
; set pwm_tmp_data, par1 to 1 if pwm_tmp_data, par2 is 0
;---------------------------
PWM_TOGGLE_CONF macro par1, par2
bcf pwm_tmp_data, par1
btfss pwm_tmp_data, par2
bsf pwm_tmp_data, par1
endm
;---------------------------
; set pwm_tmp_data, par1 to pwm_tmp_data, par2
;---------------------------
PWM_COPY_CONF macro par1, par2
bcf pwm_tmp_data, par1
btfsc pwm_tmp_data, par2
bsf pwm_tmp_data, par1
endm
;-----------------------------------
; Update pwm generator duties
;
; calculate variables for pwm generator (based on pwm_dutyX)
; and update them when finished
;
; Calculated values sets the time of the shorter pulse (pwm_time1)
; and the difference between shorter and longer part (pwm_time2)
;
; States of the outputs in each of the three parts of the pwm
; executions (initial, firts pulse finished, second finished)
; are stored in pwm_data
;
; disables interrupts momentarily
;-----------------------------------
pwm_update
clrf pwm_tmp_data
;first get initial values and timing of shorter part of the pulse
movlw PWM_DUTY_HALF
subwf pwm_duty1, w ;compare 50% and actual value
btfsc status, c
goto pwm_update_2 ;over 50%
bsf pwm_tmp_data, pstart1 ;under 50%
movf pwm_duty1, w
movwf pwm_tmp1 ;just copy the duty for further computation
pwm_update_1
movlw PWM_DUTY_HALF
subwf pwm_duty2, w ;compare 50% and actual value
btfsc status, c
goto pwm_update_3 ;over 50%
bsf pwm_tmp_data, pstart2 ;under 50%
movf pwm_duty2, w
movwf pwm_tmp2 ;just copy the duty for further computation
goto pwm_update_4
;duty1 over 50
pwm_update_2
movf pwm_duty1, w
sublw PWM_DUTY_FULL ;PWM_DUTY_FULL - pwm_duty
movwf pwm_tmp1
goto pwm_update_1
;duty2 over 50
pwm_update_3
movf pwm_duty2, w
sublw PWM_DUTY_FULL ;PWM_DUTY_FULL - pwm_duty
movwf pwm_tmp2
;first bits and times are ready, compute middle and end bits
pwm_update_4
movf pwm_tmp1, w
subwf pwm_tmp2, w ;tmp2 - tmp1
btfsc status, z
goto pwm_update_same ;tmp2 == tmp1
btfss status, c
goto pwm_update_5 ;tmp1 > tmp2
;tmp1 < tmp2
PWM_TOGGLE_CONF pmiddle1, pstart1
PWM_COPY_CONF pmiddle2, pstart2
PWM_TOGGLE_CONF pend2, pmiddle2
PWM_COPY_CONF pend1, pmiddle1
movf pwm_tmp1, w
movwf pwm_tmp_time1 ;update shorter pulse time
subwf pwm_tmp2, w
movwf pwm_tmp_time2 ;tmp2-tmp1
goto pwm_update_var ;set the permanent values and return
;tmp1 > tmp2
pwm_update_5
PWM_TOGGLE_CONF pmiddle2, pstart2
PWM_COPY_CONF pmiddle1, pstart1
PWM_TOGGLE_CONF pend1, pmiddle1
PWM_COPY_CONF pend2, pmiddle2
movf pwm_tmp2, w
movwf pwm_tmp_time1 ;update shorter pulse time
subwf pwm_tmp1, w
movwf pwm_tmp_time2 ;tmp1-tmp2
goto pwm_update_var ;set the permanent values and return
;both pwm times are same
pwm_update_same
PWM_TOGGLE_CONF pmiddle1, pstart1
PWM_TOGGLE_CONF pmiddle2, pstart2
PWM_COPY_CONF pend1, pmiddle1
PWM_COPY_CONF pend2, pmiddle2 ;toggle middle and copy middle to end
clrf pwm_tmp_time2
movf pwm_tmp1, w
movwf pwm_tmp_time1 ;update time1 to pulse length and time2 to 0
goto pwm_update_var ;finally, update the real pwm values
;finally, copy values from tmp to permanent locations
;additionally, check for 100% or 0% duty cycles and update the data parts
;disables interrupts mometarily!
pwm_update_var
;final checks, fix the max/min duty variables
movf pwm_tmp1, f
btfsc status, z
goto pwm_update_var_1 ;pwm1 is 100% or 0%
pwm_update_var_3
movf pwm_tmp2, f
btfsc status, z
goto pwm_update_var_2
pwm_update_var_4
;update the times to avoid owerflow - pwm generator first do decfsz...
incf pwm_tmp_time1, w
btfss status, z ;check if incrementing wont't cause buffer overflow
incf pwm_tmp_time1, f
incf pwm_tmp_time2, w
btfss status, z
incf pwm_tmp_time2, f
;disable interrupts and copy data to the permanent location
bcf intcon, gie ;disable interrupt
movf pwm_tmp_data, w
movwf pwm_data
movf pwm_tmp_time1, w
movwf pwm_time1
movf pwm_tmp_time2, w
movwf pwm_time2 ;copy data
bsf intcon, gie ;reenable interrupt
return
;pwm 1 on 100% or 0%
pwm_update_var_1
PWM_TOGGLE_CONF pstart1, pstart1
PWM_COPY_CONF pmiddle1, pstart1
PWM_COPY_CONF pend1, pmiddle1
goto pwm_update_var_3
;pwm 2 on 100% or 0%
pwm_update_var_2
PWM_TOGGLE_CONF pstart2, pstart2
PWM_COPY_CONF pmiddle2, pstart2
PWM_COPY_CONF pend2, pmiddle2
goto pwm_update_var_4
;-----------------------------------
; Limit value in W to PWM_DUTY_FULL
; uses tmp
;-----------------------------------
pwm_duty_limit
movwf tmp
sublw PWM_DUTY_FULL ;full - new
btfss status, c
retlw PWM_DUTY_FULL ;new > full
movf tmp, w
return
;-----------------------------------
; Set pwm1 duty from W
; pwm_update must to be called to apply this change
;
; uses tmp and 1 level stack
;-----------------------------------
pwm1_set
call pwm_duty_limit
movwf pwm_duty1
return
;-----------------------------------
; Set pwm2 duty from W
; pwm_update must to be called to apply this change
;
; uses tmp and 1 level stack
;-----------------------------------
pwm2_set
call pwm_duty_limit
movwf pwm_duty2
return
|
copyright zengfr site:http://github.com/zengfr/romhack
003AEC lea (-$2,A1,D0.w), A1 [1p+28, boss+28, container+28, enemy+28, weapon+28]
003B06 bne $3b3a [1p+28, boss+28, container+28, enemy+28, weapon+28]
003B16 bpl $3b26 [1p+28, boss+28, container+28, enemy+28, weapon+28]
003B26 lea (-$2,A1,D0.w), A1 [1p+28, boss+28, container+28, enemy+28, weapon+28]
00A2C6 dbra D0, $a2c0
00A2E0 clr.b ($28,A4)
00A2E4 clr.b ($29,A4)
00AAAC jsr $3b02.w [1p+28]
copyright zengfr site:http://github.com/zengfr/romhack
|
#include "utils.hpp"
#include "mapnik_map.hpp"
#include "mapnik_image.hpp"
#if defined(GRID_RENDERER)
#include "mapnik_grid.hpp"
#endif
#include "mapnik_feature.hpp"
#include "mapnik_cairo_surface.hpp"
#ifdef SVG_RENDERER
#include <mapnik/svg/output/svg_renderer.hpp>
#endif
#include "mapnik_vector_tile.hpp"
#include "vector_tile_compression.hpp"
#include "vector_tile_composite.hpp"
#include "vector_tile_processor.hpp"
#include "vector_tile_projection.hpp"
#include "vector_tile_datasource_pbf.hpp"
#include "vector_tile_geometry_decoder.hpp"
#include "vector_tile_load_tile.hpp"
#include "object_to_container.hpp"
// mapnik
#include <mapnik/agg_renderer.hpp> // for agg_renderer
#include <mapnik/datasource_cache.hpp>
#include <mapnik/geometry/box2d.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/featureset.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include <mapnik/geometry/is_simple.hpp>
#include <mapnik/geometry/is_valid.hpp>
#include <mapnik/geometry/reprojection.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/hit_test_filter.hpp>
#include <mapnik/image_any.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/memory_datasource.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/request.hpp>
#include <mapnik/scale_denominator.hpp>
#include <mapnik/util/geometry_to_geojson.hpp>
#include <mapnik/util/feature_to_geojson.hpp>
#include <mapnik/version.hpp>
#if defined(GRID_RENDERER)
#include <mapnik/grid/grid.hpp> // for hit_grid, grid
#include <mapnik/grid/grid_renderer.hpp> // for grid_renderer
#endif
#ifdef HAVE_CAIRO
#include <mapnik/cairo/cairo_renderer.hpp>
#include <cairo.h>
#ifdef CAIRO_HAS_SVG_SURFACE
#include <cairo-svg.h>
#endif // CAIRO_HAS_SVG_SURFACE
#endif
// std
#include <set> // for set, etc
#include <sstream> // for operator<<, basic_ostream, etc
#include <string> // for string, char_traits, etc
#include <exception> // for exception
#include <vector> // for vector
// protozero
#include <protozero/pbf_reader.hpp>
namespace detail
{
struct p2p_result
{
explicit p2p_result() :
distance(-1),
x_hit(0),
y_hit(0) {}
double distance;
double x_hit;
double y_hit;
};
struct p2p_distance
{
p2p_distance(double x, double y)
: x_(x),
y_(y) {}
p2p_result operator() (mapnik::geometry::geometry_empty const& ) const
{
p2p_result p2p;
return p2p;
}
p2p_result operator() (mapnik::geometry::point<double> const& geom) const
{
p2p_result p2p;
p2p.x_hit = geom.x;
p2p.y_hit = geom.y;
p2p.distance = mapnik::distance(geom.x, geom.y, x_, y_);
return p2p;
}
p2p_result operator() (mapnik::geometry::multi_point<double> const& geom) const
{
p2p_result p2p;
for (auto const& pt : geom)
{
p2p_result p2p_sub = operator()(pt);
if (p2p_sub.distance >= 0 && (p2p.distance < 0 || p2p_sub.distance < p2p.distance))
{
p2p.x_hit = p2p_sub.x_hit;
p2p.y_hit = p2p_sub.y_hit;
p2p.distance = p2p_sub.distance;
}
}
return p2p;
}
p2p_result operator() (mapnik::geometry::line_string<double> const& geom) const
{
p2p_result p2p;
auto num_points = geom.size();
if (num_points > 1)
{
for (std::size_t i = 1; i < num_points; ++i)
{
auto const& pt0 = geom[i-1];
auto const& pt1 = geom[i];
double dist = mapnik::point_to_segment_distance(x_,y_,pt0.x,pt0.y,pt1.x,pt1.y);
if (dist >= 0 && (p2p.distance < 0 || dist < p2p.distance))
{
p2p.x_hit = pt0.x;
p2p.y_hit = pt0.y;
p2p.distance = dist;
}
}
}
return p2p;
}
p2p_result operator() (mapnik::geometry::multi_line_string<double> const& geom) const
{
p2p_result p2p;
for (auto const& line: geom)
{
p2p_result p2p_sub = operator()(line);
if (p2p_sub.distance >= 0 && (p2p.distance < 0 || p2p_sub.distance < p2p.distance))
{
p2p.x_hit = p2p_sub.x_hit;
p2p.y_hit = p2p_sub.y_hit;
p2p.distance = p2p_sub.distance;
}
}
return p2p;
}
p2p_result operator() (mapnik::geometry::polygon<double> const& poly) const
{
p2p_result p2p;
std::size_t num_rings = poly.size();
bool inside = false;
for (std::size_t ring_index = 0; ring_index < num_rings; ++ring_index)
{
auto const& ring = poly[ring_index];
auto num_points = ring.size();
if (num_points < 4)
{
if (ring_index == 0) // exterior
return p2p;
else // interior
continue;
}
for (std::size_t index = 1; index < num_points; ++index)
{
auto const& pt0 = ring[index - 1];
auto const& pt1 = ring[index];
// todo - account for tolerance
if (mapnik::detail::pip(pt0.x, pt0.y, pt1.x, pt1.y, x_,y_))
{
inside = !inside;
}
}
if (ring_index == 0 && !inside) return p2p;
}
if (inside) p2p.distance = 0;
return p2p;
}
p2p_result operator() (mapnik::geometry::multi_polygon<double> const& geom) const
{
p2p_result p2p;
for (auto const& poly: geom)
{
p2p_result p2p_sub = operator()(poly);
if (p2p_sub.distance >= 0 && (p2p.distance < 0 || p2p_sub.distance < p2p.distance))
{
p2p.x_hit = p2p_sub.x_hit;
p2p.y_hit = p2p_sub.y_hit;
p2p.distance = p2p_sub.distance;
}
}
return p2p;
}
p2p_result operator() (mapnik::geometry::geometry_collection<double> const& collection) const
{
// There is no current way that a geometry collection could be returned from a vector tile.
/* LCOV_EXCL_START */
p2p_result p2p;
for (auto const& geom: collection)
{
p2p_result p2p_sub = mapnik::util::apply_visitor((*this),geom);
if (p2p_sub.distance >= 0 && (p2p.distance < 0 || p2p_sub.distance < p2p.distance))
{
p2p.x_hit = p2p_sub.x_hit;
p2p.y_hit = p2p_sub.y_hit;
p2p.distance = p2p_sub.distance;
}
}
return p2p;
/* LCOV_EXCL_STOP */
}
double x_;
double y_;
};
}
detail::p2p_result path_to_point_distance(mapnik::geometry::geometry<double> const& geom, double x, double y)
{
return mapnik::util::apply_visitor(detail::p2p_distance(x,y), geom);
}
Nan::Persistent<v8::FunctionTemplate> VectorTile::constructor;
/**
* **`mapnik.VectorTile`**
* A tile generator built according to the [Mapbox Vector Tile](https://github.com/mapbox/vector-tile-spec)
* specification for compressed and simplified tiled vector data.
* Learn more about vector tiles [here](https://www.mapbox.com/developers/vector-tiles/).
*
* @class VectorTile
* @param {number} z - an integer zoom level
* @param {number} x - an integer x coordinate
* @param {number} y - an integer y coordinate
* @property {number} x - horizontal axis position
* @property {number} y - vertical axis position
* @property {number} z - the zoom level
* @property {number} tileSize - the size of the tile
* @property {number} bufferSize - the size of the tile's buffer
* @example
* var vt = new mapnik.VectorTile(9,112,195);
* console.log(vt.x, vt.y, vt.z); // 9, 112, 195
* console.log(vt.tileSize, vt.bufferSize); // 4096, 128
*/
void VectorTile::Initialize(v8::Local<v8::Object> target)
{
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> lcons = Nan::New<v8::FunctionTemplate>(VectorTile::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(Nan::New("VectorTile").ToLocalChecked());
Nan::SetPrototypeMethod(lcons, "render", render);
Nan::SetPrototypeMethod(lcons, "setData", setData);
Nan::SetPrototypeMethod(lcons, "setDataSync", setDataSync);
Nan::SetPrototypeMethod(lcons, "getData", getData);
Nan::SetPrototypeMethod(lcons, "getDataSync", getDataSync);
Nan::SetPrototypeMethod(lcons, "addData", addData);
Nan::SetPrototypeMethod(lcons, "addDataSync", addDataSync);
Nan::SetPrototypeMethod(lcons, "composite", composite);
Nan::SetPrototypeMethod(lcons, "compositeSync", compositeSync);
Nan::SetPrototypeMethod(lcons, "query", query);
Nan::SetPrototypeMethod(lcons, "queryMany", queryMany);
Nan::SetPrototypeMethod(lcons, "extent", extent);
Nan::SetPrototypeMethod(lcons, "bufferedExtent", bufferedExtent);
Nan::SetPrototypeMethod(lcons, "names", names);
Nan::SetPrototypeMethod(lcons, "layer", layer);
Nan::SetPrototypeMethod(lcons, "emptyLayers", emptyLayers);
Nan::SetPrototypeMethod(lcons, "paintedLayers", paintedLayers);
Nan::SetPrototypeMethod(lcons, "toJSON", toJSON);
Nan::SetPrototypeMethod(lcons, "toGeoJSON", toGeoJSON);
Nan::SetPrototypeMethod(lcons, "toGeoJSONSync", toGeoJSONSync);
Nan::SetPrototypeMethod(lcons, "addGeoJSON", addGeoJSON);
Nan::SetPrototypeMethod(lcons, "addImage", addImage);
Nan::SetPrototypeMethod(lcons, "addImageSync", addImageSync);
Nan::SetPrototypeMethod(lcons, "addImageBuffer", addImageBuffer);
Nan::SetPrototypeMethod(lcons, "addImageBufferSync", addImageBufferSync);
#if BOOST_VERSION >= 105600
Nan::SetPrototypeMethod(lcons, "reportGeometrySimplicity", reportGeometrySimplicity);
Nan::SetPrototypeMethod(lcons, "reportGeometrySimplicitySync", reportGeometrySimplicitySync);
Nan::SetPrototypeMethod(lcons, "reportGeometryValidity", reportGeometryValidity);
Nan::SetPrototypeMethod(lcons, "reportGeometryValiditySync", reportGeometryValiditySync);
#endif // BOOST_VERSION >= 105600
Nan::SetPrototypeMethod(lcons, "painted", painted);
Nan::SetPrototypeMethod(lcons, "clear", clear);
Nan::SetPrototypeMethod(lcons, "clearSync", clearSync);
Nan::SetPrototypeMethod(lcons, "empty", empty);
// properties
ATTR(lcons, "x", get_tile_x, set_tile_x);
ATTR(lcons, "y", get_tile_y, set_tile_y);
ATTR(lcons, "z", get_tile_z, set_tile_z);
ATTR(lcons, "tileSize", get_tile_size, set_tile_size);
ATTR(lcons, "bufferSize", get_buffer_size, set_buffer_size);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(), "info", info);
target->Set(Nan::New("VectorTile").ToLocalChecked(),lcons->GetFunction());
constructor.Reset(lcons);
}
VectorTile::VectorTile(std::uint64_t z,
std::uint64_t x,
std::uint64_t y,
std::uint32_t tile_size,
std::int32_t buffer_size) :
Nan::ObjectWrap(),
tile_(std::make_shared<mapnik::vector_tile_impl::merc_tile>(x, y, z, tile_size, buffer_size))
{
}
// For some reason coverage never seems to be considered here even though
// I have tested it and it does print
/* LCOV_EXCL_START */
VectorTile::~VectorTile()
{
}
/* LCOV_EXCL_STOP */
NAN_METHOD(VectorTile::New)
{
if (!info.IsConstructCall())
{
Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword");
return;
}
if (info[0]->IsExternal())
{
v8::Local<v8::External> ext = info[0].As<v8::External>();
void* ptr = ext->Value();
VectorTile* v = static_cast<VectorTile*>(ptr);
v->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
if (info.Length() < 3)
{
Nan::ThrowError("please provide a z, x, y");
return;
}
if (!info[0]->IsNumber() ||
!info[1]->IsNumber() ||
!info[2]->IsNumber())
{
Nan::ThrowTypeError("required parameters (z, x, and y) must be a integers");
return;
}
std::int64_t z = info[0]->IntegerValue();
std::int64_t x = info[1]->IntegerValue();
std::int64_t y = info[2]->IntegerValue();
if (z < 0 || x < 0 || y < 0)
{
Nan::ThrowTypeError("required parameters (z, x, and y) must be greater then or equal to zero");
return;
}
std::int64_t max_at_zoom = pow(2,z);
if (x >= max_at_zoom)
{
Nan::ThrowTypeError("required parameter x is out of range of possible values based on z value");
return;
}
if (y >= max_at_zoom)
{
Nan::ThrowTypeError("required parameter y is out of range of possible values based on z value");
return;
}
std::uint32_t tile_size = 4096;
std::int32_t buffer_size = 128;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 3)
{
if (!info[3]->IsObject())
{
Nan::ThrowTypeError("optional fourth argument must be an options object");
return;
}
options = info[3]->ToObject();
if (options->Has(Nan::New("tile_size").ToLocalChecked()))
{
v8::Local<v8::Value> opt = options->Get(Nan::New("tile_size").ToLocalChecked());
if (!opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'tile_size' must be a number");
return;
}
int tile_size_tmp = opt->IntegerValue();
if (tile_size_tmp <= 0)
{
Nan::ThrowTypeError("optional arg 'tile_size' must be greater then zero");
return;
}
tile_size = tile_size_tmp;
}
if (options->Has(Nan::New("buffer_size").ToLocalChecked()))
{
v8::Local<v8::Value> opt = options->Get(Nan::New("buffer_size").ToLocalChecked());
if (!opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'buffer_size' must be a number");
return;
}
buffer_size = opt->IntegerValue();
}
}
if (static_cast<double>(tile_size) + (2 * buffer_size) <= 0)
{
Nan::ThrowError("too large of a negative buffer for tilesize");
return;
}
VectorTile* d = new VectorTile(z, x, y, tile_size, buffer_size);
d->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
void _composite(VectorTile* target_vt,
std::vector<VectorTile*> & vtiles,
double scale_factor,
unsigned offset_x,
unsigned offset_y,
double area_threshold,
bool strictly_simple,
bool multi_polygon_union,
mapnik::vector_tile_impl::polygon_fill_type fill_type,
double scale_denominator,
bool reencode,
boost::optional<mapnik::box2d<double>> const& max_extent,
double simplify_distance,
bool process_all_rings,
std::string const& image_format,
mapnik::scaling_method_e scaling_method,
std::launch threading_mode)
{
// create map
mapnik::Map map(target_vt->tile_size(),target_vt->tile_size(),"+init=epsg:3857");
if (max_extent)
{
map.set_maximum_extent(*max_extent);
}
else
{
map.set_maximum_extent(target_vt->get_tile()->get_buffered_extent());
}
std::vector<mapnik::vector_tile_impl::merc_tile_ptr> merc_vtiles;
for (VectorTile* vt : vtiles)
{
merc_vtiles.push_back(vt->get_tile());
}
mapnik::vector_tile_impl::processor ren(map);
ren.set_fill_type(fill_type);
ren.set_simplify_distance(simplify_distance);
ren.set_process_all_rings(process_all_rings);
ren.set_multi_polygon_union(multi_polygon_union);
ren.set_strictly_simple(strictly_simple);
ren.set_area_threshold(area_threshold);
ren.set_scale_factor(scale_factor);
ren.set_scaling_method(scaling_method);
ren.set_image_format(image_format);
ren.set_threading_mode(threading_mode);
mapnik::vector_tile_impl::composite(*target_vt->get_tile(),
merc_vtiles,
map,
ren,
scale_denominator,
offset_x,
offset_y,
reencode);
}
/**
* Synchronous version of {@link #VectorTile.composite}
*
* @name compositeSync
* @memberof VectorTile
* @instance
* @instance
* @param {Array<mapnik.VectorTile>} array - an array of vector tile objects
* @param {object} [options]
* @example
* var vt1 = new mapnik.VectorTile(0,0,0);
* var vt2 = new mapnik.VectorTile(0,0,0);
* var options = { ... };
* vt1.compositeSync([vt2], options);
*
*/
NAN_METHOD(VectorTile::compositeSync)
{
info.GetReturnValue().Set(_compositeSync(info));
}
v8::Local<v8::Value> VectorTile::_compositeSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
if (info.Length() < 1 || !info[0]->IsArray())
{
Nan::ThrowTypeError("must provide an array of VectorTile objects and an optional options object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Array> vtiles = info[0].As<v8::Array>();
unsigned num_tiles = vtiles->Length();
if (num_tiles < 1)
{
Nan::ThrowTypeError("must provide an array with at least one VectorTile object and an optional options object");
return scope.Escape(Nan::Undefined());
}
// options needed for re-rendering tiles
// unclear yet to what extent these need to be user
// driven, but we expose here to avoid hardcoding
double scale_factor = 1.0;
unsigned offset_x = 0;
unsigned offset_y = 0;
double area_threshold = 0.1;
bool strictly_simple = true;
bool multi_polygon_union = false;
mapnik::vector_tile_impl::polygon_fill_type fill_type = mapnik::vector_tile_impl::positive_fill;
double scale_denominator = 0.0;
bool reencode = false;
boost::optional<mapnik::box2d<double>> max_extent;
double simplify_distance = 0.0;
bool process_all_rings = false;
std::string image_format = "webp";
mapnik::scaling_method_e scaling_method = mapnik::SCALING_BILINEAR;
std::launch threading_mode = std::launch::deferred;
if (info.Length() > 1)
{
// options object
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("optional second argument must be an options object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> options = info[1]->ToObject();
if (options->Has(Nan::New("area_threshold").ToLocalChecked()))
{
v8::Local<v8::Value> area_thres = options->Get(Nan::New("area_threshold").ToLocalChecked());
if (!area_thres->IsNumber())
{
Nan::ThrowTypeError("option 'area_threshold' must be an floating point number");
return scope.Escape(Nan::Undefined());
}
area_threshold = area_thres->NumberValue();
if (area_threshold < 0.0)
{
Nan::ThrowTypeError("option 'area_threshold' can not be negative");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("simplify_distance").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("simplify_distance").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'simplify_distance' must be an floating point number");
return scope.Escape(Nan::Undefined());
}
simplify_distance = param_val->NumberValue();
if (simplify_distance < 0.0)
{
Nan::ThrowTypeError("option 'simplify_distance' can not be negative");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("strictly_simple").ToLocalChecked()))
{
v8::Local<v8::Value> strict_simp = options->Get(Nan::New("strictly_simple").ToLocalChecked());
if (!strict_simp->IsBoolean())
{
Nan::ThrowTypeError("option 'strictly_simple' must be a boolean");
return scope.Escape(Nan::Undefined());
}
strictly_simple = strict_simp->BooleanValue();
}
if (options->Has(Nan::New("multi_polygon_union").ToLocalChecked()))
{
v8::Local<v8::Value> mpu = options->Get(Nan::New("multi_polygon_union").ToLocalChecked());
if (!mpu->IsBoolean())
{
Nan::ThrowTypeError("option 'multi_polygon_union' must be a boolean");
return scope.Escape(Nan::Undefined());
}
multi_polygon_union = mpu->BooleanValue();
}
if (options->Has(Nan::New("fill_type").ToLocalChecked()))
{
v8::Local<v8::Value> ft = options->Get(Nan::New("fill_type").ToLocalChecked());
if (!ft->IsNumber())
{
Nan::ThrowTypeError("optional arg 'fill_type' must be a number");
return scope.Escape(Nan::Undefined());
}
fill_type = static_cast<mapnik::vector_tile_impl::polygon_fill_type>(ft->IntegerValue());
if (fill_type >= mapnik::vector_tile_impl::polygon_fill_type_max)
{
Nan::ThrowTypeError("optional arg 'fill_type' out of possible range");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("threading_mode").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("threading_mode").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'threading_mode' must be an unsigned integer");
return scope.Escape(Nan::Undefined());
}
threading_mode = static_cast<std::launch>(param_val->IntegerValue());
if (threading_mode != std::launch::async &&
threading_mode != std::launch::deferred &&
threading_mode != (std::launch::async | std::launch::deferred))
{
Nan::ThrowTypeError("optional arg 'threading_mode' is invalid");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("scale").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale' must be a number");
return scope.Escape(Nan::Undefined());
}
scale_factor = bind_opt->NumberValue();
if (scale_factor <= 0.0)
{
Nan::ThrowTypeError("optional arg 'scale' must be greater then zero");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("scale_denominator").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale_denominator").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale_denominator' must be a number");
return scope.Escape(Nan::Undefined());
}
scale_denominator = bind_opt->NumberValue();
if (scale_denominator < 0.0)
{
Nan::ThrowTypeError("optional arg 'scale_denominator' must be non negative number");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New("offset_x").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("offset_x").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'offset_x' must be a number");
return scope.Escape(Nan::Undefined());
}
offset_x = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("offset_y").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("offset_y").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'offset_y' must be a number");
return scope.Escape(Nan::Undefined());
}
offset_y = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("reencode").ToLocalChecked()))
{
v8::Local<v8::Value> reencode_opt = options->Get(Nan::New("reencode").ToLocalChecked());
if (!reencode_opt->IsBoolean())
{
Nan::ThrowTypeError("reencode value must be a boolean");
return scope.Escape(Nan::Undefined());
}
reencode = reencode_opt->BooleanValue();
}
if (options->Has(Nan::New("max_extent").ToLocalChecked()))
{
v8::Local<v8::Value> max_extent_opt = options->Get(Nan::New("max_extent").ToLocalChecked());
if (!max_extent_opt->IsArray())
{
Nan::ThrowTypeError("max_extent value must be an array of [minx,miny,maxx,maxy]");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Array> bbox = max_extent_opt.As<v8::Array>();
auto len = bbox->Length();
if (!(len == 4))
{
Nan::ThrowTypeError("max_extent value must be an array of [minx,miny,maxx,maxy]");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Value> minx = bbox->Get(0);
v8::Local<v8::Value> miny = bbox->Get(1);
v8::Local<v8::Value> maxx = bbox->Get(2);
v8::Local<v8::Value> maxy = bbox->Get(3);
if (!minx->IsNumber() || !miny->IsNumber() || !maxx->IsNumber() || !maxy->IsNumber())
{
Nan::ThrowError("max_extent [minx,miny,maxx,maxy] must be numbers");
return scope.Escape(Nan::Undefined());
}
max_extent = mapnik::box2d<double>(minx->NumberValue(),miny->NumberValue(),
maxx->NumberValue(),maxy->NumberValue());
}
if (options->Has(Nan::New("process_all_rings").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("process_all_rings").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'process_all_rings' must be a boolean");
return scope.Escape(Nan::Undefined());
}
process_all_rings = param_val->BooleanValue();
}
if (options->Has(Nan::New("image_scaling").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_scaling").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_scaling' must be a string");
return scope.Escape(Nan::Undefined());
}
std::string image_scaling = TOSTR(param_val);
boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(image_scaling);
if (!method)
{
Nan::ThrowTypeError("option 'image_scaling' must be a string and a valid scaling method (e.g 'bilinear')");
return scope.Escape(Nan::Undefined());
}
scaling_method = *method;
}
if (options->Has(Nan::New("image_format").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_format").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_format' must be a string");
return scope.Escape(Nan::Undefined());
}
image_format = TOSTR(param_val);
}
}
VectorTile* target_vt = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
std::vector<VectorTile*> vtiles_vec;
vtiles_vec.reserve(num_tiles);
for (unsigned j=0;j < num_tiles;++j)
{
v8::Local<v8::Value> val = vtiles->Get(j);
if (!val->IsObject())
{
Nan::ThrowTypeError("must provide an array of VectorTile objects");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> tile_obj = val->ToObject();
if (tile_obj->IsNull() || tile_obj->IsUndefined() || !Nan::New(VectorTile::constructor)->HasInstance(tile_obj))
{
Nan::ThrowTypeError("must provide an array of VectorTile objects");
return scope.Escape(Nan::Undefined());
}
vtiles_vec.push_back(Nan::ObjectWrap::Unwrap<VectorTile>(tile_obj));
}
try
{
_composite(target_vt,
vtiles_vec,
scale_factor,
offset_x,
offset_y,
area_threshold,
strictly_simple,
multi_polygon_union,
fill_type,
scale_denominator,
reencode,
max_extent,
simplify_distance,
process_all_rings,
image_format,
scaling_method,
threading_mode);
}
catch (std::exception const& ex)
{
Nan::ThrowTypeError(ex.what());
return scope.Escape(Nan::Undefined());
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
double scale_factor;
unsigned offset_x;
unsigned offset_y;
double area_threshold;
double scale_denominator;
std::vector<VectorTile*> vtiles;
bool error;
bool strictly_simple;
bool multi_polygon_union;
mapnik::vector_tile_impl::polygon_fill_type fill_type;
bool reencode;
boost::optional<mapnik::box2d<double>> max_extent;
double simplify_distance;
bool process_all_rings;
std::string image_format;
mapnik::scaling_method_e scaling_method;
std::launch threading_mode;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} vector_tile_composite_baton_t;
/**
* Composite an array of vector tiles into one vector tile
*
* @name composite
* @memberof VectorTile
* @instance
* @param {Array<mapnik.VectorTile>} array - an array of vector tile objects
* @param {object} [options]
* @param {float} [options.scale_factor=1.0]
* @param {number} [options.offset_x=0]
* @param {number} [options.offset_y=0]
* @param {float} [options.area_threshold=0.1] - used to discard small polygons.
* If a value is greater than `0` it will trigger polygons with an area smaller
* than the value to be discarded. Measured in grid integers, not spherical mercator
* coordinates.
* @param {boolean} [options.strictly_simple=true] - ensure all geometry is valid according to
* OGC Simple definition
* @param {boolean} [options.multi_polygon_union=false] - union all multipolygons
* @param {Object<mapnik.polygonFillType>} [options.fill_type=mapnik.polygonFillType.positive]
* the fill type used in determining what are holes and what are outer rings. See the
* [Clipper documentation](http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm)
* to learn more about fill types.
* @param {float} [options.scale_denominator=0.0]
* @param {boolean} [options.reencode=false]
* @param {Array<number>} [options.max_extent=minx,miny,maxx,maxy]
* @param {float} [options.simplify_distance=0.0] - Simplification works to generalize
* geometries before encoding into vector tiles.simplification distance The
* `simplify_distance` value works in integer space over a 4096 pixel grid and uses
* the [Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm).
* @param {boolean} [options.process_all_rings=false] - if `true`, don't assume winding order and ring order of
* polygons are correct according to the [`2.0` Mapbox Vector Tile specification](https://github.com/mapbox/vector-tile-spec)
* @param {string} [options.image_format=webp] or `jpeg`, `png`, `tiff`
* @param {string} [options.scaling_method=bilinear] - can be any
* of the <mapnik.imageScaling> methods
* @param {string} [options.threading_mode=deferred]
* @param {Function} callback - `function(err)`
* @example
* var vt1 = new mapnik.VectorTile(0,0,0);
* var vt2 = new mapnik.VectorTile(0,0,0);
* var options = {
* scale: 1.0,
* offset_x: 0,
* offset_y: 0,
* area_threshold: 0.1,
* strictly_simple: false,
* multi_polygon_union: true,
* fill_type: mapnik.polygonFillType.nonZero,
* process_all_rings:false,
* scale_denominator: 0.0,
* reencode: true
* }
* // add vt2 to vt1 tile
* vt1.composite([vt2], options, function(err) {
* if (err) throw err;
* // your custom code with `vt1`
* });
*
*/
NAN_METHOD(VectorTile::composite)
{
if ((info.Length() < 2) || !info[info.Length()-1]->IsFunction())
{
info.GetReturnValue().Set(_compositeSync(info));
return;
}
if (!info[0]->IsArray())
{
Nan::ThrowTypeError("must provide an array of VectorTile objects and an optional options object");
return;
}
v8::Local<v8::Array> vtiles = info[0].As<v8::Array>();
unsigned num_tiles = vtiles->Length();
if (num_tiles < 1)
{
Nan::ThrowTypeError("must provide an array with at least one VectorTile object and an optional options object");
return;
}
// options needed for re-rendering tiles
// unclear yet to what extent these need to be user
// driven, but we expose here to avoid hardcoding
double scale_factor = 1.0;
unsigned offset_x = 0;
unsigned offset_y = 0;
double area_threshold = 0.1;
bool strictly_simple = true;
bool multi_polygon_union = false;
mapnik::vector_tile_impl::polygon_fill_type fill_type = mapnik::vector_tile_impl::positive_fill;
double scale_denominator = 0.0;
bool reencode = false;
boost::optional<mapnik::box2d<double>> max_extent;
double simplify_distance = 0.0;
bool process_all_rings = false;
std::string image_format = "webp";
mapnik::scaling_method_e scaling_method = mapnik::SCALING_BILINEAR;
std::launch threading_mode = std::launch::deferred;
std::string merc_srs("+init=epsg:3857");
if (info.Length() > 2)
{
// options object
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("optional second argument must be an options object");
return;
}
v8::Local<v8::Object> options = info[1]->ToObject();
if (options->Has(Nan::New("area_threshold").ToLocalChecked()))
{
v8::Local<v8::Value> area_thres = options->Get(Nan::New("area_threshold").ToLocalChecked());
if (!area_thres->IsNumber())
{
Nan::ThrowTypeError("option 'area_threshold' must be a number");
return;
}
area_threshold = area_thres->NumberValue();
if (area_threshold < 0.0)
{
Nan::ThrowTypeError("option 'area_threshold' can not be negative");
return;
}
}
if (options->Has(Nan::New("strictly_simple").ToLocalChecked()))
{
v8::Local<v8::Value> strict_simp = options->Get(Nan::New("strictly_simple").ToLocalChecked());
if (!strict_simp->IsBoolean())
{
Nan::ThrowTypeError("strictly_simple value must be a boolean");
return;
}
strictly_simple = strict_simp->BooleanValue();
}
if (options->Has(Nan::New("multi_polygon_union").ToLocalChecked()))
{
v8::Local<v8::Value> mpu = options->Get(Nan::New("multi_polygon_union").ToLocalChecked());
if (!mpu->IsBoolean())
{
Nan::ThrowTypeError("multi_polygon_union value must be a boolean");
return;
}
multi_polygon_union = mpu->BooleanValue();
}
if (options->Has(Nan::New("fill_type").ToLocalChecked()))
{
v8::Local<v8::Value> ft = options->Get(Nan::New("fill_type").ToLocalChecked());
if (!ft->IsNumber())
{
Nan::ThrowTypeError("optional arg 'fill_type' must be a number");
return;
}
fill_type = static_cast<mapnik::vector_tile_impl::polygon_fill_type>(ft->IntegerValue());
if (fill_type >= mapnik::vector_tile_impl::polygon_fill_type_max)
{
Nan::ThrowTypeError("optional arg 'fill_type' out of possible range");
return;
}
}
if (options->Has(Nan::New("threading_mode").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("threading_mode").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'threading_mode' must be an unsigned integer");
return;
}
threading_mode = static_cast<std::launch>(param_val->IntegerValue());
if (threading_mode != std::launch::async &&
threading_mode != std::launch::deferred &&
threading_mode != (std::launch::async | std::launch::deferred))
{
Nan::ThrowTypeError("optional arg 'threading_mode' is not a valid value");
return;
}
}
if (options->Has(Nan::New("simplify_distance").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("simplify_distance").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'simplify_distance' must be an floating point number");
return;
}
simplify_distance = param_val->NumberValue();
if (simplify_distance < 0.0)
{
Nan::ThrowTypeError("option 'simplify_distance' can not be negative");
return;
}
}
if (options->Has(Nan::New("scale").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale' must be a number");
return;
}
scale_factor = bind_opt->NumberValue();
if (scale_factor < 0.0)
{
Nan::ThrowTypeError("option 'scale' can not be negative");
return;
}
}
if (options->Has(Nan::New("scale_denominator").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale_denominator").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale_denominator' must be a number");
return;
}
scale_denominator = bind_opt->NumberValue();
if (scale_denominator < 0.0)
{
Nan::ThrowTypeError("option 'scale_denominator' can not be negative");
return;
}
}
if (options->Has(Nan::New("offset_x").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("offset_x").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'offset_x' must be a number");
return;
}
offset_x = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("offset_y").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("offset_y").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'offset_y' must be a number");
return;
}
offset_y = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("reencode").ToLocalChecked()))
{
v8::Local<v8::Value> reencode_opt = options->Get(Nan::New("reencode").ToLocalChecked());
if (!reencode_opt->IsBoolean())
{
Nan::ThrowTypeError("reencode value must be a boolean");
return;
}
reencode = reencode_opt->BooleanValue();
}
if (options->Has(Nan::New("max_extent").ToLocalChecked()))
{
v8::Local<v8::Value> max_extent_opt = options->Get(Nan::New("max_extent").ToLocalChecked());
if (!max_extent_opt->IsArray())
{
Nan::ThrowTypeError("max_extent value must be an array of [minx,miny,maxx,maxy]");
return;
}
v8::Local<v8::Array> bbox = max_extent_opt.As<v8::Array>();
auto len = bbox->Length();
if (!(len == 4))
{
Nan::ThrowTypeError("max_extent value must be an array of [minx,miny,maxx,maxy]");
return;
}
v8::Local<v8::Value> minx = bbox->Get(0);
v8::Local<v8::Value> miny = bbox->Get(1);
v8::Local<v8::Value> maxx = bbox->Get(2);
v8::Local<v8::Value> maxy = bbox->Get(3);
if (!minx->IsNumber() || !miny->IsNumber() || !maxx->IsNumber() || !maxy->IsNumber())
{
Nan::ThrowError("max_extent [minx,miny,maxx,maxy] must be numbers");
return;
}
max_extent = mapnik::box2d<double>(minx->NumberValue(),miny->NumberValue(),
maxx->NumberValue(),maxy->NumberValue());
}
if (options->Has(Nan::New("process_all_rings").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("process_all_rings").ToLocalChecked());
if (!param_val->IsBoolean()) {
Nan::ThrowTypeError("option 'process_all_rings' must be a boolean");
return;
}
process_all_rings = param_val->BooleanValue();
}
if (options->Has(Nan::New("image_scaling").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_scaling").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_scaling' must be a string");
return;
}
std::string image_scaling = TOSTR(param_val);
boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(image_scaling);
if (!method)
{
Nan::ThrowTypeError("option 'image_scaling' must be a string and a valid scaling method (e.g 'bilinear')");
return;
}
scaling_method = *method;
}
if (options->Has(Nan::New("image_format").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_format").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_format' must be a string");
return;
}
image_format = TOSTR(param_val);
}
}
v8::Local<v8::Value> callback = info[info.Length()-1];
vector_tile_composite_baton_t *closure = new vector_tile_composite_baton_t();
closure->request.data = closure;
closure->offset_x = offset_x;
closure->offset_y = offset_y;
closure->strictly_simple = strictly_simple;
closure->fill_type = fill_type;
closure->multi_polygon_union = multi_polygon_union;
closure->area_threshold = area_threshold;
closure->scale_factor = scale_factor;
closure->scale_denominator = scale_denominator;
closure->reencode = reencode;
closure->max_extent = max_extent;
closure->simplify_distance = simplify_distance;
closure->process_all_rings = process_all_rings;
closure->scaling_method = scaling_method;
closure->image_format = image_format;
closure->threading_mode = threading_mode;
closure->d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
closure->error = false;
closure->vtiles.reserve(num_tiles);
for (unsigned j=0;j < num_tiles;++j)
{
v8::Local<v8::Value> val = vtiles->Get(j);
if (!val->IsObject())
{
delete closure;
Nan::ThrowTypeError("must provide an array of VectorTile objects");
return;
}
v8::Local<v8::Object> tile_obj = val->ToObject();
if (tile_obj->IsNull() || tile_obj->IsUndefined() || !Nan::New(VectorTile::constructor)->HasInstance(tile_obj))
{
delete closure;
Nan::ThrowTypeError("must provide an array of VectorTile objects");
return;
}
VectorTile* vt = Nan::ObjectWrap::Unwrap<VectorTile>(tile_obj);
vt->Ref();
closure->vtiles.push_back(vt);
}
closure->d->Ref();
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_Composite, (uv_after_work_cb)EIO_AfterComposite);
return;
}
void VectorTile::EIO_Composite(uv_work_t* req)
{
vector_tile_composite_baton_t *closure = static_cast<vector_tile_composite_baton_t *>(req->data);
try
{
_composite(closure->d,
closure->vtiles,
closure->scale_factor,
closure->offset_x,
closure->offset_y,
closure->area_threshold,
closure->strictly_simple,
closure->multi_polygon_union,
closure->fill_type,
closure->scale_denominator,
closure->reencode,
closure->max_extent,
closure->simplify_distance,
closure->process_all_rings,
closure->image_format,
closure->scaling_method,
closure->threading_mode);
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterComposite(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_composite_baton_t *closure = static_cast<vector_tile_composite_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->d->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
for (VectorTile* vt : closure->vtiles)
{
vt->Unref();
}
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Get the extent of this vector tile
*
* @memberof VectorTile
* @instance
* @name extent
* @returns {Array<number>} array of extent in the form of `[minx,miny,maxx,maxy]`
* @example
* var vt = new mapnik.VectorTile(9,112,195);
* var extent = vt.extent();
* console.log(extent); // [-11271098.44281895, 4696291.017841229, -11192826.925854929, 4774562.534805248]
*/
NAN_METHOD(VectorTile::extent)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
v8::Local<v8::Array> arr = Nan::New<v8::Array>(4);
mapnik::box2d<double> const& e = d->tile_->extent();
arr->Set(0, Nan::New<v8::Number>(e.minx()));
arr->Set(1, Nan::New<v8::Number>(e.miny()));
arr->Set(2, Nan::New<v8::Number>(e.maxx()));
arr->Set(3, Nan::New<v8::Number>(e.maxy()));
info.GetReturnValue().Set(arr);
return;
}
/**
* Get the extent including the buffer of this vector tile
*
* @memberof VectorTile
* @instance
* @name bufferedExtent
* @returns {Array<number>} extent - `[minx, miny, maxx, maxy]`
* @example
* var vt = new mapnik.VectorTile(9,112,195);
* var extent = vt.bufferedExtent();
* console.log(extent); // [-11273544.4277, 4693845.0329, -11190380.9409, 4777008.5197];
*/
NAN_METHOD(VectorTile::bufferedExtent)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
v8::Local<v8::Array> arr = Nan::New<v8::Array>(4);
mapnik::box2d<double> e = d->tile_->get_buffered_extent();
arr->Set(0, Nan::New<v8::Number>(e.minx()));
arr->Set(1, Nan::New<v8::Number>(e.miny()));
arr->Set(2, Nan::New<v8::Number>(e.maxx()));
arr->Set(3, Nan::New<v8::Number>(e.maxy()));
info.GetReturnValue().Set(arr);
return;
}
/**
* Get the names of all of the layers in this vector tile
*
* @memberof VectorTile
* @instance
* @name names
* @returns {Array<string>} layer names
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var data = fs.readFileSync('./path/to/data.mvt');
* vt.addDataSync(data);
* console.log(vt.names()); // ['layer-name', 'another-layer']
*/
NAN_METHOD(VectorTile::names)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
std::vector<std::string> const& names = d->tile_->get_layers();
v8::Local<v8::Array> arr = Nan::New<v8::Array>(names.size());
unsigned idx = 0;
for (std::string const& name : names)
{
arr->Set(idx++,Nan::New<v8::String>(name).ToLocalChecked());
}
info.GetReturnValue().Set(arr);
return;
}
/**
* Extract the layer by a given name to a new vector tile
*
* @memberof VectorTile
* @instance
* @name layer
* @param {string} layer_name - name of layer
* @returns {mapnik.VectorTile} mapnik VectorTile object
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var data = fs.readFileSync('./path/to/data.mvt');
* vt.addDataSync(data);
* console.log(vt.names()); // ['layer-name', 'another-layer']
* var vt2 = vt.layer('layer-name');
* console.log(vt2.names()); // ['layer-name']
*/
NAN_METHOD(VectorTile::layer)
{
if (info.Length() < 1)
{
Nan::ThrowError("first argument must be either a layer name");
return;
}
v8::Local<v8::Value> layer_id = info[0];
std::string layer_name;
if (!layer_id->IsString())
{
Nan::ThrowTypeError("'layer' argument must be a layer name (string)");
return;
}
layer_name = TOSTR(layer_id);
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!d->get_tile()->has_layer(layer_name))
{
Nan::ThrowTypeError("layer does not exist in vector tile");
return;
}
protozero::pbf_reader layer_msg;
VectorTile* v = new VectorTile(d->get_tile()->z(), d->get_tile()->x(), d->get_tile()->y(), d->tile_size(), d->buffer_size());
protozero::pbf_reader tile_message(d->get_tile()->get_reader());
while (tile_message.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
auto data_view = tile_message.get_view();
protozero::pbf_reader layer_message(data_view);
if (!layer_message.next(mapnik::vector_tile_impl::Layer_Encoding::NAME))
{
continue;
}
std::string name = layer_message.get_string();
if (layer_name == name)
{
v->get_tile()->append_layer_buffer(data_view.data(), data_view.size(), layer_name);
break;
}
}
v8::Local<v8::Value> ext = Nan::New<v8::External>(v);
Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::New(constructor)->GetFunction(), 1, &ext);
if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Layer instance");
else info.GetReturnValue().Set(maybe_local.ToLocalChecked());
return;
}
/**
* Get the names of all of the empty layers in this vector tile
*
* @memberof VectorTile
* @instance
* @name emptyLayers
* @returns {Array<string>} layer names
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var empty = vt.emptyLayers();
* // assumes you have added data to your tile
* console.log(empty); // ['layer-name', 'empty-layer']
*/
NAN_METHOD(VectorTile::emptyLayers)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
std::set<std::string> const& names = d->tile_->get_empty_layers();
v8::Local<v8::Array> arr = Nan::New<v8::Array>(names.size());
unsigned idx = 0;
for (std::string const& name : names)
{
arr->Set(idx++,Nan::New<v8::String>(name).ToLocalChecked());
}
info.GetReturnValue().Set(arr);
return;
}
/**
* Get the names of all of the painted layers in this vector tile. "Painted" is
* a check to see if data exists in the source dataset in a tile.
*
* @memberof VectorTile
* @instance
* @name paintedLayers
* @returns {Array<string>} layer names
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var painted = vt.paintedLayers();
* // assumes you have added data to your tile
* console.log(painted); // ['layer-name']
*/
NAN_METHOD(VectorTile::paintedLayers)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
std::set<std::string> const& names = d->tile_->get_painted_layers();
v8::Local<v8::Array> arr = Nan::New<v8::Array>(names.size());
unsigned idx = 0;
for (std::string const& name : names)
{
arr->Set(idx++,Nan::New<v8::String>(name).ToLocalChecked());
}
info.GetReturnValue().Set(arr);
return;
}
/**
* Return whether this vector tile is empty - whether it has no
* layers and no features
*
* @memberof VectorTile
* @instance
* @name empty
* @returns {boolean} whether the layer is empty
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var empty = vt.empty();
* console.log(empty); // true
*/
NAN_METHOD(VectorTile::empty)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Boolean>(d->tile_->is_empty()));
}
/**
* Get whether the vector tile has been painted. "Painted" is
* a check to see if data exists in the source dataset in a tile.
*
* @memberof VectorTile
* @instance
* @name painted
* @returns {boolean} painted
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var painted = vt.painted();
* console.log(painted); // false
*/
NAN_METHOD(VectorTile::painted)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New(d->tile_->is_painted()));
}
typedef struct
{
uv_work_t request;
VectorTile* d;
double lon;
double lat;
double tolerance;
bool error;
std::vector<query_result> result;
std::string layer_name;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} vector_tile_query_baton_t;
/**
* Query a vector tile by longitude and latitude and get an array of
* features in the vector tile that exist in relation to those coordinates.
*
* A note on `tolerance`: If you provide a positive value for tolerance you
* are saying that you'd like features returned in the query results that might
* not exactly intersect with a given lon/lat. The higher the tolerance the
* slower the query will run because it will do more work by comparing your query
* lon/lat against more potential features. However, this is an important parameter
* because vector tile storage, by design, results in reduced precision of coordinates.
* The amount of precision loss depends on the zoom level of a given vector tile
* and how aggressively it was simplified during encoding. So if you want at
* least one match - say the closest single feature to your query lon/lat - is is
* not possible to know the smallest tolerance that will work without experimentation.
* In general be prepared to provide a high tolerance (1-100) for low zoom levels
* while you should be okay with a low tolerance (1-10) at higher zoom levels and
* with vector tiles that are storing less simplified geometries. The units tolerance
* should be expressed in depend on the coordinate system of the underlying data.
* In the case of vector tiles this is spherical mercator so the units are meters.
* For points any features will be returned that contain a point which is, by distance
* in meters, not greater than the tolerance value. For lines any features will be
* returned that have a segment which is, by distance in meters, not greater than
* the tolerance value. For polygons tolerance is not supported which means that
* your lon/lat must fall inside a feature's polygon otherwise that feature will
* not be matched.
*
* @memberof VectorTile
* @instance
* @name query
* @param {number} longitude - longitude
* @param {number} latitude - latitude
* @param {Object} [options]
* @param {number} [options.tolerance=0] include features a specific distance from the
* lon/lat query in the response
* @param {string} [options.layer] layer - Pass a layer name to restrict
* the query results to a single layer in the vector tile. Get all possible
* layer names in the vector tile with {@link VectorTile#names}
* @param {Function} callback(err, features)
* @returns {Array<mapnik.Feature>} an array of {@link mapnik.Feature} objects
* @example
* vt.query(139.61, 37.17, {tolerance: 0}, function(err, features) {
* if (err) throw err;
* console.log(features); // array of objects
* console.log(features.length) // 1
* console.log(features[0].id()) // 89
* console.log(features[0].geometry().type()); // 'Polygon'
* console.log(features[0].distance); // 0
* console.log(features[0].layer); // 'layer name'
* });
*/
NAN_METHOD(VectorTile::query)
{
if (info.Length() < 2 || !info[0]->IsNumber() || !info[1]->IsNumber())
{
Nan::ThrowError("expects lon,lat info");
return;
}
double tolerance = 0.0; // meters
std::string layer_name("");
if (info.Length() > 2)
{
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (!info[2]->IsObject())
{
Nan::ThrowTypeError("optional third argument must be an options object");
return;
}
options = info[2]->ToObject();
if (options->Has(Nan::New("tolerance").ToLocalChecked()))
{
v8::Local<v8::Value> tol = options->Get(Nan::New("tolerance").ToLocalChecked());
if (!tol->IsNumber())
{
Nan::ThrowTypeError("tolerance value must be a number");
return;
}
tolerance = tol->NumberValue();
}
if (options->Has(Nan::New("layer").ToLocalChecked()))
{
v8::Local<v8::Value> layer_id = options->Get(Nan::New("layer").ToLocalChecked());
if (!layer_id->IsString())
{
Nan::ThrowTypeError("layer value must be a string");
return;
}
layer_name = TOSTR(layer_id);
}
}
double lon = info[0]->NumberValue();
double lat = info[1]->NumberValue();
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
// If last argument is not a function go with sync call.
if (!info[info.Length()-1]->IsFunction())
{
try
{
std::vector<query_result> result = _query(d, lon, lat, tolerance, layer_name);
v8::Local<v8::Array> arr = _queryResultToV8(result);
info.GetReturnValue().Set(arr);
return;
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return;
}
}
else
{
v8::Local<v8::Value> callback = info[info.Length()-1];
vector_tile_query_baton_t *closure = new vector_tile_query_baton_t();
closure->request.data = closure;
closure->lon = lon;
closure->lat = lat;
closure->tolerance = tolerance;
closure->layer_name = layer_name;
closure->d = d;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_Query, (uv_after_work_cb)EIO_AfterQuery);
d->Ref();
return;
}
}
void VectorTile::EIO_Query(uv_work_t* req)
{
vector_tile_query_baton_t *closure = static_cast<vector_tile_query_baton_t *>(req->data);
try
{
closure->result = _query(closure->d, closure->lon, closure->lat, closure->tolerance, closure->layer_name);
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterQuery(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_query_baton_t *closure = static_cast<vector_tile_query_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
std::vector<query_result> const& result = closure->result;
v8::Local<v8::Array> arr = _queryResultToV8(result);
v8::Local<v8::Value> argv[2] = { Nan::Null(), arr };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
std::vector<query_result> VectorTile::_query(VectorTile* d, double lon, double lat, double tolerance, std::string const& layer_name)
{
std::vector<query_result> arr;
if (d->tile_->is_empty())
{
return arr;
}
mapnik::projection wgs84("+init=epsg:4326",true);
mapnik::projection merc("+init=epsg:3857",true);
mapnik::proj_transform tr(wgs84,merc);
double x = lon;
double y = lat;
double z = 0;
if (!tr.forward(x,y,z))
{
// THIS CAN NEVER BE REACHED CURRENTLY
// internally lonlat2merc in mapnik can never return false.
/* LCOV_EXCL_START */
throw std::runtime_error("could not reproject lon/lat to mercator");
/* LCOV_EXCL_STOP */
}
mapnik::coord2d pt(x,y);
if (!layer_name.empty())
{
protozero::pbf_reader layer_msg;
if (d->tile_->layer_reader(layer_name, layer_msg))
{
auto ds = std::make_shared<mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
d->tile_->x(),
d->tile_->y(),
d->tile_->z());
mapnik::featureset_ptr fs = ds->features_at_point(pt, tolerance);
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
while ((feature = fs->next()))
{
auto const& geom = feature->get_geometry();
auto p2p = path_to_point_distance(geom,x,y);
if (!tr.backward(p2p.x_hit,p2p.y_hit,z))
{
/* LCOV_EXCL_START */
throw std::runtime_error("could not reproject lon/lat to mercator");
/* LCOV_EXCL_STOP */
}
if (p2p.distance >= 0 && p2p.distance <= tolerance)
{
query_result res;
res.x_hit = p2p.x_hit;
res.y_hit = p2p.y_hit;
res.distance = p2p.distance;
res.layer = layer_name;
res.feature = feature;
arr.push_back(std::move(res));
}
}
}
}
}
else
{
protozero::pbf_reader item(d->tile_->get_reader());
while (item.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
protozero::pbf_reader layer_msg = item.get_message();
auto ds = std::make_shared<mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
d->tile_->x(),
d->tile_->y(),
d->tile_->z());
mapnik::featureset_ptr fs = ds->features_at_point(pt,tolerance);
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
while ((feature = fs->next()))
{
auto const& geom = feature->get_geometry();
auto p2p = path_to_point_distance(geom,x,y);
if (!tr.backward(p2p.x_hit,p2p.y_hit,z))
{
/* LCOV_EXCL_START */
throw std::runtime_error("could not reproject lon/lat to mercator");
/* LCOV_EXCL_STOP */
}
if (p2p.distance >= 0 && p2p.distance <= tolerance)
{
query_result res;
res.x_hit = p2p.x_hit;
res.y_hit = p2p.y_hit;
res.distance = p2p.distance;
res.layer = ds->get_name();
res.feature = feature;
arr.push_back(std::move(res));
}
}
}
}
}
std::sort(arr.begin(), arr.end(), _querySort);
return arr;
}
bool VectorTile::_querySort(query_result const& a, query_result const& b)
{
return a.distance < b.distance;
}
v8::Local<v8::Array> VectorTile::_queryResultToV8(std::vector<query_result> const& result)
{
v8::Local<v8::Array> arr = Nan::New<v8::Array>(result.size());
std::size_t i = 0;
for (auto const& item : result)
{
v8::Local<v8::Value> feat = Feature::NewInstance(item.feature);
v8::Local<v8::Object> feat_obj = feat->ToObject();
feat_obj->Set(Nan::New("layer").ToLocalChecked(),Nan::New<v8::String>(item.layer).ToLocalChecked());
feat_obj->Set(Nan::New("distance").ToLocalChecked(),Nan::New<v8::Number>(item.distance));
feat_obj->Set(Nan::New("x_hit").ToLocalChecked(),Nan::New<v8::Number>(item.x_hit));
feat_obj->Set(Nan::New("y_hit").ToLocalChecked(),Nan::New<v8::Number>(item.y_hit));
arr->Set(i++,feat);
}
return arr;
}
typedef struct
{
uv_work_t request;
VectorTile* d;
std::vector<query_lonlat> query;
double tolerance;
std::string layer_name;
std::vector<std::string> fields;
queryMany_result result;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} vector_tile_queryMany_baton_t;
/**
* Query a vector tile by multiple sets of latitude/longitude pairs.
* Just like <mapnik.VectorTile.query> but with more points to search.
*
* @memberof VectorTile
* @instance
* @name queryMany
* @param {array<number>} array - `longitude` and `latitude` array pairs [[lon1,lat1], [lon2,lat2]]
* @param {Object} options
* @param {number} [options.tolerance=0] include features a specific distance from the
* lon/lat query in the response. Read more about tolerance at {@link VectorTile#query}.
* @param {string} options.layer - layer name
* @param {Array<string>} [options.fields] - array of field names
* @param {Function} [callback] - `function(err, results)`
* @returns {Object} The response has contains two main objects: `hits` and `features`.
* The number of hits returned will correspond to the number of lon/lats queried and will
* be returned in the order of the query. Each hit returns 1) a `distance` and a 2) `feature_id`.
* The `distance` is number of meters the queried lon/lat is from the object in the vector tile.
* The `feature_id` is the corresponding object in features object.
*
* The values for the query is contained in the features object. Use attributes() to extract a value.
* @example
* vt.queryMany([[139.61, 37.17], [140.64, 38.1]], {tolerance: 0}, function(err, results) {
* if (err) throw err;
* console.log(results.hits); //
* console.log(results.features); // array of feature objects
* if (features.length) {
* console.log(results.features[0].layer); // 'layer-name'
* console.log(results.features[0].distance, features[0].x_hit, features[0].y_hit); // 0, 0, 0
* }
* });
*/
NAN_METHOD(VectorTile::queryMany)
{
if (info.Length() < 2 || !info[0]->IsArray())
{
Nan::ThrowError("expects lon,lat info + object with layer property referring to a layer name");
return;
}
double tolerance = 0.0; // meters
std::string layer_name("");
std::vector<std::string> fields;
std::vector<query_lonlat> query;
// Convert v8 queryArray to a std vector
v8::Local<v8::Array> queryArray = v8::Local<v8::Array>::Cast(info[0]);
query.reserve(queryArray->Length());
for (uint32_t p = 0; p < queryArray->Length(); ++p)
{
v8::Local<v8::Value> item = queryArray->Get(p);
if (!item->IsArray())
{
Nan::ThrowError("non-array item encountered");
return;
}
v8::Local<v8::Array> pair = v8::Local<v8::Array>::Cast(item);
v8::Local<v8::Value> lon = pair->Get(0);
v8::Local<v8::Value> lat = pair->Get(1);
if (!lon->IsNumber() || !lat->IsNumber())
{
Nan::ThrowError("lng lat must be numbers");
return;
}
query_lonlat lonlat;
lonlat.lon = lon->NumberValue();
lonlat.lat = lat->NumberValue();
query.push_back(std::move(lonlat));
}
// Convert v8 options object to std params
if (info.Length() > 1)
{
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("optional second argument must be an options object");
return;
}
options = info[1]->ToObject();
if (options->Has(Nan::New("tolerance").ToLocalChecked()))
{
v8::Local<v8::Value> tol = options->Get(Nan::New("tolerance").ToLocalChecked());
if (!tol->IsNumber())
{
Nan::ThrowTypeError("tolerance value must be a number");
return;
}
tolerance = tol->NumberValue();
}
if (options->Has(Nan::New("layer").ToLocalChecked()))
{
v8::Local<v8::Value> layer_id = options->Get(Nan::New("layer").ToLocalChecked());
if (!layer_id->IsString())
{
Nan::ThrowTypeError("layer value must be a string");
return;
}
layer_name = TOSTR(layer_id);
}
if (options->Has(Nan::New("fields").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("fields").ToLocalChecked());
if (!param_val->IsArray())
{
Nan::ThrowTypeError("option 'fields' must be an array of strings");
return;
}
v8::Local<v8::Array> a = v8::Local<v8::Array>::Cast(param_val);
unsigned int i = 0;
unsigned int num_fields = a->Length();
fields.reserve(num_fields);
while (i < num_fields)
{
v8::Local<v8::Value> name = a->Get(i);
if (name->IsString())
{
fields.emplace_back(TOSTR(name));
}
++i;
}
}
}
if (layer_name.empty())
{
Nan::ThrowTypeError("options.layer is required");
return;
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.This());
// If last argument is not a function go with sync call.
if (!info[info.Length()-1]->IsFunction())
{
try
{
queryMany_result result;
_queryMany(result, d, query, tolerance, layer_name, fields);
v8::Local<v8::Object> result_obj = _queryManyResultToV8(result);
info.GetReturnValue().Set(result_obj);
return;
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return;
}
}
else
{
v8::Local<v8::Value> callback = info[info.Length()-1];
vector_tile_queryMany_baton_t *closure = new vector_tile_queryMany_baton_t();
closure->d = d;
closure->query = query;
closure->tolerance = tolerance;
closure->layer_name = layer_name;
closure->fields = fields;
closure->error = false;
closure->request.data = closure;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_QueryMany, (uv_after_work_cb)EIO_AfterQueryMany);
d->Ref();
return;
}
}
void VectorTile::_queryMany(queryMany_result & result,
VectorTile* d,
std::vector<query_lonlat> const& query,
double tolerance,
std::string const& layer_name,
std::vector<std::string> const& fields)
{
protozero::pbf_reader layer_msg;
if (!d->tile_->layer_reader(layer_name,layer_msg))
{
throw std::runtime_error("Could not find layer in vector tile");
}
std::map<unsigned,query_result> features;
std::map<unsigned,std::vector<query_hit> > hits;
// Reproject query => mercator points
mapnik::box2d<double> bbox;
mapnik::projection wgs84("+init=epsg:4326",true);
mapnik::projection merc("+init=epsg:3857",true);
mapnik::proj_transform tr(wgs84,merc);
std::vector<mapnik::coord2d> points;
points.reserve(query.size());
for (std::size_t p = 0; p < query.size(); ++p)
{
double x = query[p].lon;
double y = query[p].lat;
double z = 0;
if (!tr.forward(x,y,z))
{
/* LCOV_EXCL_START */
throw std::runtime_error("could not reproject lon/lat to mercator");
/* LCOV_EXCL_STOP */
}
mapnik::coord2d pt(x,y);
bbox.expand_to_include(pt);
points.emplace_back(std::move(pt));
}
bbox.pad(tolerance);
std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf> ds = std::make_shared<
mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
d->tile_->x(),
d->tile_->y(),
d->tile_->z());
mapnik::query q(bbox);
if (fields.empty())
{
// request all data attributes
auto fields2 = ds->get_descriptor().get_descriptors();
for (auto const& field : fields2)
{
q.add_property_name(field.get_name());
}
}
else
{
for (std::string const& name : fields)
{
q.add_property_name(name);
}
}
mapnik::featureset_ptr fs = ds->features(q);
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
unsigned idx = 0;
while ((feature = fs->next()))
{
unsigned has_hit = 0;
for (std::size_t p = 0; p < points.size(); ++p)
{
mapnik::coord2d const& pt = points[p];
auto const& geom = feature->get_geometry();
auto p2p = path_to_point_distance(geom,pt.x,pt.y);
if (p2p.distance >= 0 && p2p.distance <= tolerance)
{
has_hit = 1;
query_result res;
res.feature = feature;
res.distance = 0;
res.layer = ds->get_name();
query_hit hit;
hit.distance = p2p.distance;
hit.feature_id = idx;
features.insert(std::make_pair(idx, res));
std::map<unsigned,std::vector<query_hit> >::iterator hits_it;
hits_it = hits.find(p);
if (hits_it == hits.end())
{
std::vector<query_hit> pointHits;
pointHits.reserve(1);
pointHits.push_back(std::move(hit));
hits.insert(std::make_pair(p, pointHits));
}
else
{
hits_it->second.push_back(std::move(hit));
}
}
}
if (has_hit > 0)
{
idx++;
}
}
}
// Sort each group of hits by distance.
for (auto & hit : hits)
{
std::sort(hit.second.begin(), hit.second.end(), _queryManySort);
}
result.hits = std::move(hits);
result.features = std::move(features);
return;
}
bool VectorTile::_queryManySort(query_hit const& a, query_hit const& b)
{
return a.distance < b.distance;
}
v8::Local<v8::Object> VectorTile::_queryManyResultToV8(queryMany_result const& result)
{
v8::Local<v8::Object> results = Nan::New<v8::Object>();
v8::Local<v8::Array> features = Nan::New<v8::Array>(result.features.size());
v8::Local<v8::Array> hits = Nan::New<v8::Array>(result.hits.size());
results->Set(Nan::New("hits").ToLocalChecked(), hits);
results->Set(Nan::New("features").ToLocalChecked(), features);
// result.features => features
for (auto const& item : result.features)
{
v8::Local<v8::Value> feat = Feature::NewInstance(item.second.feature);
v8::Local<v8::Object> feat_obj = feat->ToObject();
feat_obj->Set(Nan::New("layer").ToLocalChecked(),Nan::New<v8::String>(item.second.layer).ToLocalChecked());
features->Set(item.first, feat_obj);
}
// result.hits => hits
for (auto const& hit : result.hits)
{
v8::Local<v8::Array> point_hits = Nan::New<v8::Array>(hit.second.size());
std::size_t i = 0;
for (auto const& h : hit.second)
{
v8::Local<v8::Object> hit_obj = Nan::New<v8::Object>();
hit_obj->Set(Nan::New("distance").ToLocalChecked(), Nan::New<v8::Number>(h.distance));
hit_obj->Set(Nan::New("feature_id").ToLocalChecked(), Nan::New<v8::Number>(h.feature_id));
point_hits->Set(i++, hit_obj);
}
hits->Set(hit.first, point_hits);
}
return results;
}
void VectorTile::EIO_QueryMany(uv_work_t* req)
{
vector_tile_queryMany_baton_t *closure = static_cast<vector_tile_queryMany_baton_t *>(req->data);
try
{
_queryMany(closure->result, closure->d, closure->query, closure->tolerance, closure->layer_name, closure->fields);
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterQueryMany(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_queryMany_baton_t *closure = static_cast<vector_tile_queryMany_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
queryMany_result result = closure->result;
v8::Local<v8::Object> obj = _queryManyResultToV8(result);
v8::Local<v8::Value> argv[2] = { Nan::Null(), obj };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
struct geometry_type_name
{
template <typename T>
std::string operator () (T const& geom) const
{
return mapnik::util::apply_visitor(*this, geom);
}
std::string operator() (mapnik::geometry::geometry_empty const& ) const
{
// LCOV_EXCL_START
return "Empty";
// LCOV_EXCL_STOP
}
template <typename T>
std::string operator () (mapnik::geometry::point<T> const&) const
{
return "Point";
}
template <typename T>
std::string operator () (mapnik::geometry::line_string<T> const&) const
{
return "LineString";
}
template <typename T>
std::string operator () (mapnik::geometry::polygon<T> const&) const
{
return "Polygon";
}
template <typename T>
std::string operator () (mapnik::geometry::multi_point<T> const&) const
{
return "MultiPoint";
}
template <typename T>
std::string operator () (mapnik::geometry::multi_line_string<T> const&) const
{
return "MultiLineString";
}
template <typename T>
std::string operator () (mapnik::geometry::multi_polygon<T> const&) const
{
return "MultiPolygon";
}
template <typename T>
std::string operator () (mapnik::geometry::geometry_collection<T> const&) const
{
// LCOV_EXCL_START
return "GeometryCollection";
// LCOV_EXCL_STOP
}
};
template <typename T>
static inline std::string geometry_type_as_string(T const& geom)
{
return geometry_type_name()(geom);
}
struct geometry_array_visitor
{
v8::Local<v8::Array> operator() (mapnik::geometry::geometry_empty const &)
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::point<T> const & geom)
{
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> arr = Nan::New<v8::Array>(2);
arr->Set(0, Nan::New<v8::Number>(geom.x));
arr->Set(1, Nan::New<v8::Number>(geom.y));
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::line_string<T> const & geom)
{
Nan::EscapableHandleScope scope;
if (geom.empty())
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::linear_ring<T> const & geom)
{
Nan::EscapableHandleScope scope;
if (geom.empty())
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::multi_point<T> const & geom)
{
Nan::EscapableHandleScope scope;
if (geom.empty())
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::multi_line_string<T> const & geom)
{
Nan::EscapableHandleScope scope;
if (geom.empty())
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::polygon<T> const & poly)
{
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> arr = Nan::New<v8::Array>(poly.size());
std::uint32_t index = 0;
for (auto const & ring : poly)
{
arr->Set(index++, (*this)(ring));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::multi_polygon<T> const & geom)
{
Nan::EscapableHandleScope scope;
if (geom.empty())
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
return scope.Escape(Nan::New<v8::Array>());
// LCOV_EXCL_STOP
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::geometry<T> const & geom)
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
Nan::EscapableHandleScope scope;
return scope.Escape(mapnik::util::apply_visitor((*this), geom));
// LCOV_EXCL_STOP
}
template <typename T>
v8::Local<v8::Array> operator() (mapnik::geometry::geometry_collection<T> const & geom)
{
// Removed as it should be a bug if a vector tile has reached this point
// therefore no known tests reach this point
// LCOV_EXCL_START
Nan::EscapableHandleScope scope;
if (geom.empty())
{
return scope.Escape(Nan::New<v8::Array>());
}
v8::Local<v8::Array> arr = Nan::New<v8::Array>(geom.size());
std::uint32_t c = 0;
for (auto const & pt : geom)
{
arr->Set(c++, (*this)(pt));
}
return scope.Escape(arr);
// LCOV_EXCL_STOP
}
};
template <typename T>
v8::Local<v8::Array> geometry_to_array(mapnik::geometry::geometry<T> const & geom)
{
Nan::EscapableHandleScope scope;
return scope.Escape(mapnik::util::apply_visitor(geometry_array_visitor(), geom));
}
struct json_value_visitor
{
v8::Local<v8::Object> & att_obj_;
std::string const& name_;
json_value_visitor(v8::Local<v8::Object> & att_obj,
std::string const& name)
: att_obj_(att_obj),
name_(name) {}
void operator() (std::string const& val)
{
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New(val).ToLocalChecked());
}
void operator() (bool const& val)
{
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New<v8::Boolean>(val));
}
void operator() (int64_t const& val)
{
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New<v8::Number>(val));
}
void operator() (uint64_t const& val)
{
// LCOV_EXCL_START
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New<v8::Number>(val));
// LCOV_EXCL_STOP
}
void operator() (double const& val)
{
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New<v8::Number>(val));
}
void operator() (float const& val)
{
att_obj_->Set(Nan::New(name_).ToLocalChecked(), Nan::New<v8::Number>(val));
}
};
/**
* Get a JSON representation of this tile
*
* @memberof VectorTile
* @instance
* @name toJSON
* @param {Object} [options]
* @param {boolean} [options.decode_geometry=false] return geometry as integers
* relative to the tile grid
* @returns {Object} json representation of this tile with name, extent,
* version, and feature properties
* @example
* var vt = mapnik.VectorTile(10,131,242);
* var buffer = fs.readFileSync('./path/to/data.mvt');
* vt.setData(buffer);
* var json = vectorTile.toJSON();
* console.log(json);
* // {
* // name: 'layer-name',
* // extent: 4096,
* // version: 2,
* // features: [ ... ] // array of objects
* // }
*/
NAN_METHOD(VectorTile::toJSON)
{
bool decode_geometry = false;
if (info.Length() >= 1)
{
if (!info[0]->IsObject())
{
Nan::ThrowError("The first argument must be an object");
return;
}
v8::Local<v8::Object> options = info[0]->ToObject();
if (options->Has(Nan::New("decode_geometry").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("decode_geometry").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'decode_geometry' must be a boolean");
return;
}
decode_geometry = param_val->BooleanValue();
}
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
try
{
protozero::pbf_reader tile_msg = d->tile_->get_reader();
v8::Local<v8::Array> arr = Nan::New<v8::Array>(d->tile_->get_layers().size());
std::size_t l_idx = 0;
while (tile_msg.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
protozero::pbf_reader layer_msg = tile_msg.get_message();
v8::Local<v8::Object> layer_obj = Nan::New<v8::Object>();
std::vector<std::string> layer_keys;
mapnik::vector_tile_impl::layer_pbf_attr_type layer_values;
std::vector<protozero::pbf_reader> layer_features;
protozero::pbf_reader val_msg;
std::uint32_t version = 1;
while (layer_msg.next())
{
switch (layer_msg.tag())
{
case mapnik::vector_tile_impl::Layer_Encoding::NAME:
layer_obj->Set(Nan::New("name").ToLocalChecked(), Nan::New<v8::String>(layer_msg.get_string()).ToLocalChecked());
break;
case mapnik::vector_tile_impl::Layer_Encoding::FEATURES:
layer_features.push_back(layer_msg.get_message());
break;
case mapnik::vector_tile_impl::Layer_Encoding::KEYS:
layer_keys.push_back(layer_msg.get_string());
break;
case mapnik::vector_tile_impl::Layer_Encoding::VALUES:
val_msg = layer_msg.get_message();
while (val_msg.next())
{
switch(val_msg.tag())
{
case mapnik::vector_tile_impl::Value_Encoding::STRING:
layer_values.push_back(val_msg.get_string());
break;
case mapnik::vector_tile_impl::Value_Encoding::FLOAT:
layer_values.push_back(val_msg.get_float());
break;
case mapnik::vector_tile_impl::Value_Encoding::DOUBLE:
layer_values.push_back(val_msg.get_double());
break;
case mapnik::vector_tile_impl::Value_Encoding::INT:
layer_values.push_back(val_msg.get_int64());
break;
case mapnik::vector_tile_impl::Value_Encoding::UINT:
// LCOV_EXCL_START
layer_values.push_back(val_msg.get_uint64());
break;
// LCOV_EXCL_STOP
case mapnik::vector_tile_impl::Value_Encoding::SINT:
// LCOV_EXCL_START
layer_values.push_back(val_msg.get_sint64());
break;
// LCOV_EXCL_STOP
case mapnik::vector_tile_impl::Value_Encoding::BOOL:
layer_values.push_back(val_msg.get_bool());
break;
default:
// LCOV_EXCL_START
val_msg.skip();
break;
// LCOV_EXCL_STOP
}
}
break;
case mapnik::vector_tile_impl::Layer_Encoding::EXTENT:
layer_obj->Set(Nan::New("extent").ToLocalChecked(), Nan::New<v8::Integer>(layer_msg.get_uint32()));
break;
case mapnik::vector_tile_impl::Layer_Encoding::VERSION:
version = layer_msg.get_uint32();
layer_obj->Set(Nan::New("version").ToLocalChecked(), Nan::New<v8::Integer>(version));
break;
default:
// LCOV_EXCL_START
layer_msg.skip();
break;
// LCOV_EXCL_STOP
}
}
v8::Local<v8::Array> f_arr = Nan::New<v8::Array>(layer_features.size());
std::size_t f_idx = 0;
for (auto feature_msg : layer_features)
{
v8::Local<v8::Object> feature_obj = Nan::New<v8::Object>();
mapnik::vector_tile_impl::GeometryPBF::pbf_itr geom_itr;
mapnik::vector_tile_impl::GeometryPBF::pbf_itr tag_itr;
bool has_geom = false;
bool has_geom_type = false;
bool has_tags = false;
std::int32_t geom_type_enum = 0;
while (feature_msg.next())
{
switch (feature_msg.tag())
{
case mapnik::vector_tile_impl::Feature_Encoding::ID:
feature_obj->Set(Nan::New("id").ToLocalChecked(),Nan::New<v8::Number>(feature_msg.get_uint64()));
break;
case mapnik::vector_tile_impl::Feature_Encoding::TAGS:
tag_itr = feature_msg.get_packed_uint32();
has_tags = true;
break;
case mapnik::vector_tile_impl::Feature_Encoding::TYPE:
geom_type_enum = feature_msg.get_enum();
has_geom_type = true;
feature_obj->Set(Nan::New("type").ToLocalChecked(),Nan::New<v8::Integer>(geom_type_enum));
break;
case mapnik::vector_tile_impl::Feature_Encoding::GEOMETRY:
geom_itr = feature_msg.get_packed_uint32();
has_geom = true;
break;
case mapnik::vector_tile_impl::Feature_Encoding::RASTER:
{
auto im_buffer = feature_msg.get_view();
feature_obj->Set(Nan::New("raster").ToLocalChecked(),
Nan::CopyBuffer(im_buffer.data(), im_buffer.size()).ToLocalChecked());
break;
}
default:
// LCOV_EXCL_START
feature_msg.skip();
break;
// LCOV_EXCL_STOP
}
}
v8::Local<v8::Object> att_obj = Nan::New<v8::Object>();
if (has_tags)
{
for (auto _i = tag_itr.begin(); _i != tag_itr.end();)
{
std::size_t key_name = *(_i++);
if (_i == tag_itr.end())
{
break;
}
std::size_t key_value = *(_i++);
if (key_name < layer_keys.size() &&
key_value < layer_values.size())
{
std::string const& name = layer_keys.at(key_name);
mapnik::vector_tile_impl::pbf_attr_value_type val = layer_values.at(key_value);
json_value_visitor vv(att_obj, name);
mapnik::util::apply_visitor(vv, val);
}
}
}
feature_obj->Set(Nan::New("properties").ToLocalChecked(),att_obj);
if (has_geom && has_geom_type)
{
if (decode_geometry)
{
// Decode the geometry first into an int64_t mapnik geometry
mapnik::vector_tile_impl::GeometryPBF geoms(geom_itr);
mapnik::geometry::geometry<std::int64_t> geom = mapnik::vector_tile_impl::decode_geometry<std::int64_t>(geoms, geom_type_enum, version, 0, 0, 1.0, 1.0);
v8::Local<v8::Array> g_arr = geometry_to_array<std::int64_t>(geom);
feature_obj->Set(Nan::New("geometry").ToLocalChecked(),g_arr);
std::string geom_type = geometry_type_as_string(geom);
feature_obj->Set(Nan::New("geometry_type").ToLocalChecked(),Nan::New(geom_type).ToLocalChecked());
}
else
{
std::vector<std::uint32_t> geom_vec;
for (auto _i = geom_itr.begin(); _i != geom_itr.end(); ++_i)
{
geom_vec.push_back(*_i);
}
v8::Local<v8::Array> g_arr = Nan::New<v8::Array>(geom_vec.size());
for (std::size_t k = 0; k < geom_vec.size();++k)
{
g_arr->Set(k,Nan::New<v8::Number>(geom_vec[k]));
}
feature_obj->Set(Nan::New("geometry").ToLocalChecked(),g_arr);
}
}
f_arr->Set(f_idx++,feature_obj);
}
layer_obj->Set(Nan::New("features").ToLocalChecked(), f_arr);
arr->Set(l_idx++, layer_obj);
}
info.GetReturnValue().Set(arr);
return;
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
Nan::ThrowError(ex.what());
return;
// LCOV_EXCL_STOP
}
}
bool layer_to_geojson(protozero::pbf_reader const& layer,
std::string & result,
unsigned x,
unsigned y,
unsigned z)
{
mapnik::vector_tile_impl::tile_datasource_pbf ds(layer, x, y, z);
mapnik::projection wgs84("+init=epsg:4326",true);
mapnik::projection merc("+init=epsg:3857",true);
mapnik::proj_transform prj_trans(merc,wgs84);
// This mega box ensures we capture all features, including those
// outside the tile extent. Geometries outside the tile extent are
// likely when the vtile was created by clipping to a buffered extent
mapnik::query q(mapnik::box2d<double>(std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max()));
mapnik::layer_descriptor ld = ds.get_descriptor();
for (auto const& item : ld.get_descriptors())
{
q.add_property_name(item.get_name());
}
mapnik::featureset_ptr fs = ds.features(q);
bool first = true;
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
while ((feature = fs->next()))
{
if (first)
{
first = false;
}
else
{
result += "\n,";
}
std::string feature_str;
mapnik::feature_impl feature_new(feature->context(),feature->id());
feature_new.set_data(feature->get_data());
unsigned int n_err = 0;
feature_new.set_geometry(mapnik::geometry::reproject_copy(feature->get_geometry(), prj_trans, n_err));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
}
}
return !first;
}
/**
* Syncronous version of {@link VectorTile}
*
* @memberof VectorTile
* @instance
* @name toGeoJSONSync
* @param {string | number} [layer=__all__] Can be a zero-index integer representing
* a layer or the string keywords `__array__` or `__all__` to get all layers in the form
* of an array of GeoJSON `FeatureCollection`s or in the form of a single GeoJSON
* `FeatureCollection` with all layers smooshed inside
* @returns {string} stringified GeoJSON of all the features in this tile.
* @example
* var geojson = vectorTile.toGeoJSONSync('__all__');
* geojson // stringified GeoJSON
* JSON.parse(geojson); // GeoJSON object
*/
NAN_METHOD(VectorTile::toGeoJSONSync)
{
info.GetReturnValue().Set(_toGeoJSONSync(info));
}
void write_geojson_array(std::string & result,
VectorTile * v)
{
protozero::pbf_reader tile_msg = v->get_tile()->get_reader();
result += "[";
bool first = true;
while (tile_msg.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
if (first)
{
first = false;
}
else
{
result += ",";
}
auto data_view = tile_msg.get_view();
protozero::pbf_reader layer_msg(data_view);
protozero::pbf_reader name_msg(data_view);
std::string layer_name;
if (name_msg.next(mapnik::vector_tile_impl::Layer_Encoding::NAME))
{
layer_name = name_msg.get_string();
}
result += "{\"type\":\"FeatureCollection\",";
result += "\"name\":\"" + layer_name + "\",\"features\":[";
std::string features;
bool hit = layer_to_geojson(layer_msg,
features,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z());
if (hit)
{
result += features;
}
result += "]}";
}
result += "]";
}
void write_geojson_all(std::string & result,
VectorTile * v)
{
protozero::pbf_reader tile_msg = v->get_tile()->get_reader();
result += "{\"type\":\"FeatureCollection\",\"features\":[";
bool first = true;
while (tile_msg.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
protozero::pbf_reader layer_msg(tile_msg.get_message());
std::string features;
bool hit = layer_to_geojson(layer_msg,
features,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z());
if (hit)
{
if (first)
{
first = false;
}
else
{
result += ",";
}
result += features;
}
}
result += "]}";
}
bool write_geojson_layer_index(std::string & result,
std::size_t layer_idx,
VectorTile * v)
{
protozero::pbf_reader layer_msg;
if (v->get_tile()->layer_reader(layer_idx, layer_msg) &&
v->get_tile()->get_layers().size() > layer_idx)
{
std::string layer_name = v->get_tile()->get_layers()[layer_idx];
result += "{\"type\":\"FeatureCollection\",";
result += "\"name\":\"" + layer_name + "\",\"features\":[";
layer_to_geojson(layer_msg,
result,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z());
result += "]}";
return true;
}
// LCOV_EXCL_START
return false;
// LCOV_EXCL_STOP
}
bool write_geojson_layer_name(std::string & result,
std::string const& name,
VectorTile * v)
{
protozero::pbf_reader layer_msg;
if (v->get_tile()->layer_reader(name, layer_msg))
{
result += "{\"type\":\"FeatureCollection\",";
result += "\"name\":\"" + name + "\",\"features\":[";
layer_to_geojson(layer_msg,
result,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z());
result += "]}";
return true;
}
return false;
}
v8::Local<v8::Value> VectorTile::_toGeoJSONSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
if (info.Length() < 1)
{
Nan::ThrowError("first argument must be either a layer name (string) or layer index (integer)");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Value> layer_id = info[0];
if (! (layer_id->IsString() || layer_id->IsNumber()) )
{
Nan::ThrowTypeError("'layer' argument must be either a layer name (string) or layer index (integer)");
return scope.Escape(Nan::Undefined());
}
VectorTile* v = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
std::string result;
try
{
if (layer_id->IsString())
{
std::string layer_name = TOSTR(layer_id);
if (layer_name == "__array__")
{
write_geojson_array(result, v);
}
else if (layer_name == "__all__")
{
write_geojson_all(result, v);
}
else
{
if (!write_geojson_layer_name(result, layer_name, v))
{
std::string error_msg("Layer name '" + layer_name + "' not found");
Nan::ThrowTypeError(error_msg.c_str());
return scope.Escape(Nan::Undefined());
}
}
}
else if (layer_id->IsNumber())
{
int layer_idx = layer_id->IntegerValue();
if (layer_idx < 0)
{
Nan::ThrowTypeError("A layer index can not be negative");
return scope.Escape(Nan::Undefined());
}
else if (layer_idx >= static_cast<int>(v->get_tile()->get_layers().size()))
{
Nan::ThrowTypeError("Layer index exceeds the number of layers in the vector tile.");
return scope.Escape(Nan::Undefined());
}
if (!write_geojson_layer_index(result, layer_idx, v))
{
// LCOV_EXCL_START
Nan::ThrowTypeError("Layer could not be retrieved (should have not reached here)");
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
}
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
Nan::ThrowTypeError(ex.what());
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
return scope.Escape(Nan::New<v8::String>(result).ToLocalChecked());
}
enum geojson_write_type : std::uint8_t
{
geojson_write_all = 0,
geojson_write_array,
geojson_write_layer_name,
geojson_write_layer_index
};
struct to_geojson_baton
{
uv_work_t request;
VectorTile* v;
bool error;
std::string result;
geojson_write_type type;
int layer_idx;
std::string layer_name;
Nan::Persistent<v8::Function> cb;
};
/**
* Get a [GeoJSON](http://geojson.org/) representation of this tile
*
* @memberof VectorTile
* @instance
* @name toGeoJSON
* @param {string | number} [layer=__all__] Can be a zero-index integer representing
* a layer or the string keywords `__array__` or `__all__` to get all layers in the form
* of an array of GeoJSON `FeatureCollection`s or in the form of a single GeoJSON
* `FeatureCollection` with all layers smooshed inside
* @param {Function} callback - `function(err, geojson)`: a stringified
* GeoJSON of all the features in this tile
* @example
* vectorTile.toGeoJSON('__all__',function(err, geojson) {
* if (err) throw err;
* console.log(geojson); // stringified GeoJSON
* console.log(JSON.parse(geojson)); // GeoJSON object
* });
*/
NAN_METHOD(VectorTile::toGeoJSON)
{
if ((info.Length() < 1) || !info[info.Length()-1]->IsFunction())
{
info.GetReturnValue().Set(_toGeoJSONSync(info));
return;
}
to_geojson_baton *closure = new to_geojson_baton();
closure->request.data = closure;
closure->v = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
closure->error = false;
closure->layer_idx = 0;
closure->type = geojson_write_all;
v8::Local<v8::Value> layer_id = info[0];
if (! (layer_id->IsString() || layer_id->IsNumber()) )
{
delete closure;
Nan::ThrowTypeError("'layer' argument must be either a layer name (string) or layer index (integer)");
return;
}
if (layer_id->IsString())
{
std::string layer_name = TOSTR(layer_id);
if (layer_name == "__array__")
{
closure->type = geojson_write_array;
}
else if (layer_name == "__all__")
{
closure->type = geojson_write_all;
}
else
{
if (!closure->v->get_tile()->has_layer(layer_name))
{
delete closure;
std::string error_msg("The layer does not contain the name: " + layer_name);
Nan::ThrowTypeError(error_msg.c_str());
return;
}
closure->layer_name = layer_name;
closure->type = geojson_write_layer_name;
}
}
else if (layer_id->IsNumber())
{
closure->layer_idx = layer_id->IntegerValue();
if (closure->layer_idx < 0)
{
delete closure;
Nan::ThrowTypeError("A layer index can not be negative");
return;
}
else if (closure->layer_idx >= static_cast<int>(closure->v->get_tile()->get_layers().size()))
{
delete closure;
Nan::ThrowTypeError("Layer index exceeds the number of layers in the vector tile.");
return;
}
closure->type = geojson_write_layer_index;
}
v8::Local<v8::Value> callback = info[info.Length()-1];
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, to_geojson, (uv_after_work_cb)after_to_geojson);
closure->v->Ref();
return;
}
void VectorTile::to_geojson(uv_work_t* req)
{
to_geojson_baton *closure = static_cast<to_geojson_baton *>(req->data);
try
{
switch (closure->type)
{
default:
case geojson_write_all:
write_geojson_all(closure->result, closure->v);
break;
case geojson_write_array:
write_geojson_array(closure->result, closure->v);
break;
case geojson_write_layer_name:
write_geojson_layer_name(closure->result, closure->layer_name, closure->v);
break;
case geojson_write_layer_index:
write_geojson_layer_index(closure->result, closure->layer_idx, closure->v);
break;
}
}
catch (std::exception const& ex)
{
// There are currently no known ways to trigger this exception in testing. If it was
// triggered this would likely be a bug in either mapnik or mapnik-vector-tile.
// LCOV_EXCL_START
closure->error = true;
closure->result = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::after_to_geojson(uv_work_t* req)
{
Nan::HandleScope scope;
to_geojson_baton *closure = static_cast<to_geojson_baton *>(req->data);
if (closure->error)
{
// Because there are no known ways to trigger the exception path in to_geojson
// there is no easy way to test this path currently
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->result.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::New<v8::String>(closure->result).ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->v->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Add features to this tile from a GeoJSON string. GeoJSON coordinates must be in the WGS84 longitude & latitude CRS
* as specified in the [GeoJSON Specification](https://www.rfc-editor.org/rfc/rfc7946.txt).
*
* @memberof VectorTile
* @instance
* @name addGeoJSON
* @param {string} geojson as a string
* @param {string} name of the layer to be added
* @param {Object} [options]
* @param {number} [options.area_threshold=0.1] used to discard small polygons.
* If a value is greater than `0` it will trigger polygons with an area smaller
* than the value to be discarded. Measured in grid integers, not spherical mercator
* coordinates.
* @param {number} [options.simplify_distance=0.0] Simplification works to generalize
* geometries before encoding into vector tiles.simplification distance The
* `simplify_distance` value works in integer space over a 4096 pixel grid and uses
* the [Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm).
* @param {boolean} [options.strictly_simple=true] ensure all geometry is valid according to
* OGC Simple definition
* @param {boolean} [options.multi_polygon_union=false] union all multipolygons
* @param {Object<mapnik.polygonFillType>} [options.fill_type=mapnik.polygonFillType.positive]
* the fill type used in determining what are holes and what are outer rings. See the
* [Clipper documentation](http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm)
* to learn more about fill types.
* @param {boolean} [options.process_all_rings=false] if `true`, don't assume winding order and ring order of
* polygons are correct according to the [`2.0` Mapbox Vector Tile specification](https://github.com/mapbox/vector-tile-spec)
* @example
* var geojson = { ... };
* var vt = mapnik.VectorTile(0,0,0);
* vt.addGeoJSON(JSON.stringify(geojson), 'layer-name', {});
*/
NAN_METHOD(VectorTile::addGeoJSON)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsString())
{
Nan::ThrowError("first argument must be a GeoJSON string");
return;
}
if (info.Length() < 2 || !info[1]->IsString())
{
Nan::ThrowError("second argument must be a layer name (string)");
return;
}
std::string geojson_string = TOSTR(info[0]);
std::string geojson_name = TOSTR(info[1]);
v8::Local<v8::Object> options = Nan::New<v8::Object>();
double area_threshold = 0.1;
double simplify_distance = 0.0;
bool strictly_simple = true;
bool multi_polygon_union = false;
mapnik::vector_tile_impl::polygon_fill_type fill_type = mapnik::vector_tile_impl::positive_fill;
bool process_all_rings = false;
if (info.Length() > 2)
{
// options object
if (!info[2]->IsObject())
{
Nan::ThrowError("optional third argument must be an options object");
return;
}
options = info[2]->ToObject();
if (options->Has(Nan::New("area_threshold").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("area_threshold").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowError("option 'area_threshold' must be a number");
return;
}
area_threshold = param_val->IntegerValue();
if (area_threshold < 0.0)
{
Nan::ThrowError("option 'area_threshold' can not be negative");
return;
}
}
if (options->Has(Nan::New("strictly_simple").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("strictly_simple").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'strictly_simple' must be a boolean");
return;
}
strictly_simple = param_val->BooleanValue();
}
if (options->Has(Nan::New("multi_polygon_union").ToLocalChecked()))
{
v8::Local<v8::Value> mpu = options->Get(Nan::New("multi_polygon_union").ToLocalChecked());
if (!mpu->IsBoolean())
{
Nan::ThrowTypeError("multi_polygon_union value must be a boolean");
return;
}
multi_polygon_union = mpu->BooleanValue();
}
if (options->Has(Nan::New("fill_type").ToLocalChecked()))
{
v8::Local<v8::Value> ft = options->Get(Nan::New("fill_type").ToLocalChecked());
if (!ft->IsNumber())
{
Nan::ThrowTypeError("optional arg 'fill_type' must be a number");
return;
}
fill_type = static_cast<mapnik::vector_tile_impl::polygon_fill_type>(ft->IntegerValue());
if (fill_type >= mapnik::vector_tile_impl::polygon_fill_type_max)
{
Nan::ThrowTypeError("optional arg 'fill_type' out of possible range");
return;
}
}
if (options->Has(Nan::New("simplify_distance").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("simplify_distance").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'simplify_distance' must be an floating point number");
return;
}
simplify_distance = param_val->NumberValue();
if (simplify_distance < 0.0)
{
Nan::ThrowTypeError("option 'simplify_distance' must be a positive number");
return;
}
}
if (options->Has(Nan::New("process_all_rings").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("process_all_rings").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'process_all_rings' must be a boolean");
return;
}
process_all_rings = param_val->BooleanValue();
}
}
try
{
// create map object
mapnik::Map map(d->tile_size(),d->tile_size(),"+init=epsg:3857");
mapnik::parameters p;
p["type"]="geojson";
p["inline"]=geojson_string;
mapnik::layer lyr(geojson_name,"+init=epsg:4326");
lyr.set_datasource(mapnik::datasource_cache::instance().create(p));
map.add_layer(lyr);
mapnik::vector_tile_impl::processor ren(map);
ren.set_area_threshold(area_threshold);
ren.set_strictly_simple(strictly_simple);
ren.set_simplify_distance(simplify_distance);
ren.set_multi_polygon_union(multi_polygon_union);
ren.set_fill_type(fill_type);
ren.set_process_all_rings(process_all_rings);
ren.update_tile(*d->get_tile());
info.GetReturnValue().Set(Nan::True());
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return;
}
}
/**
* Add a {@link Image} as a tile layer (synchronous)
*
* @memberof VectorTile
* @instance
* @name addImageSync
* @param {mapnik.Image} image
* @param {string} name of the layer to be added
* @param {Object} options
* @param {string} [options.image_scaling=bilinear] can be any
* of the <mapnik.imageScaling> methods
* @param {string} [options.image_format=webp] or `jpeg`, `png`, `tiff`
* @example
* var vt = new mapnik.VectorTile(1, 0, 0, {
* tile_size:256
* });
* var im = new mapnik.Image(256, 256);
* vt.addImageSync(im, 'layer-name', {
* image_format: 'jpeg',
* image_scaling: 'gaussian'
* });
*/
NAN_METHOD(VectorTile::addImageSync)
{
info.GetReturnValue().Set(_addImageSync(info));
}
v8::Local<v8::Value> VectorTile::_addImageSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowError("first argument must be an Image object");
return scope.Escape(Nan::Undefined());
}
if (info.Length() < 2 || !info[1]->IsString())
{
Nan::ThrowError("second argument must be a layer name (string)");
return scope.Escape(Nan::Undefined());
}
std::string layer_name = TOSTR(info[1]);
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() ||
obj->IsUndefined() ||
!Nan::New(Image::constructor)->HasInstance(obj))
{
Nan::ThrowError("first argument must be an Image object");
return scope.Escape(Nan::Undefined());
}
Image *im = Nan::ObjectWrap::Unwrap<Image>(obj);
if (im->get()->width() <= 0 || im->get()->height() <= 0)
{
Nan::ThrowError("Image width and height must be greater then zero");
return scope.Escape(Nan::Undefined());
}
std::string image_format = "webp";
mapnik::scaling_method_e scaling_method = mapnik::SCALING_BILINEAR;
if (info.Length() > 2)
{
// options object
if (!info[2]->IsObject())
{
Nan::ThrowError("optional third argument must be an options object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> options = info[2]->ToObject();
if (options->Has(Nan::New("image_scaling").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_scaling").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_scaling' must be a string");
return scope.Escape(Nan::Undefined());
}
std::string image_scaling = TOSTR(param_val);
boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(image_scaling);
if (!method)
{
Nan::ThrowTypeError("option 'image_scaling' must be a string and a valid scaling method (e.g 'bilinear')");
return scope.Escape(Nan::Undefined());
}
scaling_method = *method;
}
if (options->Has(Nan::New("image_format").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_format").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_format' must be a string");
return scope.Escape(Nan::Undefined());
}
image_format = TOSTR(param_val);
}
}
mapnik::image_any im_copy = *im->get();
std::shared_ptr<mapnik::memory_datasource> ds = std::make_shared<mapnik::memory_datasource>(mapnik::parameters());
mapnik::raster_ptr ras = std::make_shared<mapnik::raster>(d->get_tile()->extent(), im_copy, 1.0);
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
feature->set_raster(ras);
ds->push(feature);
ds->envelope(); // can be removed later, currently doesn't work with out this.
ds->set_envelope(d->get_tile()->extent());
try
{
// create map object
mapnik::Map map(d->tile_size(),d->tile_size(),"+init=epsg:3857");
mapnik::layer lyr(layer_name,"+init=epsg:3857");
lyr.set_datasource(ds);
map.add_layer(lyr);
mapnik::vector_tile_impl::processor ren(map);
ren.set_scaling_method(scaling_method);
ren.set_image_format(image_format);
ren.update_tile(*d->get_tile());
info.GetReturnValue().Set(Nan::True());
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return scope.Escape(Nan::Undefined());
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
Image* im;
std::string layer_name;
std::string image_format;
mapnik::scaling_method_e scaling_method;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} vector_tile_add_image_baton_t;
/**
* Add a <mapnik.Image> as a tile layer (asynchronous)
*
* @memberof VectorTile
* @instance
* @name addImage
* @param {mapnik.Image} image
* @param {string} name of the layer to be added
* @param {Object} [options]
* @param {string} [options.image_scaling=bilinear] can be any
* of the <mapnik.imageScaling> methods
* @param {string} [options.image_format=webp] other options include `jpeg`, `png`, `tiff`
* @example
* var vt = new mapnik.VectorTile(1, 0, 0, {
* tile_size:256
* });
* var im = new mapnik.Image(256, 256);
* vt.addImage(im, 'layer-name', {
* image_format: 'jpeg',
* image_scaling: 'gaussian'
* }, function(err) {
* if (err) throw err;
* // your custom code using `vt`
* });
*/
NAN_METHOD(VectorTile::addImage)
{
// If last param is not a function assume sync
if (info.Length() < 2)
{
Nan::ThrowError("addImage requires at least two parameters: an Image and a layer name");
return;
}
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!info[info.Length() - 1]->IsFunction())
{
info.GetReturnValue().Set(_addImageSync(info));
return;
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.This());
if (!info[0]->IsObject())
{
Nan::ThrowError("first argument must be an Image object");
return;
}
if (!info[1]->IsString())
{
Nan::ThrowError("second argument must be a layer name (string)");
return;
}
std::string layer_name = TOSTR(info[1]);
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() ||
obj->IsUndefined() ||
!Nan::New(Image::constructor)->HasInstance(obj))
{
Nan::ThrowError("first argument must be an Image object");
return;
}
Image *im = Nan::ObjectWrap::Unwrap<Image>(obj);
if (im->get()->width() <= 0 || im->get()->height() <= 0)
{
Nan::ThrowError("Image width and height must be greater then zero");
return;
}
std::string image_format = "webp";
mapnik::scaling_method_e scaling_method = mapnik::SCALING_BILINEAR;
if (info.Length() > 3)
{
// options object
if (!info[2]->IsObject())
{
Nan::ThrowError("optional third argument must be an options object");
return;
}
v8::Local<v8::Object> options = info[2]->ToObject();
if (options->Has(Nan::New("image_scaling").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_scaling").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_scaling' must be a string");
return;
}
std::string image_scaling = TOSTR(param_val);
boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(image_scaling);
if (!method)
{
Nan::ThrowTypeError("option 'image_scaling' must be a string and a valid scaling method (e.g 'bilinear')");
return;
}
scaling_method = *method;
}
if (options->Has(Nan::New("image_format").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("image_format").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'image_format' must be a string");
return;
}
image_format = TOSTR(param_val);
}
}
vector_tile_add_image_baton_t *closure = new vector_tile_add_image_baton_t();
closure->request.data = closure;
closure->d = d;
closure->im = im;
closure->scaling_method = scaling_method;
closure->image_format = image_format;
closure->layer_name = layer_name;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_AddImage, (uv_after_work_cb)EIO_AfterAddImage);
d->Ref();
im->_ref();
return;
}
void VectorTile::EIO_AddImage(uv_work_t* req)
{
vector_tile_add_image_baton_t *closure = static_cast<vector_tile_add_image_baton_t *>(req->data);
try
{
mapnik::image_any im_copy = *closure->im->get();
std::shared_ptr<mapnik::memory_datasource> ds = std::make_shared<mapnik::memory_datasource>(mapnik::parameters());
mapnik::raster_ptr ras = std::make_shared<mapnik::raster>(closure->d->get_tile()->extent(), im_copy, 1.0);
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
feature->set_raster(ras);
ds->push(feature);
ds->envelope(); // can be removed later, currently doesn't work with out this.
ds->set_envelope(closure->d->get_tile()->extent());
// create map object
mapnik::Map map(closure->d->tile_size(),closure->d->tile_size(),"+init=epsg:3857");
mapnik::layer lyr(closure->layer_name,"+init=epsg:3857");
lyr.set_datasource(ds);
map.add_layer(lyr);
mapnik::vector_tile_impl::processor ren(map);
ren.set_scaling_method(closure->scaling_method);
ren.set_image_format(closure->image_format);
ren.update_tile(*closure->d->get_tile());
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterAddImage(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_add_image_baton_t *closure = static_cast<vector_tile_add_image_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[1] = { Nan::Null() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
closure->d->Unref();
closure->im->_unref();
closure->cb.Reset();
delete closure;
}
/**
* Add raw image buffer as a new tile layer (synchronous)
*
* @memberof VectorTile
* @instance
* @name addImageBufferSync
* @param {Buffer} buffer - raw data
* @param {string} name - name of the layer to be added
* @example
* var vt = new mapnik.VectorTile(1, 0, 0, {
* tile_size: 256
* });
* var image_buffer = fs.readFileSync('./path/to/image.jpg');
* vt.addImageBufferSync(image_buffer, 'layer-name');
*/
NAN_METHOD(VectorTile::addImageBufferSync)
{
info.GetReturnValue().Set(_addImageBufferSync(info));
}
v8::Local<v8::Value> VectorTile::_addImageBufferSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return scope.Escape(Nan::Undefined());
}
if (info.Length() < 2 || !info[1]->IsString())
{
Nan::ThrowError("second argument must be a layer name (string)");
return scope.Escape(Nan::Undefined());
}
std::string layer_name = TOSTR(info[1]);
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return scope.Escape(Nan::Undefined());
}
std::size_t buffer_size = node::Buffer::Length(obj);
if (buffer_size <= 0)
{
Nan::ThrowError("cannot accept empty buffer as protobuf");
return scope.Escape(Nan::Undefined());
}
try
{
add_image_buffer_as_tile_layer(*d->get_tile(), layer_name, node::Buffer::Data(obj), buffer_size);
}
catch (std::exception const& ex)
{
// no obvious way to get this to throw in JS under obvious conditions
// but keep the standard exeption cache in C++
// LCOV_EXCL_START
Nan::ThrowError(ex.what());
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
const char *data;
size_t dataLength;
std::string layer_name;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
Nan::Persistent<v8::Object> buffer;
} vector_tile_addimagebuffer_baton_t;
/**
* Add an encoded image buffer as a layer
*
* @memberof VectorTile
* @instance
* @name addImageBuffer
* @param {Buffer} buffer - raw image data
* @param {string} name - name of the layer to be added
* @param {Function} callback
* @example
* var vt = new mapnik.VectorTile(1, 0, 0, {
* tile_size: 256
* });
* var image_buffer = fs.readFileSync('./path/to/image.jpg'); // returns a buffer
* vt.addImageBufferSync(image_buffer, 'layer-name', function(err) {
* if (err) throw err;
* // your custom code
* });
*/
NAN_METHOD(VectorTile::addImageBuffer)
{
if (info.Length() < 3)
{
info.GetReturnValue().Set(_addImageBufferSync(info));
return;
}
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!info[info.Length() - 1]->IsFunction())
{
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return;
}
if (info.Length() < 2 || !info[1]->IsString())
{
Nan::ThrowError("second argument must be a layer name (string)");
return;
}
std::string layer_name = TOSTR(info[1]);
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return;
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
vector_tile_addimagebuffer_baton_t *closure = new vector_tile_addimagebuffer_baton_t();
closure->request.data = closure;
closure->d = d;
closure->layer_name = layer_name;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
closure->buffer.Reset(obj.As<v8::Object>());
closure->data = node::Buffer::Data(obj);
closure->dataLength = node::Buffer::Length(obj);
uv_queue_work(uv_default_loop(), &closure->request, EIO_AddImageBuffer, (uv_after_work_cb)EIO_AfterAddImageBuffer);
d->Ref();
return;
}
void VectorTile::EIO_AddImageBuffer(uv_work_t* req)
{
vector_tile_addimagebuffer_baton_t *closure = static_cast<vector_tile_addimagebuffer_baton_t *>(req->data);
try
{
add_image_buffer_as_tile_layer(*closure->d->get_tile(), closure->layer_name, closure->data, closure->dataLength);
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
closure->error = true;
closure->error_name = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::EIO_AfterAddImageBuffer(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_addimagebuffer_baton_t *closure = static_cast<vector_tile_addimagebuffer_baton_t *>(req->data);
if (closure->error)
{
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Value> argv[1] = { Nan::Null() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
closure->d->Unref();
closure->cb.Reset();
closure->buffer.Reset();
delete closure;
}
/**
* Add raw data to this tile as a Buffer
*
* @memberof VectorTile
* @instance
* @name addDataSync
* @param {Buffer} buffer - raw data
* @param {object} [options]
* @param {boolean} [options.validate=false] - If true does validity checks mvt schema (not geometries)
* Will throw if anything invalid or unexpected is encountered in the data
* @param {boolean} [options.upgrade=false] - If true will upgrade v1 tiles to adhere to the v2 specification
* @example
* var data_buffer = fs.readFileSync('./path/to/data.mvt'); // returns a buffer
* // assumes you have created a vector tile object already
* vt.addDataSync(data_buffer);
* // your custom code
*/
NAN_METHOD(VectorTile::addDataSync)
{
info.GetReturnValue().Set(_addDataSync(info));
}
v8::Local<v8::Value> VectorTile::_addDataSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return scope.Escape(Nan::Undefined());
}
std::size_t buffer_size = node::Buffer::Length(obj);
if (buffer_size <= 0)
{
Nan::ThrowError("cannot accept empty buffer as protobuf");
return scope.Escape(Nan::Undefined());
}
bool upgrade = false;
bool validate = false;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 1)
{
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("second arg must be a options object");
return scope.Escape(Nan::Undefined());
}
options = info[1]->ToObject();
if (options->Has(Nan::New<v8::String>("validate").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("validate").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'validate' must be a boolean");
return scope.Escape(Nan::Undefined());
}
validate = param_val->BooleanValue();
}
if (options->Has(Nan::New<v8::String>("upgrade").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("upgrade").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'upgrade' must be a boolean");
return scope.Escape(Nan::Undefined());
}
upgrade = param_val->BooleanValue();
}
}
try
{
merge_from_compressed_buffer(*d->get_tile(), node::Buffer::Data(obj), buffer_size, validate, upgrade);
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return scope.Escape(Nan::Undefined());
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
const char *data;
bool validate;
bool upgrade;
size_t dataLength;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
Nan::Persistent<v8::Object> buffer;
} vector_tile_adddata_baton_t;
/**
* Add new vector tile data to an existing vector tile
*
* @memberof VectorTile
* @instance
* @name addData
* @param {Buffer} buffer - raw vector data
* @param {object} [options]
* @param {boolean} [options.validate=false] - If true does validity checks mvt schema (not geometries)
* Will throw if anything invalid or unexpected is encountered in the data
* @param {boolean} [options.upgrade=false] - If true will upgrade v1 tiles to adhere to the v2 specification
* @param {Object} callback
* @example
* var data_buffer = fs.readFileSync('./path/to/data.mvt'); // returns a buffer
* var vt = new mapnik.VectorTile(9,112,195);
* vt.addData(data_buffer, function(err) {
* if (err) throw err;
* // your custom code
* });
*/
NAN_METHOD(VectorTile::addData)
{
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!info[info.Length() - 1]->IsFunction())
{
info.GetReturnValue().Set(_addDataSync(info));
return;
}
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return;
}
bool upgrade = false;
bool validate = false;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 1)
{
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("second arg must be a options object");
return;
}
options = info[1]->ToObject();
if (options->Has(Nan::New<v8::String>("validate").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("validate").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'validate' must be a boolean");
return;
}
validate = param_val->BooleanValue();
}
if (options->Has(Nan::New<v8::String>("upgrade").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("upgrade").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'upgrade' must be a boolean");
return;
}
upgrade = param_val->BooleanValue();
}
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
vector_tile_adddata_baton_t *closure = new vector_tile_adddata_baton_t();
closure->request.data = closure;
closure->d = d;
closure->validate = validate;
closure->upgrade = upgrade;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
closure->buffer.Reset(obj.As<v8::Object>());
closure->data = node::Buffer::Data(obj);
closure->dataLength = node::Buffer::Length(obj);
uv_queue_work(uv_default_loop(), &closure->request, EIO_AddData, (uv_after_work_cb)EIO_AfterAddData);
d->Ref();
return;
}
void VectorTile::EIO_AddData(uv_work_t* req)
{
vector_tile_adddata_baton_t *closure = static_cast<vector_tile_adddata_baton_t *>(req->data);
if (closure->dataLength <= 0)
{
closure->error = true;
closure->error_name = "cannot accept empty buffer as protobuf";
return;
}
try
{
merge_from_compressed_buffer(*closure->d->get_tile(), closure->data, closure->dataLength, closure->validate, closure->upgrade);
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterAddData(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_adddata_baton_t *closure = static_cast<vector_tile_adddata_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[1] = { Nan::Null() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
closure->d->Unref();
closure->cb.Reset();
closure->buffer.Reset();
delete closure;
}
/**
* Replace the data in this vector tile with new raw data (synchronous). This function validates
* geometry according to the [Mapbox Vector Tile specification](https://github.com/mapbox/vector-tile-spec).
*
* @memberof VectorTile
* @instance
* @name setDataSync
* @param {Buffer} buffer - raw data
* @param {object} [options]
* @param {boolean} [options.validate=false] - If true does validity checks mvt schema (not geometries)
* Will throw if anything invalid or unexpected is encountered in the data
* @param {boolean} [options.upgrade=false] - If true will upgrade v1 tiles to adhere to the v2 specification
* @example
* var data = fs.readFileSync('./path/to/data.mvt');
* vectorTile.setDataSync(data);
* // your custom code
*/
NAN_METHOD(VectorTile::setDataSync)
{
info.GetReturnValue().Set(_setDataSync(info));
}
v8::Local<v8::Value> VectorTile::_setDataSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return scope.Escape(Nan::Undefined());
}
std::size_t buffer_size = node::Buffer::Length(obj);
if (buffer_size <= 0)
{
Nan::ThrowError("cannot accept empty buffer as protobuf");
return scope.Escape(Nan::Undefined());
}
bool upgrade = false;
bool validate = false;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 1)
{
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("second arg must be a options object");
return scope.Escape(Nan::Undefined());
}
options = info[1]->ToObject();
if (options->Has(Nan::New<v8::String>("validate").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("validate").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'validate' must be a boolean");
return scope.Escape(Nan::Undefined());
}
validate = param_val->BooleanValue();
}
if (options->Has(Nan::New<v8::String>("upgrade").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("upgrade").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'upgrade' must be a boolean");
return scope.Escape(Nan::Undefined());
}
upgrade = param_val->BooleanValue();
}
}
try
{
d->clear();
merge_from_compressed_buffer(*d->get_tile(), node::Buffer::Data(obj), buffer_size, validate, upgrade);
}
catch (std::exception const& ex)
{
Nan::ThrowError(ex.what());
return scope.Escape(Nan::Undefined());
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
const char *data;
bool validate;
bool upgrade;
size_t dataLength;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
Nan::Persistent<v8::Object> buffer;
} vector_tile_setdata_baton_t;
/**
* Replace the data in this vector tile with new raw data
*
* @memberof VectorTile
* @instance
* @name setData
* @param {Buffer} buffer - raw data
* @param {object} [options]
* @param {boolean} [options.validate=false] - If true does validity checks mvt schema (not geometries)
* Will throw if anything invalid or unexpected is encountered in the data
* @param {boolean} [options.upgrade=false] - If true will upgrade v1 tiles to adhere to the v2 specification
* @param {Function} callback
* @example
* var data = fs.readFileSync('./path/to/data.mvt');
* vectorTile.setData(data, function(err) {
* if (err) throw err;
* // your custom code
* });
*/
NAN_METHOD(VectorTile::setData)
{
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!info[info.Length() - 1]->IsFunction())
{
info.GetReturnValue().Set(_setDataSync(info));
return;
}
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("first argument must be a buffer object");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first arg must be a buffer object");
return;
}
bool upgrade = false;
bool validate = false;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 1)
{
if (!info[1]->IsObject())
{
Nan::ThrowTypeError("second arg must be a options object");
return;
}
options = info[1]->ToObject();
if (options->Has(Nan::New<v8::String>("validate").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("validate").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'validate' must be a boolean");
return;
}
validate = param_val->BooleanValue();
}
if (options->Has(Nan::New<v8::String>("upgrade").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("upgrade").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowTypeError("option 'upgrade' must be a boolean");
return;
}
upgrade = param_val->BooleanValue();
}
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
vector_tile_setdata_baton_t *closure = new vector_tile_setdata_baton_t();
closure->request.data = closure;
closure->validate = validate;
closure->upgrade = upgrade;
closure->d = d;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
closure->buffer.Reset(obj.As<v8::Object>());
closure->data = node::Buffer::Data(obj);
closure->dataLength = node::Buffer::Length(obj);
uv_queue_work(uv_default_loop(), &closure->request, EIO_SetData, (uv_after_work_cb)EIO_AfterSetData);
d->Ref();
return;
}
void VectorTile::EIO_SetData(uv_work_t* req)
{
vector_tile_setdata_baton_t *closure = static_cast<vector_tile_setdata_baton_t *>(req->data);
if (closure->dataLength <= 0)
{
closure->error = true;
closure->error_name = "cannot accept empty buffer as protobuf";
return;
}
try
{
closure->d->clear();
merge_from_compressed_buffer(*closure->d->get_tile(), closure->data, closure->dataLength, closure->validate, closure->upgrade);
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterSetData(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_setdata_baton_t *closure = static_cast<vector_tile_setdata_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[1] = { Nan::Null() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
closure->d->Unref();
closure->cb.Reset();
closure->buffer.Reset();
delete closure;
}
/**
* Get the data in this vector tile as a buffer (synchronous)
*
* @memberof VectorTile
* @instance
* @name getDataSync
* @param {Object} [options]
* @param {string} [options.compression=none] - can also be `gzip`
* @param {int} [options.level=0] a number `0` (no compression) to `9` (best compression)
* @param {string} options.strategy must be `FILTERED`, `HUFFMAN_ONLY`, `RLE`, `FIXED`, `DEFAULT`
* @returns {Buffer} raw data
* @example
* var data = vt.getData({
* compression: 'gzip',
* level: 9,
* strategy: 'FILTERED'
* });
*/
NAN_METHOD(VectorTile::getDataSync)
{
info.GetReturnValue().Set(_getDataSync(info));
}
v8::Local<v8::Value> VectorTile::_getDataSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
bool compress = false;
int level = Z_DEFAULT_COMPRESSION;
int strategy = Z_DEFAULT_STRATEGY;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 0)
{
if (!info[0]->IsObject())
{
Nan::ThrowTypeError("first arg must be a options object");
return scope.Escape(Nan::Undefined());
}
options = info[0]->ToObject();
if (options->Has(Nan::New<v8::String>("compression").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("compression").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'compression' must be a string, either 'gzip', or 'none' (default)");
return scope.Escape(Nan::Undefined());
}
compress = std::string("gzip") == (TOSTR(param_val->ToString()));
}
if (options->Has(Nan::New<v8::String>("level").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("level").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'level' must be an integer between 0 (no compression) and 9 (best compression) inclusive");
return scope.Escape(Nan::Undefined());
}
level = param_val->IntegerValue();
if (level < 0 || level > 9)
{
Nan::ThrowTypeError("option 'level' must be an integer between 0 (no compression) and 9 (best compression) inclusive");
return scope.Escape(Nan::Undefined());
}
}
if (options->Has(Nan::New<v8::String>("strategy").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("strategy").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'strategy' must be one of the following strings: FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT");
return scope.Escape(Nan::Undefined());
}
else if (std::string("FILTERED") == TOSTR(param_val->ToString()))
{
strategy = Z_FILTERED;
}
else if (std::string("HUFFMAN_ONLY") == TOSTR(param_val->ToString()))
{
strategy = Z_HUFFMAN_ONLY;
}
else if (std::string("RLE") == TOSTR(param_val->ToString()))
{
strategy = Z_RLE;
}
else if (std::string("FIXED") == TOSTR(param_val->ToString()))
{
strategy = Z_FIXED;
}
else if (std::string("DEFAULT") == TOSTR(param_val->ToString()))
{
strategy = Z_DEFAULT_STRATEGY;
}
else
{
Nan::ThrowTypeError("option 'strategy' must be one of the following strings: FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT");
return scope.Escape(Nan::Undefined());
}
}
}
try
{
std::size_t raw_size = d->tile_->size();
if (raw_size <= 0)
{
return scope.Escape(Nan::NewBuffer(0).ToLocalChecked());
}
else
{
if (raw_size >= node::Buffer::kMaxLength) {
// This is a valid test path, but I am excluding it from test coverage due to the
// requirement of loading a very large object in memory in order to test it.
// LCOV_EXCL_START
std::ostringstream s;
s << "Data is too large to convert to a node::Buffer ";
s << "(" << raw_size << " raw bytes >= node::Buffer::kMaxLength)";
Nan::ThrowTypeError(s.str().c_str());
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
if (!compress)
{
return scope.Escape(Nan::CopyBuffer((char*)d->tile_->data(),raw_size).ToLocalChecked());
}
else
{
std::string compressed;
mapnik::vector_tile_impl::zlib_compress(d->tile_->data(), raw_size, compressed, true, level, strategy);
return scope.Escape(Nan::CopyBuffer((char*)compressed.data(),compressed.size()).ToLocalChecked());
}
}
}
catch (std::exception const& ex)
{
// As all exception throwing paths are not easily testable or no way can be
// found to test with repeatability this exception path is not included
// in test coverage.
// LCOV_EXCL_START
Nan::ThrowTypeError(ex.what());
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
bool error;
std::string data;
bool compress;
int level;
int strategy;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} vector_tile_get_data_baton_t;
/**
* Get the data in this vector tile as a buffer (asynchronous)
* @memberof VectorTile
* @instance
* @name getData
* @param {Object} [options]
* @param {string} [options.compression=none] compression type can also be `gzip`
* @param {int} [options.level=0] a number `0` (no compression) to `9` (best compression)
* @param {string} options.strategy must be `FILTERED`, `HUFFMAN_ONLY`, `RLE`, `FIXED`, `DEFAULT`
* @param {Function} callback
* @example
* vt.getData({
* compression: 'gzip',
* level: 9,
* strategy: 'FILTERED'
* }, function(err, data) {
* if (err) throw err;
* console.log(data); // buffer
* });
*/
NAN_METHOD(VectorTile::getData)
{
if (info.Length() == 0 || !info[info.Length()-1]->IsFunction())
{
info.GetReturnValue().Set(_getDataSync(info));
return;
}
v8::Local<v8::Value> callback = info[info.Length()-1];
bool compress = false;
int level = Z_DEFAULT_COMPRESSION;
int strategy = Z_DEFAULT_STRATEGY;
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 1)
{
if (!info[0]->IsObject())
{
Nan::ThrowTypeError("first arg must be a options object");
return;
}
options = info[0]->ToObject();
if (options->Has(Nan::New("compression").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("compression").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'compression' must be a string, either 'gzip', or 'none' (default)");
return;
}
compress = std::string("gzip") == (TOSTR(param_val->ToString()));
}
if (options->Has(Nan::New("level").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("level").ToLocalChecked());
if (!param_val->IsNumber())
{
Nan::ThrowTypeError("option 'level' must be an integer between 0 (no compression) and 9 (best compression) inclusive");
return;
}
level = param_val->IntegerValue();
if (level < 0 || level > 9)
{
Nan::ThrowTypeError("option 'level' must be an integer between 0 (no compression) and 9 (best compression) inclusive");
return;
}
}
if (options->Has(Nan::New("strategy").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("strategy").ToLocalChecked());
if (!param_val->IsString())
{
Nan::ThrowTypeError("option 'strategy' must be one of the following strings: FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT");
return;
}
else if (std::string("FILTERED") == TOSTR(param_val->ToString()))
{
strategy = Z_FILTERED;
}
else if (std::string("HUFFMAN_ONLY") == TOSTR(param_val->ToString()))
{
strategy = Z_HUFFMAN_ONLY;
}
else if (std::string("RLE") == TOSTR(param_val->ToString()))
{
strategy = Z_RLE;
}
else if (std::string("FIXED") == TOSTR(param_val->ToString()))
{
strategy = Z_FIXED;
}
else if (std::string("DEFAULT") == TOSTR(param_val->ToString()))
{
strategy = Z_DEFAULT_STRATEGY;
}
else
{
Nan::ThrowTypeError("option 'strategy' must be one of the following strings: FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT");
return;
}
}
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
vector_tile_get_data_baton_t *closure = new vector_tile_get_data_baton_t();
closure->request.data = closure;
closure->d = d;
closure->compress = compress;
closure->level = level;
closure->strategy = strategy;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, get_data, (uv_after_work_cb)after_get_data);
d->Ref();
return;
}
void VectorTile::get_data(uv_work_t* req)
{
vector_tile_get_data_baton_t *closure = static_cast<vector_tile_get_data_baton_t *>(req->data);
try
{
// compress if requested
if (closure->compress)
{
mapnik::vector_tile_impl::zlib_compress(closure->d->tile_->data(), closure->d->tile_->size(), closure->data, true, closure->level, closure->strategy);
}
}
catch (std::exception const& ex)
{
// As all exception throwing paths are not easily testable or no way can be
// found to test with repeatability this exception path is not included
// in test coverage.
// LCOV_EXCL_START
closure->error = true;
closure->error_name = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::after_get_data(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_get_data_baton_t *closure = static_cast<vector_tile_get_data_baton_t *>(req->data);
if (closure->error)
{
// As all exception throwing paths are not easily testable or no way can be
// found to test with repeatability this exception path is not included
// in test coverage.
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else if (!closure->data.empty())
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::CopyBuffer((char*)closure->data.data(),closure->data.size()).ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
else
{
std::size_t raw_size = closure->d->tile_->size();
if (raw_size <= 0)
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::NewBuffer(0).ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
else if (raw_size >= node::Buffer::kMaxLength)
{
// This is a valid test path, but I am excluding it from test coverage due to the
// requirement of loading a very large object in memory in order to test it.
// LCOV_EXCL_START
std::ostringstream s;
s << "Data is too large to convert to a node::Buffer ";
s << "(" << raw_size << " raw bytes >= node::Buffer::kMaxLength)";
v8::Local<v8::Value> argv[1] = { Nan::Error(s.str().c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::CopyBuffer((char*)closure->d->tile_->data(),raw_size).ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
}
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
struct dummy_surface {};
using surface_type = mapnik::util::variant
<dummy_surface,
Image *,
CairoSurface *
#if defined(GRID_RENDERER)
,Grid *
#endif
>;
struct deref_visitor
{
void operator() (dummy_surface) {} // no-op
template <typename SurfaceType>
void operator() (SurfaceType * surface)
{
if (surface != nullptr)
{
surface->_unref();
}
}
};
struct vector_tile_render_baton_t
{
uv_work_t request;
Map* m;
VectorTile * d;
surface_type surface;
mapnik::attributes variables;
std::string error_name;
Nan::Persistent<v8::Function> cb;
std::string result;
std::size_t layer_idx;
std::int64_t z;
std::int64_t x;
std::int64_t y;
unsigned width;
unsigned height;
int buffer_size;
double scale_factor;
double scale_denominator;
bool use_cairo;
bool zxy_override;
bool error;
vector_tile_render_baton_t() :
request(),
m(nullptr),
d(nullptr),
surface(),
variables(),
error_name(),
cb(),
result(),
layer_idx(0),
z(0),
x(0),
y(0),
width(0),
height(0),
buffer_size(0),
scale_factor(1.0),
scale_denominator(0.0),
use_cairo(true),
zxy_override(false),
error(false)
{}
~vector_tile_render_baton_t()
{
mapnik::util::apply_visitor(deref_visitor(),surface);
}
};
struct baton_guard
{
baton_guard(vector_tile_render_baton_t * baton) :
baton_(baton),
released_(false) {}
~baton_guard()
{
if (!released_) delete baton_;
}
void release()
{
released_ = true;
}
vector_tile_render_baton_t * baton_;
bool released_;
};
/**
* Render/write this vector tile to a surface/image, like a {@link Image}
*
* @name render
* @memberof VectorTile
* @instance
* @param {mapnik.Map} map - mapnik map object
* @param {mapnik.Image} surface - renderable surface object
* @param {Object} [options]
* @param {number} [options.z] an integer zoom level. Must be used with `x` and `y`
* @param {number} [options.x] an integer x coordinate. Must be used with `y` and `z`.
* @param {number} [options.y] an integer y coordinate. Must be used with `x` and `z`
* @param {number} [options.buffer_size] the size of the tile's buffer
* @param {number} [options.scale] floating point scale factor size to used
* for rendering
* @param {number} [options.scale_denominator] An floating point `scale_denominator`
* to be used by Mapnik when matching zoom filters. If provided this overrides the
* auto-calculated scale_denominator that is based on the map dimensions and bbox.
* Do not set this option unless you know what it means.
* @param {Object} [options.variables] Mapnik 3.x ONLY: A javascript object
* containing key value pairs that should be passed into Mapnik as variables
* for rendering and for datasource queries. For example if you passed
* `vtile.render(map,image,{ variables : {zoom:1} },cb)` then the `@zoom`
* variable would be usable in Mapnik symbolizers like `line-width:"@zoom"`
* and as a token in Mapnik postgis sql sub-selects like
* `(select * from table where some_field > @zoom)` as tmp
* @param {string} [options.renderer] must be `cairo` or `svg`
* @param {string|number} [options.layer] option required for grid rendering
* and must be either a layer name (string) or layer index (integer)
* @param {Array<string>} [options.fields] must be an array of strings
* @param {Function} callback
* @example
* var vt = new mapnik.VectorTile(0,0,0);
* var tileSize = vt.tileSize;
* var map = new mapnik.Map(tileSize, tileSize);
* vt.render(map, new mapnik.Image(256,256), function(err, image) {
* if (err) throw err;
* // save the rendered image to an existing image file somewhere
* // see mapnik.Image for available methods
* image.save('./path/to/image/file.png', 'png32');
* });
*/
NAN_METHOD(VectorTile::render)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("mapnik.Map expected as first arg");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Map::constructor)->HasInstance(obj))
{
Nan::ThrowTypeError("mapnik.Map expected as first arg");
return;
}
Map *m = Nan::ObjectWrap::Unwrap<Map>(obj);
if (info.Length() < 2 || !info[1]->IsObject())
{
Nan::ThrowTypeError("a renderable mapnik object is expected as second arg");
return;
}
v8::Local<v8::Object> im_obj = info[1]->ToObject();
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length()-1];
if (!info[info.Length()-1]->IsFunction())
{
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
vector_tile_render_baton_t *closure = new vector_tile_render_baton_t();
baton_guard guard(closure);
v8::Local<v8::Object> options = Nan::New<v8::Object>();
if (info.Length() > 2)
{
bool set_x = false;
bool set_y = false;
bool set_z = false;
if (!info[2]->IsObject())
{
Nan::ThrowTypeError("optional third argument must be an options object");
return;
}
options = info[2]->ToObject();
if (options->Has(Nan::New("z").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("z").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'z' must be a number");
return;
}
closure->z = bind_opt->IntegerValue();
set_z = true;
closure->zxy_override = true;
}
if (options->Has(Nan::New("x").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("x").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'x' must be a number");
return;
}
closure->x = bind_opt->IntegerValue();
set_x = true;
closure->zxy_override = true;
}
if (options->Has(Nan::New("y").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("y").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'y' must be a number");
return;
}
closure->y = bind_opt->IntegerValue();
set_y = true;
closure->zxy_override = true;
}
if (closure->zxy_override)
{
if (!set_z || !set_x || !set_y)
{
Nan::ThrowTypeError("original args 'z', 'x', and 'y' must all be used together");
return;
}
if (closure->x < 0 || closure->y < 0 || closure->z < 0)
{
Nan::ThrowTypeError("original args 'z', 'x', and 'y' can not be negative");
return;
}
std::int64_t max_at_zoom = pow(2,closure->z);
if (closure->x >= max_at_zoom)
{
Nan::ThrowTypeError("required parameter x is out of range of possible values based on z value");
return;
}
if (closure->y >= max_at_zoom)
{
Nan::ThrowTypeError("required parameter y is out of range of possible values based on z value");
return;
}
}
if (options->Has(Nan::New("buffer_size").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("buffer_size").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'buffer_size' must be a number");
return;
}
closure->buffer_size = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("scale").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale' must be a number");
return;
}
closure->scale_factor = bind_opt->NumberValue();
}
if (options->Has(Nan::New("scale_denominator").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("scale_denominator").ToLocalChecked());
if (!bind_opt->IsNumber())
{
Nan::ThrowTypeError("optional arg 'scale_denominator' must be a number");
return;
}
closure->scale_denominator = bind_opt->NumberValue();
}
if (options->Has(Nan::New("variables").ToLocalChecked()))
{
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("variables").ToLocalChecked());
if (!bind_opt->IsObject())
{
Nan::ThrowTypeError("optional arg 'variables' must be an object");
return;
}
object_to_container(closure->variables,bind_opt->ToObject());
}
}
closure->layer_idx = 0;
if (Nan::New(Image::constructor)->HasInstance(im_obj))
{
Image *im = Nan::ObjectWrap::Unwrap<Image>(im_obj);
im->_ref();
closure->width = im->get()->width();
closure->height = im->get()->height();
closure->surface = im;
}
else if (Nan::New(CairoSurface::constructor)->HasInstance(im_obj))
{
CairoSurface *c = Nan::ObjectWrap::Unwrap<CairoSurface>(im_obj);
c->_ref();
closure->width = c->width();
closure->height = c->height();
closure->surface = c;
if (options->Has(Nan::New("renderer").ToLocalChecked()))
{
v8::Local<v8::Value> renderer = options->Get(Nan::New("renderer").ToLocalChecked());
if (!renderer->IsString() )
{
Nan::ThrowError("'renderer' option must be a string of either 'svg' or 'cairo'");
return;
}
std::string renderer_name = TOSTR(renderer);
if (renderer_name == "cairo")
{
closure->use_cairo = true;
}
else if (renderer_name == "svg")
{
closure->use_cairo = false;
}
else
{
Nan::ThrowError("'renderer' option must be a string of either 'svg' or 'cairo'");
return;
}
}
}
#if defined(GRID_RENDERER)
else if (Nan::New(Grid::constructor)->HasInstance(im_obj))
{
Grid *g = Nan::ObjectWrap::Unwrap<Grid>(im_obj);
g->_ref();
closure->width = g->get()->width();
closure->height = g->get()->height();
closure->surface = g;
std::size_t layer_idx = 0;
// grid requires special options for now
if (!options->Has(Nan::New("layer").ToLocalChecked()))
{
Nan::ThrowTypeError("'layer' option required for grid rendering and must be either a layer name(string) or layer index (integer)");
return;
}
else
{
std::vector<mapnik::layer> const& layers = m->get()->layers();
v8::Local<v8::Value> layer_id = options->Get(Nan::New("layer").ToLocalChecked());
if (layer_id->IsString())
{
bool found = false;
unsigned int idx(0);
std::string layer_name = TOSTR(layer_id);
for (mapnik::layer const& lyr : layers)
{
if (lyr.name() == layer_name)
{
found = true;
layer_idx = idx;
break;
}
++idx;
}
if (!found)
{
std::ostringstream s;
s << "Layer name '" << layer_name << "' not found";
Nan::ThrowTypeError(s.str().c_str());
return;
}
}
else if (layer_id->IsNumber())
{
layer_idx = layer_id->IntegerValue();
std::size_t layer_num = layers.size();
if (layer_idx >= layer_num)
{
std::ostringstream s;
s << "Zero-based layer index '" << layer_idx << "' not valid, ";
if (layer_num > 0)
{
s << "only '" << layer_num << "' layers exist in map";
}
else
{
s << "no layers found in map";
}
Nan::ThrowTypeError(s.str().c_str());
return;
}
}
else
{
Nan::ThrowTypeError("'layer' option required for grid rendering and must be either a layer name(string) or layer index (integer)");
return;
}
}
if (options->Has(Nan::New("fields").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("fields").ToLocalChecked());
if (!param_val->IsArray())
{
Nan::ThrowTypeError("option 'fields' must be an array of strings");
return;
}
v8::Local<v8::Array> a = v8::Local<v8::Array>::Cast(param_val);
unsigned int i = 0;
unsigned int num_fields = a->Length();
while (i < num_fields)
{
v8::Local<v8::Value> name = a->Get(i);
if (name->IsString())
{
g->get()->add_field(TOSTR(name));
}
++i;
}
}
closure->layer_idx = layer_idx;
}
#endif
else
{
Nan::ThrowTypeError("renderable mapnik object expected as second arg");
return;
}
closure->request.data = closure;
closure->d = d;
closure->m = m;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_RenderTile, (uv_after_work_cb)EIO_AfterRenderTile);
m->_ref();
d->Ref();
guard.release();
return;
}
template <typename Renderer> void process_layers(Renderer & ren,
mapnik::request const& m_req,
mapnik::projection const& map_proj,
std::vector<mapnik::layer> const& layers,
double scale_denom,
std::string const& map_srs,
vector_tile_render_baton_t *closure)
{
for (auto const& lyr : layers)
{
if (lyr.visible(scale_denom))
{
protozero::pbf_reader layer_msg;
if (closure->d->get_tile()->layer_reader(lyr.name(), layer_msg))
{
mapnik::layer lyr_copy(lyr);
lyr_copy.set_srs(map_srs);
std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf> ds = std::make_shared<
mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
closure->d->get_tile()->x(),
closure->d->get_tile()->y(),
closure->d->get_tile()->z());
ds->set_envelope(m_req.get_buffered_extent());
lyr_copy.set_datasource(ds);
std::set<std::string> names;
ren.apply_to_layer(lyr_copy,
ren,
map_proj,
m_req.scale(),
scale_denom,
m_req.width(),
m_req.height(),
m_req.extent(),
m_req.buffer_size(),
names);
}
}
}
}
void VectorTile::EIO_RenderTile(uv_work_t* req)
{
vector_tile_render_baton_t *closure = static_cast<vector_tile_render_baton_t *>(req->data);
try
{
mapnik::Map const& map_in = *closure->m->get();
mapnik::vector_tile_impl::spherical_mercator merc(closure->d->tile_size());
double minx,miny,maxx,maxy;
if (closure->zxy_override)
{
merc.xyz(closure->x,closure->y,closure->z,minx,miny,maxx,maxy);
}
else
{
merc.xyz(closure->d->get_tile()->x(),
closure->d->get_tile()->y(),
closure->d->get_tile()->z(),
minx,miny,maxx,maxy);
}
mapnik::box2d<double> map_extent(minx,miny,maxx,maxy);
mapnik::request m_req(closure->width, closure->height, map_extent);
m_req.set_buffer_size(closure->buffer_size);
mapnik::projection map_proj(map_in.srs(),true);
double scale_denom = closure->scale_denominator;
if (scale_denom <= 0.0)
{
scale_denom = mapnik::scale_denominator(m_req.scale(),map_proj.is_geographic());
}
scale_denom *= closure->scale_factor;
std::vector<mapnik::layer> const& layers = map_in.layers();
#if defined(GRID_RENDERER)
// render grid for layer
if (closure->surface.is<Grid *>())
{
Grid * g = mapnik::util::get<Grid *>(closure->surface);
mapnik::grid_renderer<mapnik::grid> ren(map_in,
m_req,
closure->variables,
*(g->get()),
closure->scale_factor);
ren.start_map_processing(map_in);
mapnik::layer const& lyr = layers[closure->layer_idx];
if (lyr.visible(scale_denom))
{
protozero::pbf_reader layer_msg;
if (closure->d->get_tile()->layer_reader(lyr.name(),layer_msg))
{
// copy field names
std::set<std::string> attributes = g->get()->get_fields();
// todo - make this a static constant
std::string known_id_key = "__id__";
if (attributes.find(known_id_key) != attributes.end())
{
attributes.erase(known_id_key);
}
std::string join_field = g->get()->get_key();
if (known_id_key != join_field &&
attributes.find(join_field) == attributes.end())
{
attributes.insert(join_field);
}
mapnik::layer lyr_copy(lyr);
lyr_copy.set_srs(map_in.srs());
std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf> ds = std::make_shared<
mapnik::vector_tile_impl::tile_datasource_pbf>(
layer_msg,
closure->d->get_tile()->x(),
closure->d->get_tile()->y(),
closure->d->get_tile()->z());
ds->set_envelope(m_req.get_buffered_extent());
lyr_copy.set_datasource(ds);
ren.apply_to_layer(lyr_copy,
ren,
map_proj,
m_req.scale(),
scale_denom,
m_req.width(),
m_req.height(),
m_req.extent(),
m_req.buffer_size(),
attributes);
}
ren.end_map_processing(map_in);
}
}
else
#endif
if (closure->surface.is<CairoSurface *>())
{
CairoSurface * c = mapnik::util::get<CairoSurface *>(closure->surface);
if (closure->use_cairo)
{
#if defined(HAVE_CAIRO)
mapnik::cairo_surface_ptr surface;
// TODO - support any surface type
surface = mapnik::cairo_surface_ptr(cairo_svg_surface_create_for_stream(
(cairo_write_func_t)c->write_callback,
(void*)(&c->ss_),
static_cast<double>(c->width()),
static_cast<double>(c->height())
),mapnik::cairo_surface_closer());
mapnik::cairo_ptr c_context = mapnik::create_context(surface);
mapnik::cairo_renderer<mapnik::cairo_ptr> ren(map_in,m_req,
closure->variables,
c_context,closure->scale_factor);
ren.start_map_processing(map_in);
process_layers(ren,m_req,map_proj,layers,scale_denom,map_in.srs(),closure);
ren.end_map_processing(map_in);
#else
closure->error = true;
closure->error_name = "no support for rendering svg with cairo backend";
#endif
}
else
{
#if defined(SVG_RENDERER)
typedef mapnik::svg_renderer<std::ostream_iterator<char> > svg_ren;
std::ostream_iterator<char> output_stream_iterator(c->ss_);
svg_ren ren(map_in, m_req,
closure->variables,
output_stream_iterator, closure->scale_factor);
ren.start_map_processing(map_in);
process_layers(ren,m_req,map_proj,layers,scale_denom,map_in.srs(),closure);
ren.end_map_processing(map_in);
#else
closure->error = true;
closure->error_name = "no support for rendering svg with native svg backend (-DSVG_RENDERER)";
#endif
}
}
// render all layers with agg
else if (closure->surface.is<Image *>())
{
Image * js_image = mapnik::util::get<Image *>(closure->surface);
mapnik::image_any & im = *(js_image->get());
if (im.is<mapnik::image_rgba8>())
{
mapnik::image_rgba8 & im_data = mapnik::util::get<mapnik::image_rgba8>(im);
mapnik::agg_renderer<mapnik::image_rgba8> ren(map_in,m_req,
closure->variables,
im_data,closure->scale_factor);
ren.start_map_processing(map_in);
process_layers(ren,m_req,map_proj,layers,scale_denom,map_in.srs(),closure);
ren.end_map_processing(map_in);
}
else
{
throw std::runtime_error("This image type is not currently supported for rendering.");
}
}
}
catch (std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void VectorTile::EIO_AfterRenderTile(uv_work_t* req)
{
Nan::HandleScope scope;
vector_tile_render_baton_t *closure = static_cast<vector_tile_render_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
if (closure->surface.is<Image *>())
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), mapnik::util::get<Image *>(closure->surface)->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
#if defined(GRID_RENDERER)
else if (closure->surface.is<Grid *>())
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), mapnik::util::get<Grid *>(closure->surface)->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
#endif
else if (closure->surface.is<CairoSurface *>())
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), mapnik::util::get<CairoSurface *>(closure->surface)->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
}
closure->m->_unref();
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Remove all data from this vector tile (synchronously)
* @name clearSync
* @memberof VectorTile
* @instance
* @example
* vt.clearSync();
* console.log(vt.getData().length); // 0
*/
NAN_METHOD(VectorTile::clearSync)
{
info.GetReturnValue().Set(_clearSync(info));
}
v8::Local<v8::Value> VectorTile::_clearSync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
d->clear();
return scope.Escape(Nan::Undefined());
}
typedef struct
{
uv_work_t request;
VectorTile* d;
std::string format;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} clear_vector_tile_baton_t;
/**
* Remove all data from this vector tile
*
* @memberof VectorTile
* @instance
* @name clear
* @param {Function} callback
* @example
* vt.clear(function(err) {
* if (err) throw err;
* console.log(vt.getData().length); // 0
* });
*/
NAN_METHOD(VectorTile::clear)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (info.Length() == 0)
{
info.GetReturnValue().Set(_clearSync(info));
return;
}
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!callback->IsFunction())
{
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
clear_vector_tile_baton_t *closure = new clear_vector_tile_baton_t();
closure->request.data = closure;
closure->d = d;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_Clear, (uv_after_work_cb)EIO_AfterClear);
d->Ref();
return;
}
void VectorTile::EIO_Clear(uv_work_t* req)
{
clear_vector_tile_baton_t *closure = static_cast<clear_vector_tile_baton_t *>(req->data);
try
{
closure->d->clear();
}
catch(std::exception const& ex)
{
// No reason this should ever throw an exception, not currently testable.
// LCOV_EXCL_START
closure->error = true;
closure->error_name = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::EIO_AfterClear(uv_work_t* req)
{
Nan::HandleScope scope;
clear_vector_tile_baton_t *closure = static_cast<clear_vector_tile_baton_t *>(req->data);
if (closure->error)
{
// No reason this should ever throw an exception, not currently testable.
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Value> argv[1] = { Nan::Null() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
closure->d->Unref();
closure->cb.Reset();
delete closure;
}
#if BOOST_VERSION >= 105800
// LCOV_EXCL_START
struct not_simple_feature
{
not_simple_feature(std::string const& layer_,
std::int64_t feature_id_)
: layer(layer_),
feature_id(feature_id_) {}
std::string const layer;
std::int64_t const feature_id;
};
// LCOV_EXCL_STOP
struct not_valid_feature
{
not_valid_feature(std::string const& message_,
std::string const& layer_,
std::int64_t feature_id_,
std::string const& geojson_)
: message(message_),
layer(layer_),
feature_id(feature_id_),
geojson(geojson_) {}
std::string const message;
std::string const layer;
std::int64_t const feature_id;
std::string const geojson;
};
void layer_not_simple(protozero::pbf_reader const& layer_msg,
unsigned x,
unsigned y,
unsigned z,
std::vector<not_simple_feature> & errors)
{
mapnik::vector_tile_impl::tile_datasource_pbf ds(layer_msg, x, y, z);
mapnik::query q(mapnik::box2d<double>(std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max()));
mapnik::layer_descriptor ld = ds.get_descriptor();
for (auto const& item : ld.get_descriptors())
{
q.add_property_name(item.get_name());
}
mapnik::featureset_ptr fs = ds.features(q);
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
while ((feature = fs->next()))
{
if (!mapnik::geometry::is_simple(feature->get_geometry()))
{
// Right now we don't have an obvious way of bypassing our validation
// process in JS, so let's skip testing this line
// LCOV_EXCL_START
errors.emplace_back(ds.get_name(), feature->id());
// LCOV_EXCL_STOP
}
}
}
}
struct visitor_geom_valid
{
std::vector<not_valid_feature> & errors;
mapnik::feature_ptr & feature;
std::string const& layer_name;
bool split_multi_features;
visitor_geom_valid(std::vector<not_valid_feature> & errors_,
mapnik::feature_ptr & feature_,
std::string const& layer_name_,
bool split_multi_features_)
: errors(errors_),
feature(feature_),
layer_name(layer_name_),
split_multi_features(split_multi_features_) {}
void operator() (mapnik::geometry::geometry_empty const&) {}
template <typename T>
void operator() (mapnik::geometry::point<T> const& geom)
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::multi_point<T> const& geom)
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::line_string<T> const& geom)
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::multi_line_string<T> const& geom)
{
if (split_multi_features)
{
for (auto const& ls : geom)
{
std::string message;
if (!mapnik::geometry::is_valid(ls, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(ls));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
else
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::polygon<T> const& geom)
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::multi_polygon<T> const& geom)
{
if (split_multi_features)
{
for (auto const& poly : geom)
{
std::string message;
if (!mapnik::geometry::is_valid(poly, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(poly));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
else
{
std::string message;
if (!mapnik::geometry::is_valid(geom, message))
{
mapnik::feature_impl feature_new(feature->context(),feature->id());
std::string result;
std::string feature_str;
result += "{\"type\":\"FeatureCollection\",\"features\":[";
feature_new.set_data(feature->get_data());
feature_new.set_geometry(mapnik::geometry::geometry<T>(geom));
if (!mapnik::util::to_geojson(feature_str, feature_new))
{
// LCOV_EXCL_START
throw std::runtime_error("Failed to generate GeoJSON geometry");
// LCOV_EXCL_STOP
}
result += feature_str;
result += "]}";
errors.emplace_back(message,
layer_name,
feature->id(),
result);
}
}
}
template <typename T>
void operator() (mapnik::geometry::geometry_collection<T> const& geom)
{
// This should never be able to be reached.
// LCOV_EXCL_START
for (auto const& g : geom)
{
mapnik::util::apply_visitor((*this), g);
}
// LCOV_EXCL_STOP
}
};
void layer_not_valid(protozero::pbf_reader & layer_msg,
unsigned x,
unsigned y,
unsigned z,
std::vector<not_valid_feature> & errors,
bool split_multi_features = false,
bool lat_lon = false,
bool web_merc = false)
{
if (web_merc || lat_lon)
{
mapnik::vector_tile_impl::tile_datasource_pbf ds(layer_msg, x, y, z);
mapnik::query q(mapnik::box2d<double>(std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max(),
std::numeric_limits<double>::max()));
mapnik::layer_descriptor ld = ds.get_descriptor();
for (auto const& item : ld.get_descriptors())
{
q.add_property_name(item.get_name());
}
mapnik::featureset_ptr fs = ds.features(q);
if (fs && mapnik::is_valid(fs))
{
mapnik::feature_ptr feature;
while ((feature = fs->next()))
{
if (lat_lon)
{
mapnik::projection wgs84("+init=epsg:4326",true);
mapnik::projection merc("+init=epsg:3857",true);
mapnik::proj_transform prj_trans(merc,wgs84);
unsigned int n_err = 0;
mapnik::util::apply_visitor(
visitor_geom_valid(errors, feature, ds.get_name(), split_multi_features),
mapnik::geometry::reproject_copy(feature->get_geometry(), prj_trans, n_err));
}
else
{
mapnik::util::apply_visitor(
visitor_geom_valid(errors, feature, ds.get_name(), split_multi_features),
feature->get_geometry());
}
}
}
}
else
{
std::vector<protozero::pbf_reader> layer_features;
std::uint32_t version = 1;
std::string layer_name;
while (layer_msg.next())
{
switch (layer_msg.tag())
{
case mapnik::vector_tile_impl::Layer_Encoding::NAME:
layer_name = layer_msg.get_string();
break;
case mapnik::vector_tile_impl::Layer_Encoding::FEATURES:
layer_features.push_back(layer_msg.get_message());
break;
case mapnik::vector_tile_impl::Layer_Encoding::VERSION:
version = layer_msg.get_uint32();
break;
default:
layer_msg.skip();
break;
}
}
for (auto feature_msg : layer_features)
{
mapnik::vector_tile_impl::GeometryPBF::pbf_itr geom_itr;
bool has_geom = false;
bool has_geom_type = false;
std::int32_t geom_type_enum = 0;
std::uint64_t feature_id = 0;
while (feature_msg.next())
{
switch (feature_msg.tag())
{
case mapnik::vector_tile_impl::Feature_Encoding::ID:
feature_id = feature_msg.get_uint64();
break;
case mapnik::vector_tile_impl::Feature_Encoding::TYPE:
geom_type_enum = feature_msg.get_enum();
has_geom_type = true;
break;
case mapnik::vector_tile_impl::Feature_Encoding::GEOMETRY:
geom_itr = feature_msg.get_packed_uint32();
has_geom = true;
break;
default:
feature_msg.skip();
break;
}
}
if (has_geom && has_geom_type)
{
// Decode the geometry first into an int64_t mapnik geometry
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
mapnik::vector_tile_impl::GeometryPBF geoms(geom_itr);
feature->set_geometry(mapnik::vector_tile_impl::decode_geometry<double>(geoms, geom_type_enum, version, 0.0, 0.0, 1.0, 1.0));
mapnik::util::apply_visitor(
visitor_geom_valid(errors, feature, layer_name, split_multi_features),
feature->get_geometry());
}
}
}
}
void vector_tile_not_simple(VectorTile * v,
std::vector<not_simple_feature> & errors)
{
protozero::pbf_reader tile_msg(v->get_tile()->get_reader());
while (tile_msg.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
protozero::pbf_reader layer_msg(tile_msg.get_message());
layer_not_simple(layer_msg,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z(),
errors);
}
}
v8::Local<v8::Array> make_not_simple_array(std::vector<not_simple_feature> & errors)
{
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> array = Nan::New<v8::Array>(errors.size());
v8::Local<v8::String> layer_key = Nan::New<v8::String>("layer").ToLocalChecked();
v8::Local<v8::String> feature_id_key = Nan::New<v8::String>("featureId").ToLocalChecked();
std::uint32_t idx = 0;
for (auto const& error : errors)
{
// LCOV_EXCL_START
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
obj->Set(layer_key, Nan::New<v8::String>(error.layer).ToLocalChecked());
obj->Set(feature_id_key, Nan::New<v8::Number>(error.feature_id));
array->Set(idx++, obj);
// LCOV_EXCL_STOP
}
return scope.Escape(array);
}
void vector_tile_not_valid(VectorTile * v,
std::vector<not_valid_feature> & errors,
bool split_multi_features = false,
bool lat_lon = false,
bool web_merc = false)
{
protozero::pbf_reader tile_msg(v->get_tile()->get_reader());
while (tile_msg.next(mapnik::vector_tile_impl::Tile_Encoding::LAYERS))
{
protozero::pbf_reader layer_msg(tile_msg.get_message());
layer_not_valid(layer_msg,
v->get_tile()->x(),
v->get_tile()->y(),
v->get_tile()->z(),
errors,
split_multi_features,
lat_lon,
web_merc);
}
}
v8::Local<v8::Array> make_not_valid_array(std::vector<not_valid_feature> & errors)
{
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> array = Nan::New<v8::Array>(errors.size());
v8::Local<v8::String> layer_key = Nan::New<v8::String>("layer").ToLocalChecked();
v8::Local<v8::String> feature_id_key = Nan::New<v8::String>("featureId").ToLocalChecked();
v8::Local<v8::String> message_key = Nan::New<v8::String>("message").ToLocalChecked();
v8::Local<v8::String> geojson_key = Nan::New<v8::String>("geojson").ToLocalChecked();
std::uint32_t idx = 0;
for (auto const& error : errors)
{
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
obj->Set(layer_key, Nan::New<v8::String>(error.layer).ToLocalChecked());
obj->Set(message_key, Nan::New<v8::String>(error.message).ToLocalChecked());
obj->Set(feature_id_key, Nan::New<v8::Number>(error.feature_id));
obj->Set(geojson_key, Nan::New<v8::String>(error.geojson).ToLocalChecked());
array->Set(idx++, obj);
}
return scope.Escape(array);
}
struct not_simple_baton
{
uv_work_t request;
VectorTile* v;
bool error;
std::vector<not_simple_feature> result;
std::string err_msg;
Nan::Persistent<v8::Function> cb;
};
struct not_valid_baton
{
uv_work_t request;
VectorTile* v;
bool error;
bool split_multi_features;
bool lat_lon;
bool web_merc;
std::vector<not_valid_feature> result;
std::string err_msg;
Nan::Persistent<v8::Function> cb;
};
/**
* Count the number of geometries that are not [OGC simple]{@link http://www.iso.org/iso/catalogue_detail.htm?csnumber=40114}
*
* @memberof VectorTile
* @instance
* @name reportGeometrySimplicitySync
* @returns {number} number of features that are not simple
* @example
* var simple = vectorTile.reportGeometrySimplicitySync();
* console.log(simple); // array of non-simple geometries and their layer info
* console.log(simple.length); // number
*/
NAN_METHOD(VectorTile::reportGeometrySimplicitySync)
{
info.GetReturnValue().Set(_reportGeometrySimplicitySync(info));
}
v8::Local<v8::Value> VectorTile::_reportGeometrySimplicitySync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
try
{
std::vector<not_simple_feature> errors;
vector_tile_not_simple(d, errors);
return scope.Escape(make_not_simple_array(errors));
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
Nan::ThrowError(ex.what());
// LCOV_EXCL_STOP
}
// LCOV_EXCL_START
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
/**
* Count the number of geometries that are not [OGC valid]{@link http://postgis.net/docs/using_postgis_dbmanagement.html#OGC_Validity}
*
* @memberof VectorTile
* @instance
* @name reportGeometryValiditySync
* @param {object} [options]
* @param {boolean} [options.split_multi_features=false] - If true does validity checks on multi geometries part by part
* Normally the validity of multipolygons and multilinestrings is done together against
* all the parts of the geometries. Changing this to true checks the validity of multipolygons
* and multilinestrings for each part they contain, rather then as a group.
* @param {boolean} [options.lat_lon=false] - If true results in EPSG:4326
* @param {boolean} [options.web_merc=false] - If true results in EPSG:3857
* @returns {number} number of features that are not valid
* @example
* var valid = vectorTile.reportGeometryValiditySync();
* console.log(valid); // array of invalid geometries and their layer info
* console.log(valid.length); // number
*/
NAN_METHOD(VectorTile::reportGeometryValiditySync)
{
info.GetReturnValue().Set(_reportGeometryValiditySync(info));
}
v8::Local<v8::Value> VectorTile::_reportGeometryValiditySync(Nan::NAN_METHOD_ARGS_TYPE info)
{
Nan::EscapableHandleScope scope;
bool split_multi_features = false;
bool lat_lon = false;
bool web_merc = false;
if (info.Length() >= 1)
{
if (!info[0]->IsObject())
{
Nan::ThrowError("The first argument must be an object");
return scope.Escape(Nan::Undefined());
}
v8::Local<v8::Object> options = info[0]->ToObject();
if (options->Has(Nan::New("split_multi_features").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("split_multi_features").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'split_multi_features' must be a boolean");
return scope.Escape(Nan::Undefined());
}
split_multi_features = param_val->BooleanValue();
}
if (options->Has(Nan::New("lat_lon").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("lat_lon").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'lat_lon' must be a boolean");
return scope.Escape(Nan::Undefined());
}
lat_lon = param_val->BooleanValue();
}
if (options->Has(Nan::New("web_merc").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("web_merc").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'web_merc' must be a boolean");
return scope.Escape(Nan::Undefined());
}
web_merc = param_val->BooleanValue();
}
}
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
try
{
std::vector<not_valid_feature> errors;
vector_tile_not_valid(d, errors, split_multi_features, lat_lon, web_merc);
return scope.Escape(make_not_valid_array(errors));
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
Nan::ThrowError(ex.what());
// LCOV_EXCL_STOP
}
// LCOV_EXCL_START
return scope.Escape(Nan::Undefined());
// LCOV_EXCL_STOP
}
/**
* Count the number of geometries that are not [OGC simple]{@link http://www.iso.org/iso/catalogue_detail.htm?csnumber=40114}
*
* @memberof VectorTile
* @instance
* @name reportGeometrySimplicity
* @param {Function} callback
* @example
* vectorTile.reportGeometrySimplicity(function(err, simple) {
* if (err) throw err;
* console.log(simple); // array of non-simple geometries and their layer info
* console.log(simple.length); // number
* });
*/
NAN_METHOD(VectorTile::reportGeometrySimplicity)
{
if (info.Length() == 0)
{
info.GetReturnValue().Set(_reportGeometrySimplicitySync(info));
return;
}
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!callback->IsFunction())
{
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
not_simple_baton *closure = new not_simple_baton();
closure->request.data = closure;
closure->v = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_ReportGeometrySimplicity, (uv_after_work_cb)EIO_AfterReportGeometrySimplicity);
closure->v->Ref();
return;
}
void VectorTile::EIO_ReportGeometrySimplicity(uv_work_t* req)
{
not_simple_baton *closure = static_cast<not_simple_baton *>(req->data);
try
{
vector_tile_not_simple(closure->v, closure->result);
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
closure->error = true;
closure->err_msg = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::EIO_AfterReportGeometrySimplicity(uv_work_t* req)
{
Nan::HandleScope scope;
not_simple_baton *closure = static_cast<not_simple_baton *>(req->data);
if (closure->error)
{
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->err_msg.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Array> array = make_not_simple_array(closure->result);
v8::Local<v8::Value> argv[2] = { Nan::Null(), array };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->v->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Count the number of geometries that are not [OGC valid]{@link http://postgis.net/docs/using_postgis_dbmanagement.html#OGC_Validity}
*
* @memberof VectorTile
* @instance
* @name reportGeometryValidity
* @param {object} [options]
* @param {boolean} [options.split_multi_features=false] - If true does validity checks on multi geometries part by part
* Normally the validity of multipolygons and multilinestrings is done together against
* all the parts of the geometries. Changing this to true checks the validity of multipolygons
* and multilinestrings for each part they contain, rather then as a group.
* @param {boolean} [options.lat_lon=false] - If true results in EPSG:4326
* @param {boolean} [options.web_merc=false] - If true results in EPSG:3857
* @param {Function} callback
* @example
* vectorTile.reportGeometryValidity(function(err, valid) {
* console.log(valid); // array of invalid geometries and their layer info
* console.log(valid.length); // number
* });
*/
NAN_METHOD(VectorTile::reportGeometryValidity)
{
if (info.Length() == 0 || (info.Length() == 1 && !info[0]->IsFunction()))
{
info.GetReturnValue().Set(_reportGeometryValiditySync(info));
return;
}
bool split_multi_features = false;
bool lat_lon = false;
bool web_merc = false;
if (info.Length() >= 2)
{
if (!info[0]->IsObject())
{
Nan::ThrowError("The first argument must be an object");
return;
}
v8::Local<v8::Object> options = info[0]->ToObject();
if (options->Has(Nan::New("split_multi_features").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("split_multi_features").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'split_multi_features' must be a boolean");
return;
}
split_multi_features = param_val->BooleanValue();
}
if (options->Has(Nan::New("lat_lon").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("lat_lon").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'lat_lon' must be a boolean");
return;
}
lat_lon = param_val->BooleanValue();
}
if (options->Has(Nan::New("web_merc").ToLocalChecked()))
{
v8::Local<v8::Value> param_val = options->Get(Nan::New("web_merc").ToLocalChecked());
if (!param_val->IsBoolean())
{
Nan::ThrowError("option 'web_merc' must be a boolean");
return;
}
web_merc = param_val->BooleanValue();
}
}
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length() - 1];
if (!callback->IsFunction())
{
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
not_valid_baton *closure = new not_valid_baton();
closure->request.data = closure;
closure->v = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
closure->error = false;
closure->split_multi_features = split_multi_features;
closure->lat_lon = lat_lon;
closure->web_merc = web_merc;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_ReportGeometryValidity, (uv_after_work_cb)EIO_AfterReportGeometryValidity);
closure->v->Ref();
return;
}
void VectorTile::EIO_ReportGeometryValidity(uv_work_t* req)
{
not_valid_baton *closure = static_cast<not_valid_baton *>(req->data);
try
{
vector_tile_not_valid(closure->v, closure->result, closure->split_multi_features, closure->lat_lon, closure->web_merc);
}
catch (std::exception const& ex)
{
// LCOV_EXCL_START
closure->error = true;
closure->err_msg = ex.what();
// LCOV_EXCL_STOP
}
}
void VectorTile::EIO_AfterReportGeometryValidity(uv_work_t* req)
{
Nan::HandleScope scope;
not_valid_baton *closure = static_cast<not_valid_baton *>(req->data);
if (closure->error)
{
// LCOV_EXCL_START
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->err_msg.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
// LCOV_EXCL_STOP
}
else
{
v8::Local<v8::Array> array = make_not_valid_array(closure->result);
v8::Local<v8::Value> argv[2] = { Nan::Null(), array };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->v->Unref();
closure->cb.Reset();
delete closure;
}
#endif // BOOST_VERSION >= 1.58
NAN_GETTER(VectorTile::get_tile_x)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(d->tile_->x()));
}
NAN_GETTER(VectorTile::get_tile_y)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(d->tile_->y()));
}
NAN_GETTER(VectorTile::get_tile_z)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(d->tile_->z()));
}
NAN_GETTER(VectorTile::get_tile_size)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(d->tile_->tile_size()));
}
NAN_GETTER(VectorTile::get_buffer_size)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
info.GetReturnValue().Set(Nan::New<v8::Number>(d->tile_->buffer_size()));
}
NAN_SETTER(VectorTile::set_tile_x)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!value->IsNumber())
{
Nan::ThrowError("Must provide a number");
}
else
{
int val = value->IntegerValue();
if (val < 0)
{
Nan::ThrowError("tile x coordinate must be greater then or equal to zero");
return;
}
d->tile_->x(val);
}
}
NAN_SETTER(VectorTile::set_tile_y)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!value->IsNumber())
{
Nan::ThrowError("Must provide a number");
}
else
{
int val = value->IntegerValue();
if (val < 0)
{
Nan::ThrowError("tile y coordinate must be greater then or equal to zero");
return;
}
d->tile_->y(val);
}
}
NAN_SETTER(VectorTile::set_tile_z)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!value->IsNumber())
{
Nan::ThrowError("Must provide a number");
}
else
{
int val = value->IntegerValue();
if (val < 0)
{
Nan::ThrowError("tile z coordinate must be greater then or equal to zero");
return;
}
d->tile_->z(val);
}
}
NAN_SETTER(VectorTile::set_tile_size)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!value->IsNumber())
{
Nan::ThrowError("Must provide a number");
}
else
{
int val = value->IntegerValue();
if (val <= 0)
{
Nan::ThrowError("tile size must be greater then zero");
return;
}
d->tile_->tile_size(val);
}
}
NAN_SETTER(VectorTile::set_buffer_size)
{
VectorTile* d = Nan::ObjectWrap::Unwrap<VectorTile>(info.Holder());
if (!value->IsNumber())
{
Nan::ThrowError("Must provide a number");
}
else
{
int val = value->IntegerValue();
if (static_cast<int>(d->tile_size()) + (2 * val) <= 0)
{
Nan::ThrowError("too large of a negative buffer for tilesize");
return;
}
d->tile_->buffer_size(val);
}
}
typedef struct {
uv_work_t request;
const char *data;
size_t dataLength;
v8::Local<v8::Object> obj;
bool error;
std::string error_str;
Nan::Persistent<v8::Object> buffer;
Nan::Persistent<v8::Function> cb;
} vector_tile_info_baton_t;
/**
* Return an object containing information about a vector tile buffer. Useful for
* debugging `.mvt` files with errors.
*
* @name info
* @param {Buffer} buffer - vector tile buffer
* @returns {Object} json object with information about the vector tile buffer
* @static
* @memberof VectorTile
* @instance
* @example
* var buffer = fs.readFileSync('./path/to/tile.mvt');
* var info = mapnik.VectorTile.info(buffer);
* console.log(info);
* // { layers:
* // [ { name: 'world',
* // features: 1,
* // point_features: 0,
* // linestring_features: 0,
* // polygon_features: 1,
* // unknown_features: 0,
* // raster_features: 0,
* // version: 2 },
* // { name: 'world2',
* // features: 1,
* // point_features: 0,
* // linestring_features: 0,
* // polygon_features: 1,
* // unknown_features: 0,
* // raster_features: 0,
* // version: 2 } ],
* // errors: false }
*/
NAN_METHOD(VectorTile::info)
{
if (info.Length() < 1 || !info[0]->IsObject())
{
Nan::ThrowTypeError("must provide a buffer argument");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj))
{
Nan::ThrowTypeError("first argument is invalid, must be a Buffer");
return;
}
v8::Local<v8::Object> out = Nan::New<v8::Object>();
v8::Local<v8::Array> layers = Nan::New<v8::Array>();
std::set<mapnik::vector_tile_impl::validity_error> errors;
bool has_errors = false;
std::size_t layers_size = 0;
bool first_layer = true;
std::set<std::string> layer_names_set;
std::uint32_t version = 1;
protozero::pbf_reader tile_msg;
std::string decompressed;
try
{
if (mapnik::vector_tile_impl::is_gzip_compressed(node::Buffer::Data(obj),node::Buffer::Length(obj)) ||
mapnik::vector_tile_impl::is_zlib_compressed(node::Buffer::Data(obj),node::Buffer::Length(obj)))
{
mapnik::vector_tile_impl::zlib_decompress(node::Buffer::Data(obj), node::Buffer::Length(obj), decompressed);
tile_msg = protozero::pbf_reader(decompressed);
}
else
{
tile_msg = protozero::pbf_reader(node::Buffer::Data(obj),node::Buffer::Length(obj));
}
while (tile_msg.next())
{
switch (tile_msg.tag())
{
case mapnik::vector_tile_impl::Tile_Encoding::LAYERS:
{
v8::Local<v8::Object> layer_obj = Nan::New<v8::Object>();
std::uint64_t point_feature_count = 0;
std::uint64_t line_feature_count = 0;
std::uint64_t polygon_feature_count = 0;
std::uint64_t unknown_feature_count = 0;
std::uint64_t raster_feature_count = 0;
auto layer_view = tile_msg.get_view();
protozero::pbf_reader layer_props_msg(layer_view);
auto layer_info = mapnik::vector_tile_impl::get_layer_name_and_version(layer_props_msg);
std::string const& layer_name = layer_info.first;
std::uint32_t layer_version = layer_info.second;
std::set<mapnik::vector_tile_impl::validity_error> layer_errors;
if (version > 2 || version < 1)
{
layer_errors.insert(mapnik::vector_tile_impl::LAYER_HAS_UNSUPPORTED_VERSION);
}
protozero::pbf_reader layer_msg(layer_view);
mapnik::vector_tile_impl::layer_is_valid(layer_msg,
layer_errors,
point_feature_count,
line_feature_count,
polygon_feature_count,
unknown_feature_count,
raster_feature_count);
std::uint64_t feature_count = point_feature_count +
line_feature_count +
polygon_feature_count +
unknown_feature_count +
raster_feature_count;
if (!layer_name.empty())
{
auto p = layer_names_set.insert(layer_name);
if (!p.second)
{
errors.insert(mapnik::vector_tile_impl::TILE_REPEATED_LAYER_NAMES);
}
layer_obj->Set(Nan::New("name").ToLocalChecked(), Nan::New<v8::String>(layer_name).ToLocalChecked());
}
layer_obj->Set(Nan::New("features").ToLocalChecked(), Nan::New<v8::Number>(feature_count));
layer_obj->Set(Nan::New("point_features").ToLocalChecked(), Nan::New<v8::Number>(point_feature_count));
layer_obj->Set(Nan::New("linestring_features").ToLocalChecked(), Nan::New<v8::Number>(line_feature_count));
layer_obj->Set(Nan::New("polygon_features").ToLocalChecked(), Nan::New<v8::Number>(polygon_feature_count));
layer_obj->Set(Nan::New("unknown_features").ToLocalChecked(), Nan::New<v8::Number>(unknown_feature_count));
layer_obj->Set(Nan::New("raster_features").ToLocalChecked(), Nan::New<v8::Number>(raster_feature_count));
layer_obj->Set(Nan::New("version").ToLocalChecked(), Nan::New<v8::Number>(layer_version));
if (!layer_errors.empty())
{
has_errors = true;
v8::Local<v8::Array> err_arr = Nan::New<v8::Array>();
std::size_t i = 0;
for (auto const& e : layer_errors)
{
err_arr->Set(i++, Nan::New<v8::String>(mapnik::vector_tile_impl::validity_error_to_string(e)).ToLocalChecked());
}
layer_obj->Set(Nan::New("errors").ToLocalChecked(), err_arr);
}
if (first_layer)
{
version = layer_version;
}
else
{
if (version != layer_version)
{
errors.insert(mapnik::vector_tile_impl::TILE_HAS_DIFFERENT_VERSIONS);
}
}
first_layer = false;
layers->Set(layers_size++, layer_obj);
}
break;
default:
errors.insert(mapnik::vector_tile_impl::TILE_HAS_UNKNOWN_TAG);
tile_msg.skip();
break;
}
}
}
catch (...)
{
errors.insert(mapnik::vector_tile_impl::INVALID_PBF_BUFFER);
}
out->Set(Nan::New("layers").ToLocalChecked(), layers);
has_errors = has_errors || !errors.empty();
out->Set(Nan::New("errors").ToLocalChecked(), Nan::New<v8::Boolean>(has_errors));
if (!errors.empty())
{
v8::Local<v8::Array> err_arr = Nan::New<v8::Array>();
std::size_t i = 0;
for (auto const& e : errors)
{
err_arr->Set(i++, Nan::New<v8::String>(mapnik::vector_tile_impl::validity_error_to_string(e)).ToLocalChecked());
}
out->Set(Nan::New("tile_errors").ToLocalChecked(), err_arr);
}
info.GetReturnValue().Set(out);
return;
}
|
// Copyright 2020 John Manferdelli, All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// or in the the file LICENSE-2.0.txt in the top level sourcedirectory
// 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
// File: nist_hash_rng.cc
#include <stdio.h>
#include "crypto_support.h"
#include "probability_support.h"
#include "entropy_collection.h"
#include "hash_drng.h"
#include "nist_hash_rng.h"
nist_hash_rng::nist_hash_rng() {
}
nist_hash_rng::~nist_hash_rng() {
}
bool nist_hash_rng::initialize(int n_sample, double entropy_per_sample,
double required_entropy_to_extract, int reseed_interval) {
n_sample_ = n_sample;
h_estimate_ = entropy_per_sample;
required_entropy_to_extract_= required_entropy_to_extract;
reseed_interval_ = reseed_interval;
return true;
}
bool nist_hash_rng::collect_samples(int num_samples, byte* samples) {
return raw_entropy_.add_samples(num_samples, samples);
}
bool nist_hash_rng::initialize_drng() {
int size_init_data = raw_entropy_.pool_size_ + sha256::DIGESTBYTESIZE;
byte data[size_init_data];
double pool_entropy = 0;
memset(data, 0, size_init_data);
if (!raw_entropy_.empty_pool(&size_init_data, data, &pool_entropy)) {
printf("Can't empty entropy pool\n");
return false;
}
return drng_.init(0, nullptr, 0, nullptr, size_init_data, data,
pool_entropy);
return true;
}
int nist_hash_rng::extract_random_number(int num_bits, byte* rn) {
return drng_.generate_random_bits(num_bits, rn, 0, nullptr);
}
bool nist_hash_rng::reseed() {
return true;
}
bool nist_hash_rng::health_test(int num_samples, byte* samples) {
return true;
}
bool nist_hash_rng::restart_test(int num_samples, byte* samples) {
return true;
}
|
; A211715: Number of (n+1) X (n+1) -11..11 symmetric matrices with every 2 X 2 subblock having sum zero and two or four distinct values.
; 34,58,106,202,394,778,1546,3082,6154,12298,24586,49162,98314,196618,393226,786442,1572874,3145738,6291466,12582922,25165834,50331658,100663306,201326602,402653194,805306378,1610612746,3221225482,6442450954,12884901898,25769803786,51539607562,103079215114,206158430218,412316860426,824633720842,1649267441674,3298534883338,6597069766666,13194139533322,26388279066634,52776558133258,105553116266506,211106232533002,422212465065994,844424930131978,1688849860263946,3377699720527882,6755399441055754
mov $1,2
pow $1,$0
sub $1,1
mul $1,24
add $1,34
|
.file 1 ""
.section .mdebug.abi32
.previous
.nan legacy
.module fp=32
.module nooddspreg
.abicalls
.text
.align 2
.globl main
.set nomips16
.set nomicromips
.ent main
.type main, @function
main:
.frame $fp,32,$31 # vars= 16, regs= 1/0, args= 0, gp= 8
.mask 0x40000000,-4
.fmask 0x00000000,0
.set noreorder
.set nomacro
addiu $sp,$sp,-32
sw $fp,28($sp)
move $fp,$sp
sw $0,12($fp)
b $L2
movz $31,$31,$0
nop
$L5:
sw $0,16($fp)
b $L3
nop
$L4:
lw $2,8($fp)
nop
addiu $2,$2,1
sw $2,8($fp)
lw $2,16($fp)
nop
addiu $2,$2,1
sw $2,16($fp)
$L3:
lw $2,16($fp)
nop
slt $2,$2,4
bne $2,$0,$L4
nop
lw $2,12($fp)
nop
addiu $2,$2,1
sw $2,12($fp)
$L2:
lw $2,12($fp)
nop
slt $2,$2,1000
bne $2,$0,$L5
nop
lw $2,8($fp)
move $sp,$fp
lw $fp,28($sp)
addiu $sp,$sp,32
j $31
nop
.set macro
.set reorder
.end main
.size main, .-main
.ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609" |
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=87176fc60914cbca9c6a20998a033c24
REG_FIDDLE(Rect_makeOutset, 256, 256, true, 0) {
void draw(SkCanvas* canvas) {
SkRect rect = { 10, 50, 20, 60 };
SkDebugf("rect: %g, %g, %g, %g isEmpty: %s\n", rect.left(), rect.top(), rect.right(),
rect.bottom(), rect.isEmpty() ? "true" : "false");
rect = rect.makeOutset(15, 32);
SkDebugf("rect: %g, %g, %g, %g isEmpty: %s\n", rect.left(), rect.top(), rect.right(),
rect.bottom(), rect.isEmpty() ? "true" : "false");
}
} // END FIDDLE
|
#include "ML_modules.hpp"
#include "dsp/digital.hpp"
#include <cmath>
#include <cstdlib>
struct ShiftRegister2 : Module {
enum ParamIds {
NUM_STEPS_PARAM,
PROB1_PARAM,
PROB2_PARAM,
MIX1_PARAM,
AUX_OFFSET_PARAM,
NUM_PARAMS
};
enum InputIds {
IN1_INPUT,
IN2_INPUT,
TRIGGER_INPUT,
NUM_STEPS_INPUT,
PROB1_INPUT,
PROB2_INPUT,
MIX1_INPUT,
NUM_INPUTS
};
enum OutputIds {
OUT_OUTPUT,
AUX_OUTPUT,
NUM_OUTPUTS
};
ShiftRegister2() : Module( NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS ) {};
void step() override;
int numSteps;
float values[32] = {};
SchmittTrigger trigTrigger;
inline float randf() {return rand()/(RAND_MAX-1.0);}
#ifdef v_dev
void reset() override {
#endif
#ifdef v040
void initialize() override {
#endif
};
};
void ShiftRegister2::step() {
numSteps = roundf(clampf(params[NUM_STEPS_PARAM].value * clampf(inputs[NUM_STEPS_INPUT].normalize(5.0),0.0,5.0)/5.0,1.0,16.0));
if( inputs[TRIGGER_INPUT].active ) {
if( trigTrigger.process(inputs[TRIGGER_INPUT].value) ) {
float new_in1 = inputs[IN1_INPUT].normalize( randf()*10.0-5.0 );
float new_in2 = inputs[IN2_INPUT].normalize( new_in1 + 1.0 );
for(int i=32; i>0; i--) values[i] = values[i-1];
float p1 = params[PROB1_PARAM].value + clampf(inputs[PROB1_INPUT].normalize(0.0),-10.0,10.0)/10.0;
float p2 = params[PROB2_PARAM].value + clampf(inputs[PROB2_INPUT].normalize(0.0),-10.0,10.0)/10.0;
bool replace = ( randf() < p1 );
bool rnd2 = ( randf() < p2 );
float a = params[MIX1_PARAM].value + clampf(inputs[MIX1_INPUT].normalize(0.0),-10.0,10.0)/10.0;
if(replace) {
values[0] = a* (rnd2?new_in2:new_in1) + (1-a)*values[numSteps];
} else {
values[0] = values[numSteps];
};
};
};
outputs[OUT_OUTPUT].value = values[0];
int offset = roundf(params[AUX_OFFSET_PARAM].value);
outputs[AUX_OUTPUT].value = values[offset];
};
struct IntDisplayWidget : TransparentWidget {
int *value;
std::shared_ptr<Font> font;
IntDisplayWidget() {
font = Font::load(assetPlugin(plugin, "res/Segment7Standard.ttf"));
};
void draw(NVGcontext *vg) {
// Background
NVGcolor backgroundColor = nvgRGB(0x44, 0x44, 0x44);
NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10);
nvgBeginPath(vg);
nvgRoundedRect(vg, 0.0, 0.0, box.size.x, box.size.y, 4.0);
nvgFillColor(vg, backgroundColor);
nvgFill(vg);
nvgStrokeWidth(vg, 1.0);
nvgStrokeColor(vg, borderColor);
nvgStroke(vg);
nvgFontSize(vg, 18);
nvgFontFaceId(vg, font->handle);
nvgTextLetterSpacing(vg, 2.5);
// std::string to_display = std::to_string( (unsigned) *value);
char displayStr[3];
// while(to_display.length()<1) to_display = ' ' + to_display;
sprintf(displayStr, "%2u", (unsigned) *value);
Vec textPos = Vec(6.0f, 17.0f);
NVGcolor textColor = nvgRGB(0xdf, 0xd2, 0x2c);
nvgFillColor(vg, nvgTransRGBA(textColor, 16));
nvgText(vg, textPos.x, textPos.y, "~~", NULL);
textColor = nvgRGB(0xda, 0xe9, 0x29);
nvgFillColor(vg, nvgTransRGBA(textColor, 16));
nvgText(vg, textPos.x, textPos.y, "\\\\", NULL);
textColor = nvgRGB(0xf0, 0x00, 0x00);
nvgFillColor(vg, textColor);
nvgText(vg, textPos.x, textPos.y, displayStr, NULL);
}
};
ShiftRegister2Widget::ShiftRegister2Widget() {
ShiftRegister2 *module = new ShiftRegister2();
setModule(module);
box.size = Vec(15*8, 380);
{
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin,"res/ShiftReg2.svg")));
addChild(panel);
}
addChild(createScrew<ScrewSilver>(Vec(15, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0)));
addChild(createScrew<ScrewSilver>(Vec(15, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365)));
const float column1 = 20, column2 = 75;
IntDisplayWidget *display = new IntDisplayWidget();
display->box.pos = Vec(65,46);
display->box.size = Vec(40, 20);
display->value = &module->numSteps;
addChild(display);
addInput(createInput<PJ301MPort>(Vec(column1, 44), module, ShiftRegister2::TRIGGER_INPUT));
addInput(createInput<PJ301MPort>(Vec(column1, 96), module, ShiftRegister2::NUM_STEPS_INPUT));
addParam(createParam<RedMLKnob>(Vec(65, 86), module, ShiftRegister2::NUM_STEPS_PARAM, 1.0, 16.0, 8.0));
addInput(createInput<PJ301MPort>(Vec(column1+8, 135), module, ShiftRegister2::IN1_INPUT));
addInput(createInput<PJ301MPort>(Vec(column2-8, 135), module, ShiftRegister2::IN2_INPUT));
addInput(createInput<PJ301MPort>(Vec(column1+3, 183), module, ShiftRegister2::PROB1_INPUT));
addParam(createParam<SmallMLKnob>(Vec(column2-1, 176), module, ShiftRegister2::PROB1_PARAM, 0.0, 1.0, 0.0));
addInput(createInput<PJ301MPort>(Vec(column1+3, 229), module, ShiftRegister2::PROB2_INPUT));
addParam(createParam<SmallMLKnob>(Vec(column2-1, 222), module, ShiftRegister2::PROB2_PARAM, 0.0, 1.0, 0.0));
addInput(createInput<PJ301MPort>(Vec(column1+3, 275), module, ShiftRegister2::MIX1_INPUT));
addParam(createParam<SmallMLKnob>(Vec(column2-1, 268), module, ShiftRegister2::MIX1_PARAM, 0.0, 1.0, 1.0));
addParam(createParam<Trimpot>(Vec(56, 318), module, ShiftRegister2::AUX_OFFSET_PARAM, 1.0, 16.0, 1.0));
addOutput(createOutput<PJ301MPort>(Vec(column1-2, 328 ), module, ShiftRegister2::OUT_OUTPUT));
addOutput(createOutput<PJ301MPort>(Vec(column2+2, 328 ), module, ShiftRegister2::AUX_OUTPUT));
}
|
// Copyright (c) 2019-2020 The BITCHAIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/bitchain/dashboardwidget.h"
#include "qt/bitchain/forms/ui_dashboardwidget.h"
#include "qt/bitchain/sendconfirmdialog.h"
#include "qt/bitchain/txrow.h"
#include "qt/bitchain/qtutils.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "clientmodel.h"
#include "optionsmodel.h"
#include "utiltime.h"
#include <QPainter>
#include <QModelIndex>
#include <QList>
#include <QGraphicsLayout>
#define DECORATION_SIZE 65
#define NUM_ITEMS 3
#define SHOW_EMPTY_CHART_VIEW_THRESHOLD 4000
#define REQUEST_LOAD_TASK 1
#define CHART_LOAD_MIN_TIME_INTERVAL 15
DashboardWidget::DashboardWidget(BITCHAINGUI* parent) :
PWidget(parent),
ui(new Ui::DashboardWidget)
{
ui->setupUi(this);
txHolder = new TxViewHolder(isLightTheme());
txViewDelegate = new FurAbstractListItemDelegate(
DECORATION_SIZE,
txHolder,
this
);
this->setStyleSheet(parent->styleSheet());
this->setContentsMargins(0,0,0,0);
// Containers
setCssProperty({this, ui->left}, "container");
ui->left->setContentsMargins(0,0,0,0);
setCssProperty(ui->right, "container-right");
ui->right->setContentsMargins(20,20,20,0);
// Title
ui->labelTitle2->setText(tr("Staking Rewards"));
setCssTitleScreen(ui->labelTitle);
setCssTitleScreen(ui->labelTitle2);
/* Subtitle */
ui->labelSubtitle->setText(tr("You can view your account's history"));
setCssSubtitleScreen(ui->labelSubtitle);
// Staking Information
ui->labelMessage->setText(tr("Amount of XBIT and zXBIT staked."));
setCssSubtitleScreen(ui->labelMessage);
setCssProperty(ui->labelSquareXBIT, "square-chart-xbit");
setCssProperty(ui->labelSquarezXBIT, "square-chart-zxbit");
setCssProperty(ui->labelXBIT, "text-chart-xbit");
setCssProperty(ui->labelZxbit, "text-chart-zxbit");
// Staking Amount
QFont fontBold;
fontBold.setWeight(QFont::Bold);
setCssProperty(ui->labelChart, "legend-chart");
ui->labelAmountZxbit->setText("0 zXBIT");
ui->labelAmountXBIT->setText("0 XBIT");
setCssProperty(ui->labelAmountXBIT, "text-stake-xbit-disable");
setCssProperty(ui->labelAmountZxbit, "text-stake-zxbit-disable");
setCssProperty({ui->pushButtonAll, ui->pushButtonMonth, ui->pushButtonYear}, "btn-check-time");
setCssProperty({ui->comboBoxMonths, ui->comboBoxYears}, "btn-combo-chart-selected");
ui->comboBoxMonths->setView(new QListView());
ui->comboBoxMonths->setStyleSheet("selection-background-color:transparent; selection-color:transparent;");
ui->comboBoxYears->setView(new QListView());
ui->comboBoxYears->setStyleSheet("selection-background-color:transparent; selection-color:transparent;");
ui->pushButtonYear->setChecked(true);
setCssProperty(ui->pushButtonChartArrow, "btn-chart-arrow");
setCssProperty(ui->pushButtonChartRight, "btn-chart-arrow-right");
connect(ui->comboBoxYears, SIGNAL(currentIndexChanged(const QString&)), this,SLOT(onChartYearChanged(const QString&)));
// Sort Transactions
SortEdit* lineEdit = new SortEdit(ui->comboBoxSort);
initComboBox(ui->comboBoxSort, lineEdit);
connect(lineEdit, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSort->showPopup();});
ui->comboBoxSort->addItem("Date desc", SortTx::DATE_DESC);
ui->comboBoxSort->addItem("Date asc", SortTx::DATE_ASC);
ui->comboBoxSort->addItem("Amount desc", SortTx::AMOUNT_ASC);
ui->comboBoxSort->addItem("Amount asc", SortTx::AMOUNT_DESC);
connect(ui->comboBoxSort, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(onSortChanged(const QString&)));
// Sort type
SortEdit* lineEditType = new SortEdit(ui->comboBoxSortType);
initComboBox(ui->comboBoxSortType, lineEditType);
connect(lineEditType, &SortEdit::Mouse_Pressed, [this](){ui->comboBoxSortType->showPopup();});
QSettings settings;
ui->comboBoxSortType->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
ui->comboBoxSortType->addItem(tr("Received"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) | TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
ui->comboBoxSortType->addItem(tr("Sent"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) | TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
ui->comboBoxSortType->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
ui->comboBoxSortType->addItem(tr("Minted"), TransactionFilterProxy::TYPE(TransactionRecord::StakeMint));
ui->comboBoxSortType->addItem(tr("MN reward"), TransactionFilterProxy::TYPE(TransactionRecord::MNReward));
ui->comboBoxSortType->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
ui->comboBoxSortType->addItem(tr("Cold stakes"), TransactionFilterProxy::TYPE(TransactionRecord::StakeDelegated));
ui->comboBoxSortType->addItem(tr("Hot stakes"), TransactionFilterProxy::TYPE(TransactionRecord::StakeHot));
ui->comboBoxSortType->addItem(tr("Delegated"), TransactionFilterProxy::TYPE(TransactionRecord::P2CSDelegationSent) | TransactionFilterProxy::TYPE(TransactionRecord::P2CSDelegationSentOwner));
ui->comboBoxSortType->addItem(tr("Delegations"), TransactionFilterProxy::TYPE(TransactionRecord::P2CSDelegation));
ui->comboBoxSortType->setCurrentIndex(0);
connect(ui->comboBoxSortType, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(onSortTypeChanged(const QString&)));
// Transactions
setCssProperty(ui->listTransactions, "container");
ui->listTransactions->setItemDelegate(txViewDelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->listTransactions->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->listTransactions->setLayoutMode(QListView::LayoutMode::Batched);
ui->listTransactions->setBatchSize(50);
ui->listTransactions->setUniformItemSizes(true);
// Sync Warning
ui->layoutWarning->setVisible(true);
ui->lblWarning->setText(tr("Please wait until the wallet is fully synced to see your correct balance"));
setCssProperty(ui->lblWarning, "text-warning");
setCssProperty(ui->imgWarning, "ic-warning");
//Empty List
ui->emptyContainer->setVisible(false);
setCssProperty(ui->pushImgEmpty, "img-empty-transactions");
ui->labelEmpty->setText(tr("No transactions yet"));
setCssProperty(ui->labelEmpty, "text-empty");
setCssProperty(ui->chartContainer, "container-chart");
setCssProperty(ui->pushImgEmptyChart, "img-empty-staking-on");
ui->btnHowTo->setText(tr("How to get XBIT or zXBIT"));
setCssBtnSecondary(ui->btnHowTo);
setCssProperty(ui->labelEmptyChart, "text-empty");
ui->labelMessageEmpty->setText(tr("You can verify the staking activity in the status bar at the top right of the wallet.\nIt will start automatically as soon as the wallet has enough confirmations on any unspent balances, and the wallet has synced."));
setCssSubtitleScreen(ui->labelMessageEmpty);
// Chart State
ui->layoutChart->setVisible(false);
ui->emptyContainerChart->setVisible(true);
setShadow(ui->layoutShadow);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
if (window)
connect(window, SIGNAL(windowResizeEvent(QResizeEvent*)), this, SLOT(windowResizeEvent(QResizeEvent*)));
bool hasCharts = false;
#ifdef USE_QTCHARTS
hasCharts = true;
isLoading = false;
setChartShow(YEAR);
connect(ui->pushButtonYear, &QPushButton::clicked, [this](){setChartShow(YEAR);});
connect(ui->pushButtonMonth, &QPushButton::clicked, [this](){setChartShow(MONTH);});
connect(ui->pushButtonAll, &QPushButton::clicked, [this](){setChartShow(ALL);});
#endif
if (hasCharts) {
ui->labelEmptyChart->setText(tr("You have no staking rewards"));
} else {
ui->labelEmptyChart->setText(tr("No charts library"));
}
}
void DashboardWidget::handleTransactionClicked(const QModelIndex &index){
ui->listTransactions->setCurrentIndex(index);
QModelIndex rIndex = filter->mapToSource(index);
window->showHide(true);
TxDetailDialog *dialog = new TxDetailDialog(window, false);
dialog->setData(walletModel, rIndex);
openDialogWithOpaqueBackgroundY(dialog, window, 3, 17);
// Back to regular status
ui->listTransactions->scrollTo(index);
ui->listTransactions->clearSelection();
ui->listTransactions->setFocus();
dialog->deleteLater();
}
void DashboardWidget::loadWalletModel(){
if (walletModel && walletModel->getOptionsModel()) {
txModel = walletModel->getTransactionTableModel();
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setDynamicSortFilter(true);
filter->setSortCaseSensitivity(Qt::CaseInsensitive);
filter->setFilterCaseSensitivity(Qt::CaseInsensitive);
filter->setSortRole(Qt::EditRole);
filter->setSourceModel(txModel);
filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);
txHolder->setFilter(filter);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
if(txModel->size() == 0){
ui->emptyContainer->setVisible(true);
ui->listTransactions->setVisible(false);
ui->comboBoxSortType->setVisible(false);
ui->comboBoxSort->setVisible(false);
}
connect(ui->pushImgEmpty, SIGNAL(clicked()), window, SLOT(openFAQ()));
connect(ui->btnHowTo, SIGNAL(clicked()), window, SLOT(openFAQ()));
connect(txModel, &TransactionTableModel::txArrived, this, &DashboardWidget::onTxArrived);
// Notification pop-up for new transaction
connect(txModel, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SLOT(processNewTransaction(QModelIndex, int, int)));
#ifdef USE_QTCHARTS
// chart filter
stakesFilter = new TransactionFilterProxy();
stakesFilter->setDynamicSortFilter(true);
stakesFilter->setSortCaseSensitivity(Qt::CaseInsensitive);
stakesFilter->setFilterCaseSensitivity(Qt::CaseInsensitive);
stakesFilter->setSortRole(Qt::EditRole);
stakesFilter->setOnlyStakes(true);
stakesFilter->setSourceModel(txModel);
stakesFilter->sort(TransactionTableModel::Date, Qt::AscendingOrder);
hasStakes = stakesFilter->rowCount() > 0;
loadChart();
#endif
}
// update the display unit, to not use the default ("XBIT")
updateDisplayUnit();
}
void DashboardWidget::onTxArrived(const QString& hash, const bool& isCoinStake, const bool& isCSAnyType) {
showList();
#ifdef USE_QTCHARTS
if (isCoinStake) {
// Update value if this is our first stake
if (!hasStakes)
hasStakes = stakesFilter->rowCount() > 0;
tryChartRefresh();
}
#endif
}
void DashboardWidget::showList(){
if (filter->rowCount() == 0){
ui->emptyContainer->setVisible(true);
ui->listTransactions->setVisible(false);
ui->comboBoxSortType->setVisible(false);
ui->comboBoxSort->setVisible(false);
} else {
ui->emptyContainer->setVisible(false);
ui->listTransactions->setVisible(true);
ui->comboBoxSortType->setVisible(true);
ui->comboBoxSort->setVisible(true);
}
}
void DashboardWidget::updateDisplayUnit() {
if (walletModel && walletModel->getOptionsModel()) {
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
txHolder->setDisplayUnit(nDisplayUnit);
ui->listTransactions->update();
}
}
void DashboardWidget::onSortChanged(const QString& value){
if (!filter) return;
int columnIndex = 0;
Qt::SortOrder order = Qt::DescendingOrder;
if(!value.isNull()) {
switch (ui->comboBoxSort->itemData(ui->comboBoxSort->currentIndex()).toInt()) {
case SortTx::DATE_ASC:{
columnIndex = TransactionTableModel::Date;
order = Qt::AscendingOrder;
break;
}
case SortTx::DATE_DESC:{
columnIndex = TransactionTableModel::Date;
break;
}
case SortTx::AMOUNT_ASC:{
columnIndex = TransactionTableModel::Amount;
order = Qt::AscendingOrder;
break;
}
case SortTx::AMOUNT_DESC:{
columnIndex = TransactionTableModel::Amount;
break;
}
}
}
filter->sort(columnIndex, order);
ui->listTransactions->update();
}
void DashboardWidget::onSortTypeChanged(const QString& value){
if (!filter) return;
int filterByType = ui->comboBoxSortType->itemData(ui->comboBoxSortType->currentIndex()).toInt();
filter->setTypeFilter(filterByType);
ui->listTransactions->update();
if (filter->rowCount() == 0){
ui->emptyContainer->setVisible(true);
ui->listTransactions->setVisible(false);
} else {
showList();
}
// Store settings
QSettings settings;
settings.setValue("transactionType", filterByType);
}
void DashboardWidget::walletSynced(bool sync){
if (this->isSync != sync) {
this->isSync = sync;
ui->layoutWarning->setVisible(!this->isSync);
#ifdef USE_QTCHARTS
tryChartRefresh();
#endif
}
}
void DashboardWidget::changeTheme(bool isLightTheme, QString& theme){
static_cast<TxViewHolder*>(this->txViewDelegate->getRowFactory())->isLightTheme = isLightTheme;
#ifdef USE_QTCHARTS
if (chart) this->changeChartColors();
#endif
}
#ifdef USE_QTCHARTS
void DashboardWidget::tryChartRefresh() {
if (hasStakes) {
// First check that everything was loaded properly.
if (!chart) {
loadChart();
} else {
// Check for min update time to not reload the UI so often if the node is syncing.
int64_t now = GetTime();
if (lastRefreshTime + CHART_LOAD_MIN_TIME_INTERVAL < now) {
lastRefreshTime = now;
refreshChart();
}
}
}
}
void DashboardWidget::setChartShow(ChartShowType type) {
this->chartShow = type;
if (chartShow == MONTH) {
ui->containerChartArrow->setVisible(true);
} else {
ui->containerChartArrow->setVisible(false);
}
if (isChartInitialized) refreshChart();
}
const QStringList monthsNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
void DashboardWidget::loadChart(){
if (hasStakes) {
if (!chart) {
showHideEmptyChart(false, false);
initChart();
QDate currentDate = QDate::currentDate();
monthFilter = currentDate.month();
yearFilter = currentDate.year();
for (int i = 1; i < 13; ++i) ui->comboBoxMonths->addItem(QString(monthsNames[i-1]), QVariant(i));
ui->comboBoxMonths->setCurrentIndex(monthFilter - 1);
connect(ui->comboBoxMonths, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(onChartMonthChanged(const QString&)));
connect(ui->pushButtonChartArrow, &QPushButton::clicked, [this](){ onChartArrowClicked(true); });
connect(ui->pushButtonChartRight, &QPushButton::clicked, [this](){ onChartArrowClicked(false); });
}
refreshChart();
changeChartColors();
} else {
showHideEmptyChart(true, false);
}
}
void DashboardWidget::showHideEmptyChart(bool showEmpty, bool loading, bool forceView) {
if (stakesFilter->rowCount() > SHOW_EMPTY_CHART_VIEW_THRESHOLD || forceView) {
if (ui->emptyContainerChart->isVisible() != showEmpty) {
ui->layoutChart->setVisible(!showEmpty);
ui->emptyContainerChart->setVisible(showEmpty);
}
}
// Enable/Disable sort buttons
bool invLoading = !loading;
ui->comboBoxMonths->setEnabled(invLoading);
ui->comboBoxYears->setEnabled(invLoading);
ui->pushButtonMonth->setEnabled(invLoading);
ui->pushButtonAll->setEnabled(invLoading);
ui->pushButtonYear->setEnabled(invLoading);
ui->labelEmptyChart->setText(loading ? tr("Loading chart..") : tr("You have no staking rewards"));
}
void DashboardWidget::initChart() {
chart = new QChart();
axisX = new QBarCategoryAxis();
axisY = new QValueAxis();
// Chart style
chart->legend()->setVisible(false);
chart->legend()->setAlignment(Qt::AlignTop);
chart->layout()->setContentsMargins(0, 0, 0, 0);
chart->setMargins({0, 0, 0, 0});
chart->setBackgroundRoundness(0);
// Axis
chart->addAxis(axisX, Qt::AlignBottom);
chart->addAxis(axisY, Qt::AlignRight);
chart->setAnimationOptions(QChart::SeriesAnimations);
chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->setRubberBand( QChartView::HorizontalRubberBand );
chartView->setContentsMargins(0,0,0,0);
QHBoxLayout *baseScreensContainer = new QHBoxLayout(this);
baseScreensContainer->setMargin(0);
baseScreensContainer->addWidget(chartView);
ui->chartContainer->setLayout(baseScreensContainer);
ui->chartContainer->setContentsMargins(0,0,0,0);
setCssProperty(ui->chartContainer, "container-chart");
}
void DashboardWidget::changeChartColors(){
QColor gridLineColorX;
QColor linePenColorY;
QColor backgroundColor;
QColor gridY;
if(isLightTheme()){
gridLineColorX = QColor(255,255,255);
linePenColorY = gridLineColorX;
backgroundColor = linePenColorY;
axisY->setGridLineColor(QColor("#1a000000"));
}else{
gridY = QColor("#40ffffff");
axisY->setGridLineColor(gridY);
gridLineColorX = QColor(15,11,22);
linePenColorY = gridLineColorX;
backgroundColor = linePenColorY;
}
axisX->setGridLineColor(gridLineColorX);
axisY->setLinePenColor(linePenColorY);
chart->setBackgroundBrush(QBrush(backgroundColor));
if (set0) set0->setBorderColor(gridLineColorX);
if (set1) set1->setBorderColor(gridLineColorX);
}
void DashboardWidget::updateStakeFilter() {
if (chartShow != ALL) {
bool filterByMonth = false;
if (monthFilter != 0 && chartShow == MONTH) {
filterByMonth = true;
}
if (yearFilter != 0) {
if (filterByMonth) {
QDate monthFirst = QDate(yearFilter, monthFilter, 1);
stakesFilter->setDateRange(
QDateTime(monthFirst),
QDateTime(QDate(yearFilter, monthFilter, monthFirst.daysInMonth()))
);
} else {
stakesFilter->setDateRange(
QDateTime(QDate(yearFilter, 1, 1)),
QDateTime(QDate(yearFilter, 12, 31))
);
}
} else if (filterByMonth) {
QDate currentDate = QDate::currentDate();
QDate monthFirst = QDate(currentDate.year(), monthFilter, 1);
stakesFilter->setDateRange(
QDateTime(monthFirst),
QDateTime(QDate(currentDate.year(), monthFilter, monthFirst.daysInMonth()))
);
ui->comboBoxYears->setCurrentText(QString::number(currentDate.year()));
} else {
stakesFilter->clearDateRange();
}
} else {
stakesFilter->clearDateRange();
}
}
// pair XBIT, zXBIT
const QMap<int, std::pair<qint64, qint64>> DashboardWidget::getAmountBy() {
updateStakeFilter();
const int size = stakesFilter->rowCount();
QMap<int, std::pair<qint64, qint64>> amountBy;
// Get all of the stakes
for (int i = 0; i < size; ++i) {
QModelIndex modelIndex = stakesFilter->index(i, TransactionTableModel::ToAddress);
qint64 amount = llabs(modelIndex.data(TransactionTableModel::AmountRole).toLongLong());
QDate date = modelIndex.data(TransactionTableModel::DateRole).toDateTime().date();
bool isXBIT = modelIndex.data(TransactionTableModel::TypeRole).toInt() != TransactionRecord::StakeZXBIT;
int time = 0;
switch (chartShow) {
case YEAR: {
time = date.month();
break;
}
case ALL: {
time = date.year();
break;
}
case MONTH: {
time = date.day();
break;
}
default:
inform(tr("Error loading chart, invalid show option"));
return amountBy;
}
if (amountBy.contains(time)) {
if (isXBIT) {
amountBy[time].first += amount;
} else
amountBy[time].second += amount;
} else {
if (isXBIT) {
amountBy[time] = std::make_pair(amount, 0);
} else {
amountBy[time] = std::make_pair(0, amount);
hasZxbitStakes = true;
}
}
}
return amountBy;
}
bool DashboardWidget::loadChartData(bool withMonthNames) {
if (chartData) {
delete chartData;
chartData = nullptr;
}
chartData = new ChartData();
chartData->amountsByCache = getAmountBy(); // pair XBIT, zXBIT
std::pair<int,int> range = getChartRange(chartData->amountsByCache);
if (range.first == 0 && range.second == 0) {
// Problem loading the chart.
return false;
}
bool isOrderedByMonth = chartShow == MONTH;
int daysInMonth = QDate(yearFilter, monthFilter, 1).daysInMonth();
for (int j = range.first; j < range.second; j++) {
int num = (isOrderedByMonth && j > daysInMonth) ? (j % daysInMonth) : j;
qreal xbit = 0;
qreal zxbit = 0;
if (chartData->amountsByCache.contains(num)) {
std::pair <qint64, qint64> pair = chartData->amountsByCache[num];
xbit = (pair.first != 0) ? pair.first / 100000000 : 0;
zxbit = (pair.second != 0) ? pair.second / 100000000 : 0;
chartData->totalXBIT += pair.first;
chartData->totalZxbit += pair.second;
}
chartData->xLabels << ((withMonthNames) ? monthsNames[num - 1] : QString::number(num));
chartData->valuesXBIT.append(xbit);
chartData->valueszXBIT.append(zxbit);
int max = std::max(xbit, zxbit);
if (max > chartData->maxValue) {
chartData->maxValue = max;
}
}
return true;
}
void DashboardWidget::onChartYearChanged(const QString& yearStr) {
if (isChartInitialized) {
int newYear = yearStr.toInt();
if (newYear != yearFilter) {
yearFilter = newYear;
refreshChart();
}
}
}
void DashboardWidget::onChartMonthChanged(const QString& monthStr) {
if (isChartInitialized) {
int newMonth = ui->comboBoxMonths->currentData().toInt();
if (newMonth != monthFilter) {
monthFilter = newMonth;
refreshChart();
#ifndef Q_OS_MAC
// quick hack to re paint the chart view.
chart->removeSeries(series);
chart->addSeries(series);
#endif
}
}
}
bool DashboardWidget::refreshChart(){
if (isLoading) return false;
isLoading = true;
isChartMin = width() < 1300;
isChartInitialized = false;
showHideEmptyChart(true, true);
return execute(REQUEST_LOAD_TASK);
}
void DashboardWidget::onChartRefreshed() {
if (chart) {
if(series){
series->clear();
series->detachAxis(axisX);
series->detachAxis(axisY);
}
axisX->clear();
}
// init sets
set0 = new QBarSet("XBIT");
set1 = new QBarSet("zXBIT");
set0->setColor(QColor(75,125,92));
set1->setColor(QColor(136,255,176));
if(!series) {
series = new QBarSeries();
chart->addSeries(series);
}
series->attachAxis(axisX);
series->attachAxis(axisY);
set0->append(chartData->valuesXBIT);
set1->append(chartData->valueszXBIT);
// Total
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
if (chartData->totalXBIT > 0 || chartData->totalZxbit > 0) {
setCssProperty(ui->labelAmountXBIT, "text-stake-xbit");
setCssProperty(ui->labelAmountZxbit, "text-stake-zxbit");
} else {
setCssProperty(ui->labelAmountXBIT, "text-stake-xbit-disable");
setCssProperty(ui->labelAmountZxbit, "text-stake-zxbit-disable");
}
forceUpdateStyle({ui->labelAmountXBIT, ui->labelAmountZxbit});
ui->labelAmountXBIT->setText(GUIUtil::formatBalance(chartData->totalXBIT, nDisplayUnit));
ui->labelAmountZxbit->setText(GUIUtil::formatBalance(chartData->totalZxbit, nDisplayUnit, true));
series->append(set0);
if(hasZxbitStakes)
series->append(set1);
// bar width
if (chartShow == YEAR)
series->setBarWidth(0.8);
else {
series->setBarWidth(0.3);
}
axisX->append(chartData->xLabels);
axisY->setRange(0, chartData->maxValue);
// Controllers
switch (chartShow) {
case ALL: {
ui->container_chart_dropboxes->setVisible(false);
break;
}
case YEAR: {
ui->container_chart_dropboxes->setVisible(true);
ui->containerBoxMonths->setVisible(false);
break;
}
case MONTH: {
ui->container_chart_dropboxes->setVisible(true);
ui->containerBoxMonths->setVisible(true);
break;
}
default: break;
}
// Refresh years filter, first address created is the start
int yearStart = QDateTime::fromTime_t(static_cast<uint>(walletModel->getCreationTime())).date().year();
int currentYear = QDateTime::currentDateTime().date().year();
QString selection;
if (ui->comboBoxYears->count() > 0) {
selection = ui->comboBoxYears->currentText();
isChartInitialized = false;
}
ui->comboBoxYears->clear();
if (yearStart == currentYear) {
ui->comboBoxYears->addItem(QString::number(currentYear));
} else {
for (int i = yearStart; i < (currentYear + 1); ++i)ui->comboBoxYears->addItem(QString::number(i));
}
if (!selection.isEmpty()) {
ui->comboBoxYears->setCurrentText(selection);
isChartInitialized = true;
} else {
ui->comboBoxYears->setCurrentText(QString::number(currentYear));
}
// back to normal
isChartInitialized = true;
showHideEmptyChart(false, false, true);
isLoading = false;
}
std::pair<int, int> DashboardWidget::getChartRange(QMap<int, std::pair<qint64, qint64>> amountsBy) {
switch (chartShow) {
case YEAR:
return std::make_pair(1, 13);
case ALL: {
QList<int> keys = amountsBy.uniqueKeys();
if (keys.isEmpty()) {
// This should never happen, ALL means from the beginning of time and if this is called then it must have at least one stake..
inform(tr("Error loading chart, invalid data"));
return std::make_pair(0, 0);
}
qSort(keys);
return std::make_pair(keys.first(), keys.last() + 1);
}
case MONTH:
return std::make_pair(dayStart, dayStart + 9);
default:
inform(tr("Error loading chart, invalid show option"));
return std::make_pair(0, 0);
}
}
void DashboardWidget::updateAxisX(const QStringList* args) {
axisX->clear();
QStringList months;
std::pair<int,int> range = getChartRange(chartData->amountsByCache);
if (args) {
months = *args;
} else {
for (int i = range.first; i < range.second; i++) months << QString::number(i);
}
axisX->append(months);
}
void DashboardWidget::onChartArrowClicked(bool goLeft) {
if (goLeft) {
dayStart--;
if (dayStart == 0) {
dayStart = QDate(yearFilter, monthFilter, 1).daysInMonth();
}
} else {
int dayInMonth = QDate(yearFilter, monthFilter, dayStart).daysInMonth();
dayStart++;
if (dayStart > dayInMonth) {
dayStart = 1;
}
}
refreshChart();
}
void DashboardWidget::windowResizeEvent(QResizeEvent *event){
if (hasStakes && axisX) {
if (width() > 1300) {
if (isChartMin) {
isChartMin = false;
switch (chartShow) {
case YEAR: {
updateAxisX(&monthsNames);
break;
}
case ALL: break;
case MONTH: {
updateAxisX();
break;
}
default:
inform(tr("Error loading chart, invalid show option"));
return;
}
chartView->repaint();
}
} else {
if (!isChartMin) {
updateAxisX();
isChartMin = true;
}
}
}
}
#endif
void DashboardWidget::run(int type) {
#ifdef USE_QTCHARTS
if (type == REQUEST_LOAD_TASK) {
bool withMonthNames = !isChartMin && (chartShow == YEAR);
if (loadChartData(withMonthNames))
QMetaObject::invokeMethod(this, "onChartRefreshed", Qt::QueuedConnection);
}
#endif
}
void DashboardWidget::onError(QString error, int type) {
inform(tr("Error loading chart: %1").arg(error));
}
void DashboardWidget::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) {
// Prevent notifications-spam when initial block download is in progress
if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
if (!txModel || txModel->processingQueuedTransactions())
return;
QString date = txModel->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = txModel->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = txModel->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = txModel->index(start, TransactionTableModel::ToAddress, parent).data().toString();
Q_EMIT incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
DashboardWidget::~DashboardWidget(){
#ifdef USE_QTCHARTS
delete chart;
#endif
delete ui;
}
|
// $Id: SegmentNodeTest.cpp 2344 2009-04-09 21:46:30Z mloskot $
//
// Test Suite for geos::noding::SegmentNode class.
#include <tut.hpp>
// geos
#include <geos/noding/SegmentNode.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequenceFactory.h>
// std
#include <memory>
namespace tut
{
//
// Test Group
//
// Common data used by all tests
struct test_segmentnode_data
{
typedef std::auto_ptr<geos::geom::CoordinateSequence>
CoordSeqPtr;
typedef std::auto_ptr<geos::noding::SegmentString>
SegmentStringPtr;
const geos::geom::CoordinateSequenceFactory* factory_;
test_segmentnode_data()
: factory_(geos::geom::CoordinateArraySequenceFactory::instance())
{}
};
typedef test_group<test_segmentnode_data> group;
typedef group::object object;
group test_segmentnode_group("geos::noding::SegmentNode");
//
// Test Cases
//
// Test of overriden constructor
template<>
template<>
void object::test<1>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(3,3), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// only first endpoint is considered interior
ensure( node.isInterior() );
//
// TODO - mloskot
// 1. What's the purpose of isEndPoint() and how to test it?
// 2. Add new test cases
//
}
}
template<>
template<>
void object::test<2>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(0,0), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( ! node.isInterior() );
}
}
template<>
template<>
void object::test<3>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct an interior node on the given NodedSegmentString
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(2,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
template<>
template<>
void object::test<4>()
{
using geos::geom::Coordinate;
using geos::noding::NodedSegmentString;
using geos::noding::SegmentNode;
// Create coordinates sequence
const size_t coords_size = 2;
CoordSeqPtr cs( factory_->create(0, coords_size) );
ensure( 0 != cs.get() );
Coordinate c0(0, 0);
Coordinate c1(3, 3);
cs->add(c0);
cs->add(c1);
ensure_equals( cs->size(), coords_size );
// Create SegmentString instance
NodedSegmentString segment(cs.get(), 0);
ensure_equals( segment.size(), coords_size );
// Construct a node that doesn't even intersect !!
{
const size_t segment_index = 0;
SegmentNode node( segment, Coordinate(1,2), segment_index,
segment.getSegmentOctant(segment_index) );
ensure_equals( node.segmentIndex, segment_index );
// on first endpoint ...
ensure( node.isInterior() );
}
}
} // namespace tut
|
; A029110: Expansion of 1/((1-x)(1-x^6)(1-x^7)(1-x^12)).
; 1,1,1,1,1,1,2,3,3,3,3,3,5,6,7,7,7,7,9,11,12,13,13,13,16,18,20,21,22,22,25,28,30,32,33,34,38,41,44,46,48,49,54,58,61,64,66,68,74,79,83,86,89,91,98,104,109,113,116,119
lpb $0
mov $2,$0
sub $0,6
seq $2,25788 ; Expansion of 1/((1-x)(1-x^7)(1-x^12)).
add $1,$2
add $1,$2
lpe
div $1,2
add $1,1
mov $0,$1
|
;*!
;* \copy
;* Copyright (c) 2009-2013, Cisco Systems
;* 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.
;*
;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
;* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
;* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
;* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;* POSSIBILITY OF SUCH DAMAGE.
;*
;*
;* quant.asm
;*
;* Abstract
;* sse2 quantize inter-block
;*
;* History
;* 7/6/2009 Created
;*
;*
;*************************************************************************/
%include "asm_inc.asm"
SECTION .text
;************************************************
;NEW_QUANT
;************************************************
%macro SSE2_Quant8 5
MOVDQ %1, %5
pxor %2, %2
pcmpgtw %2, %1
pxor %1, %2
psubw %1, %2
paddusw %1, %3
pmulhuw %1, %4
pxor %1, %2
psubw %1, %2
MOVDQ %5, %1
%endmacro
%macro SSE2_QuantMax8 6
MOVDQ %1, %5
pxor %2, %2
pcmpgtw %2, %1
pxor %1, %2
psubw %1, %2
paddusw %1, %3
pmulhuw %1, %4
pmaxsw %6, %1
pxor %1, %2
psubw %1, %2
MOVDQ %5, %1
%endmacro
%define pDct esp + 4
%define ff esp + 8
%define mf esp + 12
%define max esp + 16
;***********************************************************************
; void WelsQuant4x4_sse2(int16_t *pDct, int16_t* ff, int16_t *mf);
;***********************************************************************
WELS_EXTERN WelsQuant4x4_sse2
%assign push_num 0
LOAD_3_PARA
movdqa xmm2, [r1]
movdqa xmm3, [r2]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x10]
ret
;***********************************************************************
;void WelsQuant4x4Dc_sse2(int16_t *pDct, const int16_t ff, int16_t mf);
;***********************************************************************
WELS_EXTERN WelsQuant4x4Dc_sse2
%assign push_num 0
LOAD_3_PARA
SIGN_EXTENSIONW r1, r1w
SIGN_EXTENSIONW r2, r2w
SSE2_Copy8Times xmm3, r2d
SSE2_Copy8Times xmm2, r1d
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x10]
ret
;***********************************************************************
; void WelsQuantFour4x4_sse2(int16_t *pDct, int16_t* ff, int16_t *mf);
;***********************************************************************
WELS_EXTERN WelsQuantFour4x4_sse2
%assign push_num 0
LOAD_3_PARA
MOVDQ xmm2, [r1]
MOVDQ xmm3, [r2]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x10]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x20]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x30]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x40]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x50]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x60]
SSE2_Quant8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x70]
ret
;***********************************************************************
; void WelsQuantFour4x4Max_sse2(int16_t *pDct, int32_t* f, int16_t *mf, int16_t *max);
;***********************************************************************
WELS_EXTERN WelsQuantFour4x4Max_sse2
%assign push_num 0
LOAD_4_PARA
PUSH_XMM 8
MOVDQ xmm2, [r1]
MOVDQ xmm3, [r2]
pxor xmm4, xmm4
pxor xmm5, xmm5
pxor xmm6, xmm6
pxor xmm7, xmm7
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 ], xmm4
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x10], xmm4
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x20], xmm5
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x30], xmm5
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x40], xmm6
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x50], xmm6
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x60], xmm7
SSE2_QuantMax8 xmm0, xmm1, xmm2, xmm3, [r0 + 0x70], xmm7
SSE2_TransTwo4x4W xmm4, xmm5, xmm6, xmm7, xmm0
pmaxsw xmm0, xmm4
pmaxsw xmm0, xmm5
pmaxsw xmm0, xmm7
movdqa xmm1, xmm0
punpckhqdq xmm0, xmm1
pmaxsw xmm0, xmm1
movq [r3], xmm0
POP_XMM
LOAD_4_PARA_POP
ret
%macro MMX_Copy4Times 2
movd %1, %2
punpcklwd %1, %1
punpckldq %1, %1
%endmacro
SECTION .text
%macro MMX_Quant4 4
pxor %2, %2
pcmpgtw %2, %1
pxor %1, %2
psubw %1, %2
paddusw %1, %3
pmulhuw %1, %4
pxor %1, %2
psubw %1, %2
%endmacro
;***********************************************************************
;int32_t WelsHadamardQuant2x2_mmx(int16_t *rs, const int16_t ff, int16_t mf, int16_t * pDct, int16_t * block);
;***********************************************************************
WELS_EXTERN WelsHadamardQuant2x2_mmx
%assign push_num 0
LOAD_5_PARA
SIGN_EXTENSIONW r1, r1w
SIGN_EXTENSIONW r2, r2w
movd mm0, [r0]
movd mm1, [r0 + 0x20]
punpcklwd mm0, mm1
movd mm3, [r0 + 0x40]
movd mm1, [r0 + 0x60]
punpcklwd mm3, mm1
;hdm_2x2, mm0 = dct0 dct1, mm3 = dct2 dct3
movq mm5, mm3
paddw mm3, mm0
psubw mm0, mm5
punpcklwd mm3, mm0
movq mm1, mm3
psrlq mm1, 32
movq mm5, mm1
paddw mm1, mm3
psubw mm3, mm5
punpcklwd mm1, mm3
;quant_2x2_dc
MMX_Copy4Times mm3, r2d
MMX_Copy4Times mm2, r1d
MMX_Quant4 mm1, mm0, mm2, mm3
; store dct_2x2
movq [r3], mm1
movq [r4], mm1
; pNonZeroCount of dct_2x2
pcmpeqb mm2, mm2 ; mm2 = FF
pxor mm3, mm3
packsswb mm1, mm3
pcmpeqb mm1, mm3 ; set FF if equal, 0 if not equal
psubsb mm1, mm2 ; set 0 if equal, 1 if not equal
psadbw mm1, mm3 ;
mov r1w, 0
mov [r0], r1w
mov [r0 + 0x20], r1w
mov [r0 + 0x40], r1w
mov [r0 + 0x60], r1w
movd retrd, mm1
WELSEMMS
LOAD_5_PARA_POP
ret
;***********************************************************************
;int32_t WelsHadamardQuant2x2Skip_mmx(int16_t *pDct, int16_t ff, int16_t mf);
;***********************************************************************
WELS_EXTERN WelsHadamardQuant2x2Skip_mmx
%assign push_num 0
LOAD_3_PARA
SIGN_EXTENSIONW r1, r1w
SIGN_EXTENSIONW r2, r2w
movd mm0, [r0]
movd mm1, [r0 + 0x20]
punpcklwd mm0, mm1
movd mm3, [r0 + 0x40]
movd mm1, [r0 + 0x60]
punpcklwd mm3, mm1
;hdm_2x2, mm0 = dct0 dct1, mm3 = dct2 dct3
movq mm5, mm3
paddw mm3, mm0
psubw mm0, mm5
punpcklwd mm3, mm0
movq mm1, mm3
psrlq mm1, 32
movq mm5, mm1
paddw mm1, mm3
psubw mm3, mm5
punpcklwd mm1, mm3
;quant_2x2_dc
MMX_Copy4Times mm3, r2d
MMX_Copy4Times mm2, r1d
MMX_Quant4 mm1, mm0, mm2, mm3
; pNonZeroCount of dct_2x2
pcmpeqb mm2, mm2 ; mm2 = FF
pxor mm3, mm3
packsswb mm1, mm3
pcmpeqb mm1, mm3 ; set FF if equal, 0 if not equal
psubsb mm1, mm2 ; set 0 if equal, 1 if not equal
psadbw mm1, mm3 ;
movd retrd, mm1
WELSEMMS
ret
%macro SSE2_DeQuant8 3
MOVDQ %2, %1
pmullw %2, %3
MOVDQ %1, %2
%endmacro
;***********************************************************************
; void WelsDequant4x4_sse2(int16_t *pDct, const uint16_t* mf);
;***********************************************************************
WELS_EXTERN WelsDequant4x4_sse2
%assign push_num 0
LOAD_2_PARA
movdqa xmm1, [r1]
SSE2_DeQuant8 [r0 ], xmm0, xmm1
SSE2_DeQuant8 [r0 + 0x10], xmm0, xmm1
ret
;***********************************************************************
;void WelsDequantFour4x4_sse2(int16_t *pDct, const uint16_t* mf);
;***********************************************************************
WELS_EXTERN WelsDequantFour4x4_sse2
%assign push_num 0
LOAD_2_PARA
movdqa xmm1, [r1]
SSE2_DeQuant8 [r0 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x10 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x20 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x30 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x40 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x50 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x60 ], xmm0, xmm1
SSE2_DeQuant8 [r0+0x70 ], xmm0, xmm1
ret
;***********************************************************************
;void WelsDequantIHadamard4x4_sse2(int16_t *rs, const uint16_t mf);
;***********************************************************************
WELS_EXTERN WelsDequantIHadamard4x4_sse2
%assign push_num 0
LOAD_2_PARA
%ifndef X86_32
movzx r1, r1w
%endif
; WelsDequantLumaDc4x4
SSE2_Copy8Times xmm1, r1d
;psrlw xmm1, 2 ; for the (>>2) in ihdm
MOVDQ xmm0, [r0]
MOVDQ xmm2, [r0+0x10]
pmullw xmm0, xmm1
pmullw xmm2, xmm1
; ihdm_4x4
movdqa xmm1, xmm0
psrldq xmm1, 8
movdqa xmm3, xmm2
psrldq xmm3, 8
SSE2_SumSub xmm0, xmm3, xmm5 ; xmm0 = xmm0 - xmm3, xmm3 = xmm0 + xmm3
SSE2_SumSub xmm1, xmm2, xmm5 ; xmm1 = xmm1 - xmm2, xmm2 = xmm1 + xmm2
SSE2_SumSub xmm3, xmm2, xmm5 ; xmm3 = xmm3 - xmm2, xmm2 = xmm3 + xmm2
SSE2_SumSub xmm0, xmm1, xmm5 ; xmm0 = xmm0 - xmm1, xmm1 = xmm0 + xmm1
SSE2_TransTwo4x4W xmm2, xmm1, xmm3, xmm0, xmm4
SSE2_SumSub xmm2, xmm4, xmm5
SSE2_SumSub xmm1, xmm0, xmm5
SSE2_SumSub xmm4, xmm0, xmm5
SSE2_SumSub xmm2, xmm1, xmm5
SSE2_TransTwo4x4W xmm0, xmm1, xmm4, xmm2, xmm3
punpcklqdq xmm0, xmm1
MOVDQ [r0], xmm0
punpcklqdq xmm2, xmm3
MOVDQ [r0+16], xmm2
ret
%ifdef HAVE_AVX2
; data=%1 abs_out=%2 ff=%3 mf=%4 7FFFh=%5
%macro AVX2_Quant 5
vpabsw %2, %1
vpor %1, %1, %5 ; ensure non-zero before vpsignw
vpaddusw %2, %2, %3
vpmulhuw %2, %2, %4
vpsignw %1, %2, %1
%endmacro
;***********************************************************************
; void WelsQuant4x4_avx2(int16_t *pDct, int16_t* ff, int16_t *mf);
;***********************************************************************
WELS_EXTERN WelsQuant4x4_avx2
%assign push_num 0
LOAD_3_PARA
PUSH_XMM 5
vbroadcasti128 ymm0, [r1]
vbroadcasti128 ymm1, [r2]
WELS_DW32767_VEX ymm2
vmovdqu ymm3, [r0]
AVX2_Quant ymm3, ymm4, ymm0, ymm1, ymm2
vmovdqu [r0], ymm3
vzeroupper
POP_XMM
ret
;***********************************************************************
;void WelsQuant4x4Dc_avx2(int16_t *pDct, int16_t ff, int16_t mf);
;***********************************************************************
WELS_EXTERN WelsQuant4x4Dc_avx2
%assign push_num 0
LOAD_1_PARA
PUSH_XMM 5
%ifidni r1, arg2
vmovd xmm0, arg2d
vpbroadcastw ymm0, xmm0
%else
vpbroadcastw ymm0, arg2
%endif
%ifidni r2, arg3
vmovd xmm1, arg3d
vpbroadcastw ymm1, xmm1
%else
vpbroadcastw ymm1, arg3
%endif
WELS_DW32767_VEX ymm2
vmovdqu ymm3, [r0]
AVX2_Quant ymm3, ymm4, ymm0, ymm1, ymm2
vmovdqu [r0], ymm3
vzeroupper
POP_XMM
ret
;***********************************************************************
; void WelsQuantFour4x4_avx2(int16_t *pDct, int16_t* ff, int16_t *mf);
;***********************************************************************
WELS_EXTERN WelsQuantFour4x4_avx2
%assign push_num 0
LOAD_3_PARA
PUSH_XMM 6
vbroadcasti128 ymm0, [r1]
vbroadcasti128 ymm1, [r2]
WELS_DW32767_VEX ymm4
vmovdqu ymm3, [r0 + 0x00]
vmovdqu ymm5, [r0 + 0x20]
AVX2_Quant ymm3, ymm2, ymm0, ymm1, ymm4
vmovdqu [r0 + 0x00], ymm3
AVX2_Quant ymm5, ymm2, ymm0, ymm1, ymm4
vmovdqu [r0 + 0x20], ymm5
vmovdqu ymm3, [r0 + 0x40]
vmovdqu ymm5, [r0 + 0x60]
AVX2_Quant ymm3, ymm2, ymm0, ymm1, ymm4
vmovdqu [r0 + 0x40], ymm3
AVX2_Quant ymm5, ymm2, ymm0, ymm1, ymm4
vmovdqu [r0 + 0x60], ymm5
vzeroupper
POP_XMM
ret
;***********************************************************************
; void WelsQuantFour4x4Max_avx2(int16_t *pDct, int32_t* ff, int16_t *mf, int16_t *max);
;***********************************************************************
WELS_EXTERN WelsQuantFour4x4Max_avx2
%assign push_num 0
LOAD_4_PARA
PUSH_XMM 7
vbroadcasti128 ymm0, [r1]
vbroadcasti128 ymm1, [r2]
WELS_DW32767_VEX ymm6
vmovdqu ymm4, [r0 + 0x00]
vmovdqu ymm5, [r0 + 0x20]
AVX2_Quant ymm4, ymm2, ymm0, ymm1, ymm6
vmovdqu [r0 + 0x00], ymm4
AVX2_Quant ymm5, ymm3, ymm0, ymm1, ymm6
vmovdqu [r0 + 0x20], ymm5
vperm2i128 ymm4, ymm2, ymm3, 00100000b
vperm2i128 ymm3, ymm2, ymm3, 00110001b
vpmaxsw ymm2, ymm4, ymm3
vmovdqu ymm4, [r0 + 0x40]
vmovdqu ymm5, [r0 + 0x60]
AVX2_Quant ymm4, ymm3, ymm0, ymm1, ymm6
vmovdqu [r0 + 0x40], ymm4
AVX2_Quant ymm5, ymm4, ymm0, ymm1, ymm6
vmovdqu [r0 + 0x60], ymm5
vperm2i128 ymm5, ymm3, ymm4, 00100000b
vperm2i128 ymm4, ymm3, ymm4, 00110001b
vpmaxsw ymm3, ymm5, ymm4
vpxor ymm2, ymm2, ymm6 ; flip bits so as to enable use of vphminposuw to find max value.
vpxor ymm3, ymm3, ymm6 ; flip bits so as to enable use of vphminposuw to find max value.
vextracti128 xmm4, ymm2, 1
vextracti128 xmm5, ymm3, 1
vphminposuw xmm2, xmm2
vphminposuw xmm3, xmm3
vphminposuw xmm4, xmm4
vphminposuw xmm5, xmm5
vpunpcklwd xmm2, xmm2, xmm4
vpunpcklwd xmm3, xmm3, xmm5
vpunpckldq xmm2, xmm2, xmm3
vpxor xmm2, xmm2, xmm6 ; restore non-flipped values.
vmovq [r3], xmm2 ; store max values.
vzeroupper
POP_XMM
LOAD_4_PARA_POP
ret
%endif
|
; A254601: Numbers of n-length words on alphabet {0,1,...,6} with no subwords ii, where i is from {0,1,2}.
; Submitted by Jamie Morken(s2)
; 1,7,46,304,2008,13264,87616,578752,3822976,25252864,166809088,1101865984,7278432256,48078057472,317582073856,2097804673024,13857156333568,91534156693504,604633565495296,3993938019745792,26382162380455936,174268726361718784,1151141007692136448,7603920951599693824,50228089740366708736,331784222248599027712,2191617692453061001216,14476843043712762118144,95627529032088816713728,631672546367383948754944,4172545394332658959384576,27561962551465489551327232,182061956886123573145501696
lpb $0
sub $0,1
add $2,$3
mov $1,$2
add $1,2
add $1,$2
mul $3,2
add $3,$2
mov $2,$3
add $2,2
mov $3,$1
add $3,$2
lpe
mov $0,$3
div $0,2
mul $0,3
add $0,1
|
; A348845: allocated for Wolfdieter Lang
; Submitted by Simon Strandgaard
; 11,35,59,83,107,131,155,179,203,227,251,275,299,323,347,371,395,419,443,467,491,515,539,563,587,611,635,659,683,707,731,755,779,803,827,851,875,899,923,947,971,995,1019,1043,1067
mul $0,24
add $0,11
|
;--------------------------------------------------------------------------------
; OnLoadOW
;--------------------------------------------------------------------------------
;OnLoadMap:
; LDA $7EF2DB ; thing we wrote over
;RTL
;--------------------------------------------------------------------------------
OnPrepFileSelect:
LDA $11 : CMP.b #$03 : BNE +
LDA.b #$06 : STA $14 ; thing we wrote over
RTL
+
JSL.l LoadAlphabetTilemap
JML.l LoadFullItemTiles
;--------------------------------------------------------------------------------
OnDrawHud:
JSL.l DrawChallengeTimer ; this has to come before NewDrawHud because the timer overwrites the compass counter
JSL.l DrHudOverride
JSL.l NewDrawHud
JSL.l SwapSpriteIfNecessary
JSL.l CuccoStorm
JSL.l PollService
JML.l ReturnFromOnDrawHud
;--------------------------------------------------------------------------------
;OnDungeonEntrance:
; STA $7EC172 ; thing we wrote over
;RTL
;--------------------------------------------------------------------------------
OnPlayerDead:
PHA
JSL.l SetDeathWorldChecked
JSL.l SetSilverBowMode
JSL.l RefreshRainAmmo
PLA
RTL
;--------------------------------------------------------------------------------
OnDungeonExit:
PHA : PHP
SEP #$20 ; set 8-bit accumulator
JSL.l SQEGFix
PLP : PLA
STA $040C : STZ $04AC ; thing we wrote over
PHA : PHP
JSL.l HUD_RebuildLong
JSL.l FloodGateResetInner
JSL.l SetSilverBowMode
PLP : PLA
RTL
;--------------------------------------------------------------------------------
OnQuit:
JSL.l SQEGFix
LDA.b #$00 : STA $7F5035 ; bandaid patch bug with mirroring away from text
LDA.b #$10 : STA $1C ; thing we wrote over
RTL
;--------------------------------------------------------------------------------
OnUncleItemGet:
PHA
LDA.l EscapeAssist
BIT.b #$04 : BEQ + : STA !INFINITE_MAGIC : +
BIT.b #$02 : BEQ + : STA !INFINITE_BOMBS : +
BIT.b #$01 : BEQ + : STA !INFINITE_ARROWS : +
LDA UncleItem_Player : STA !MULTIWORLD_ITEM_PLAYER_ID
PLA
JSL Link_ReceiveItem
LDA.l UncleRefill : BIT.b #$04 : BEQ + : LDA.b #$80 : STA $7EF373 : + ; refill magic
LDA.l UncleRefill : BIT.b #$02 : BEQ + : LDA.b #50 : STA $7EF375 : + ; refill bombs
LDA.l UncleRefill : BIT.b #$01 : BEQ + ; refill arrows
LDA.b #70 : STA $7EF376
LDA.l ArrowMode : BEQ +
LDA !INVENTORY_SWAP_2 : ORA #$80 : STA !INVENTORY_SWAP_2 ; enable bow toggle
REP #$20 ; set 16-bit accumulator
LDA $7EF360 : !ADD.l FreeUncleItemAmount : STA $7EF360 ; rupee arrows, so also give the player some money to start
SEP #$20 ; set 8-bit accumulator
+
RTL
;--------------------------------------------------------------------------------
OnAga2Defeated:
JSL.l Dungeon_SaveRoomData_justKeys ; thing we wrote over, make sure this is first
JML.l IncrementAgahnim2Sword
;--------------------------------------------------------------------------------
OnFileCreation:
TAX ; what we wrote over
LDA StartingEquipment+$4C : STA $700340+$4C ; copy starting equipment swaps to file select screen
LDA StartingEquipment+$4E : STA $700340+$4E
RTL
;--------------------------------------------------------------------------------
!RNG_ITEM_LOCK_IN = "$7F5090"
OnFileLoad:
REP #$10 ; set 16 bit index registers
JSL.l EnableForceBlank ; what we wrote over
REP #$20 : LDA.l $30F010 : STA.l $7EF33E : SEP #$20
LDA MultiClientFlags : STA.l $7EF33D
LDA.b #$07 : STA $210C ; Restore screen 3 to normal tile area
LDA !FRESH_FILE_MARKER : BNE +
JSL.l OnNewFile
LDA.b #$FF : STA !FRESH_FILE_MARKER
+
LDA.w $010A : BNE + ; don't adjust the worlds for "continue" or "save-continue"
LDA.l $7EC011 : BNE + ; don't adjust worlds if mosiac is enabled (Read: mirroring in dungeon)
JSL.l DoWorldFix
+
JSL.l MasterSwordFollowerClear
JSL.l InitOpenMode
LDA #$FF : STA !RNG_ITEM_LOCK_IN ; reset rng item lock-in
LDA #$00 : STA $7F5001 ; mark fake flipper softlock as impossible
LDA.l GenericKeys : BEQ +
LDA $7EF38B : STA $7EF36F ; copy generic keys to key counter
+
JSL.l SetSilverBowMode
JSL.l RefreshRainAmmo
JSL.l SetEscapeAssist
LDA.l IsEncrypted : CMP.b #01 : BNE +
JSL LoadStaticDecryptionKey
+
SEP #$10 ; restore 8 bit index registers
RTL
;--------------------------------------------------------------------------------
!RNG_ITEM_LOCK_IN = "$7F5090"
OnNewFile:
PHX : PHP
REP #$20 ; set 16-bit accumulator
LDA.l LinkStartingRupees : STA $7EF362 : STA $7EF360
LDA.l StartingTime : STA $7EF454
LDA.l StartingTime+2 : STA $7EF454+2
LDX.w #$004E : - ; copy over starting equipment
LDA StartingEquipment, X : STA $7EF340, X
DEX : DEX
BPL -
LDX #$000E : -
LDA $7EF37C, X : STA $7EF4E0, X
DEX : DEX
BPL -
LDX #$000E : -
LDA $7EF37C, X : STA $7EF4E0, X
DEX : DEX
BPL -
SEP #$20 ; set 8-bit accumulator
;LDA #$FF : STA !RNG_ITEM_LOCK_IN ; reset rng item lock-in
LDA.l PreopenCurtains : BEQ +
LDA.b #$80 : STA $7EF061 ; open aga tower curtain
LDA.b #$80 : STA $7EF093 ; open skull woods curtain
+
LDA.l PreopenPyramid : BEQ +
LDA.b #$20 : STA $7EF2DB ; pyramid hole already open
+
LDA.l PreopenGanonsTower : BEQ +
LDA.b #$20 : STA $7EF2C3 ; Ganons Tower already open
+
LDA StartingSword : STA $7EF359 ; set starting sword type
; reset some values on new file that are otherwise only reset on hard reset
STZ $03C4 ; ancilla slot index
STZ $047A ; EG
STZ $0B08 : STZ $0B09 ; arc variable
STZ $0CFB ; enemies killed (pull trees)
STZ $0CFC ; times taken damage (pull trees)
STZ $0FC7 : STZ $0FC8 : STZ $0FC9 : STZ $0FCA : STZ $0FCB : STZ $0FCC : STZ $0FCD ; prize packs
LDA #$00 : STA $7EC011 ; mosaic
JSL InitRNGPointerTable ; boss RNG
PLP : PLX
RTL
;--------------------------------------------------------------------------------
OnInitFileSelect:
; LDA.b #$10 : STA $BC ; init sprite pointer - does nothing unless spriteswap.asm is included
; JSL.l SpriteSwap_SetSprite
LDA.b #$51 : STA $0AA2 ;<-- Line missing from JP1.0, needed to ensure "extra" copy of naming screen graphics are loaded.
JSL.l EnableForceBlank
RTL
;--------------------------------------------------------------------------------
OnLinkDamaged:
JSL.l IncrementDamageTakenCounter_Arb
;JSL.l FlipperKill
JML.l OHKOTimer
;--------------------------------------------------------------------------------
OnEnterWater:
JSL.l RegisterWaterEntryScreen
JSL.l MysteryWaterFunction
LDX.b #$04
RTL
;--------------------------------------------------------------------------------
OnLinkDamagedFromPit:
JSL.l OHKOTimer
LDA.l AllowAccidentalMajorGlitch
BEQ ++
-- LDA.b #$14 : STA $11 ; thing we wrote over
RTL
++ LDA.b $10 : CMP.b #$12 : BNE --
STZ.b $11
RTL
;--------------------------------------------------------------------------------
OnLinkDamagedFromPitOutdoors:
JML.l OHKOTimer ; make sure this is last
;--------------------------------------------------------------------------------
!RNG_ITEM_LOCK_IN = "$7F5090"
OnOWTransition:
JSL.l FloodGateReset
JSL.l FlipperFlag
JSL.l StatTransitionCounter
PHP
SEP #$20 ; set 8-bit accumulator
LDA.b #$FF : STA !RNG_ITEM_LOCK_IN ; clear lock-in
PLP
RTL
;--------------------------------------------------------------------------------
!DARK_DUCK_TEMP = "$7F509C"
OnLoadDuckMap:
LDA !DARK_DUCK_TEMP
BNE +
INC : STA !DARK_DUCK_TEMP
JSL OverworldMap_InitGfx : DEC $0200
RTL
+
LDA.b #$00 : STA !DARK_DUCK_TEMP
JML OverworldMap_DarkWorldTilemap
;--------------------------------------------------------------------------------
PreItemGet:
LDA.b #$01 : STA !ITEM_BUSY ; mark item as busy
RTL
;--------------------------------------------------------------------------------
PostItemGet:
JML.l MaybeWriteSRAMTrace
;--------------------------------------------------------------------------------
PostItemAnimation:
LDA.b #$00 : STA !ITEM_BUSY ; mark item as finished
LDA $7F509F : BEQ +
STZ $1CF0 : STZ $1CF1 ; reset decompression buffer
JSL.l Main_ShowTextMessage_Alt
LDA.b #$00 : STA $7F509F
+
LDA $1B : BEQ +
REP #$20 : LDA $A0 : STA !MULTIWORLD_ROOMID : SEP #$20
LDA $0403 : STA !MULTIWORLD_ROOMDATA
+
LDA !MULTIWORLD_ITEM_PLAYER_ID : BEQ +
STZ $02E9
LDA #$00 : STA !MULTIWORLD_ITEM_PLAYER_ID
JML.l Ancilla_ReceiveItem_objectFinished
+
LDA.w $02E9 : CMP.b #$01 : BNE +
LDA.b $2F : BEQ +
JSL.l IncrementChestTurnCounter
+
STZ $02E9 : LDA $0C5E, X ; thing we wrote over to get here
JML.l Ancilla_ReceiveItem_optimus+6
;--------------------------------------------------------------------------------
|
#include "SDLWrapper.h"
bool SDLWrapper::init(int width, int height, int up) {
upscale = up;
screenWidth = width * upscale;
screenHeight = height * upscale;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return false;
} else {
// Create window
window = SDL_CreateWindow("Chip8Emu", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return false;
} else {
// Get window surface
screenSurface = SDL_GetWindowSurface(window);
}
}
return true;
}
void SDLWrapper::drawGraphics(unsigned char* gfx) {
// Fill the screen in black
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0, 0, 0));
for (int i = 0; i < 64 * 32; i++) {
if (*(gfx + i) == 1) {
SDL_Rect rect;
rect.x = ((i * upscale) % screenWidth);
rect.y = ((i * upscale) / screenWidth) * upscale;
rect.w = upscale;
rect.h = upscale;
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(screenSurface->format, 255, 255, 255));
}
}
SDL_UpdateWindowSurface(window);
}
// Please do not look at the contents of this method
unsigned char* SDLWrapper::getKeyState() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
hasPressedQuit = true;
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) { // ....Just look at the wiki
case SDLK_1:
keys[1] = 1;
break;
case SDLK_2:
keys[2] = 1;
break;
case SDLK_3:
keys[3] = 1;
break;
case SDLK_q:
keys[4] = 1;
break;
case SDLK_w:
keys[5] = 1;
break;
case SDLK_e:
keys[6] = 1;
break;
case SDLK_a:
keys[7] = 1;
break;
case SDLK_s:
keys[8] = 1;
break;
case SDLK_d:
keys[9] = 1;
break;
case SDLK_z:
keys[10] = 1;
break;
case SDLK_x:
keys[0] = 1;
break;
case SDLK_c:
keys[11] = 1;
break;
case SDLK_4:
keys[12] = 1;
break;
case SDLK_r:
keys[13] = 1;
break;
case SDLK_f:
keys[14] = 1;
break;
case SDLK_v:
keys[15] = 1;
break;
}
}
if (event.type == SDL_KEYUP) {
switch (event.key.keysym.sym) { // ....Just look at the wiki
case SDLK_1:
keys[1] = 0;
break;
case SDLK_2:
keys[2] = 0;
break;
case SDLK_3:
keys[3] = 0;
break;
case SDLK_q:
keys[4] = 0;
break;
case SDLK_w:
keys[5] = 0;
break;
case SDLK_e:
keys[6] = 0;
break;
case SDLK_a:
keys[7] = 0;
break;
case SDLK_s:
keys[8] = 0;
break;
case SDLK_d:
keys[9] = 0;
break;
case SDLK_z:
keys[10] = 0;
break;
case SDLK_x:
keys[0] = 0;
break;
case SDLK_c:
keys[11] = 0;
break;
case SDLK_4:
keys[12] = 0;
break;
case SDLK_r:
keys[13] = 0;
break;
case SDLK_f:
keys[14] = 0;
break;
case SDLK_v:
keys[15] = 0;
break;
}
}
}
return keys;
}
void SDLWrapper::shutDown() {
SDL_DestroyWindow(window);
SDL_Quit();
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Connection.h"
#include "../TestBase.h"
#include "ProvenanceTestHelper.h"
TEST_CASE("Connection::poll() works correctly", "[poll]") {
const auto flow_repo = std::make_shared<TestRepository>();
const auto content_repo = std::make_shared<core::repository::VolatileContentRepository>();
content_repo->initialize(std::make_shared<minifi::Configure>());
const auto id_generator = utils::IdGenerator::getIdGenerator();
utils::Identifier connection_id = id_generator->generate();
utils::Identifier src_id = id_generator->generate();
utils::Identifier dest_id = id_generator->generate();
const auto connection = std::make_shared<minifi::Connection>(flow_repo, content_repo, "test_connection", connection_id, src_id, dest_id);
std::set<std::shared_ptr<core::FlowFile>> expired_flow_files;
SECTION("when called on an empty Connection, poll() returns nullptr") {
SECTION("without expiration duration") {}
SECTION("with expiration duration") { connection->setFlowExpirationDuration(1s); }
REQUIRE(nullptr == connection->poll(expired_flow_files));
}
SECTION("when called on a connection with a single flow file, poll() returns the flow file") {
SECTION("without expiration duration") {}
SECTION("with expiration duration") { connection->setFlowExpirationDuration(1s); }
const auto flow_file = std::make_shared<core::FlowFile>();
connection->put(flow_file);
REQUIRE(flow_file == connection->poll(expired_flow_files));
REQUIRE(nullptr == connection->poll(expired_flow_files));
}
SECTION("when called on a connection with a single penalized flow file, poll() returns nullptr") {
SECTION("without expiration duration") {}
SECTION("with expiration duration") { connection->setFlowExpirationDuration(1s); }
const auto flow_file = std::make_shared<core::FlowFile>();
flow_file->penalize(std::chrono::seconds{10});
connection->put(flow_file);
REQUIRE(nullptr == connection->poll(expired_flow_files));
}
SECTION("when called on a connection with a single expired flow file, poll() returns nullptr and returns the expired flow file in the out parameter") {
const auto flow_file = std::make_shared<core::FlowFile>();
connection->setFlowExpirationDuration(1ms);
connection->put(flow_file);
std::this_thread::sleep_for(std::chrono::milliseconds{2});
REQUIRE(nullptr == connection->poll(expired_flow_files));
REQUIRE(std::set<std::shared_ptr<core::FlowFile>>{flow_file} == expired_flow_files);
}
SECTION("when there is a non-penalized flow file followed by a penalized flow file, poll() returns the non-penalized flow file") {
SECTION("without expiration duration") {}
SECTION("with expiration duration") { connection->setFlowExpirationDuration(1s); }
const auto penalized_flow_file = std::make_shared<core::FlowFile>();
penalized_flow_file->penalize(std::chrono::seconds{10});
connection->put(penalized_flow_file);
const auto flow_file = std::make_shared<core::FlowFile>();
connection->put(flow_file);
REQUIRE(flow_file == connection->poll(expired_flow_files));
REQUIRE(nullptr == connection->poll(expired_flow_files));
}
}
|
; A023504: Greatest exponent in prime-power factorization of prime(n) - 1.
; 0,1,2,1,1,2,4,2,1,2,1,2,3,1,1,2,1,2,1,1,3,1,1,3,5,2,1,1,3,4,2,1,3,1,2,2,2,4,1,2,1,2,1,6,2,2,1,1,1,2,3,1,4,3,8,1,2,3,2,3,1,2,2,1,3,2,1,4,1,2,5,1,1,2,3,1,2,2,4,3,1,2,1,4,1,1,6,3,2,1,1,1,5,2,1,1,2,3,2,3
seq $0,40976 ; a(n) = prime(n) - 2.
seq $0,51903 ; Maximal exponent in prime factorization of n.
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC _log10
EXTERN cm48_sdcciy_log10
defc _log10 = cm48_sdcciy_log10
|
; A046897: Sum of divisors of n that are not divisible by 4.
; 1,3,4,3,6,12,8,3,13,18,12,12,14,24,24,3,18,39,20,18,32,36,24,12,31,42,40,24,30,72,32,3,48,54,48,39,38,60,56,18,42,96,44,36,78,72,48,12,57,93,72,42,54,120,72,24,80,90,60,72,62,96,104,3,84,144,68,54,96,144,72,39,74,114,124,60,96,168,80,18,121,126,84,96,108,132,120,36,90,234,112,72,128,144,120,12,98,171,156,93
seq $0,259445 ; Multiplicative with a(n) = n if n is odd and a(2^s)=2.
seq $0,39653 ; a(0) = 0; for n > 0, a(n) = sigma(n)-1.
add $0,1
|
// Copyright (c) 2012 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 "chrome/renderer/loadtimes_extension_bindings.h"
#include <math.h>
#include "base/time/time.h"
#include "content/public/renderer/document_state.h"
#include "extensions/renderer/v8_helpers.h"
#include "net/http/http_response_info.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPerformance.h"
#include "v8/include/v8.h"
using blink::WebDataSource;
using blink::WebLocalFrame;
using blink::WebNavigationType;
using blink::WebPerformance;
using content::DocumentState;
// Values for CSI "tran" property
const int kTransitionLink = 0;
const int kTransitionForwardBack = 6;
const int kTransitionOther = 15;
const int kTransitionReload = 16;
namespace extensions_v8 {
static const char* const kLoadTimesExtensionName = "v8/LoadTimes";
class LoadTimesExtensionWrapper : public v8::Extension {
public:
// Creates an extension which adds a new function, chrome.loadTimes()
// This function returns an object containing the following members:
// requestTime: The time the request to load the page was received
// loadTime: The time the renderer started the load process
// finishDocumentLoadTime: The time the document itself was loaded
// (this is before the onload() method is fired)
// finishLoadTime: The time all loading is done, after the onload()
// method and all resources
// navigationType: A string describing what user action initiated the load
//
// Note that chrome.loadTimes() is deprecated in favor of performance.timing.
// Many of the timings reported via chrome.loadTimes() match timings available
// in performance.timing. Timing data will be removed from chrome.loadTimes()
// in a future release. No new timings or other information should be exposed
// via these APIs.
LoadTimesExtensionWrapper() :
v8::Extension(kLoadTimesExtensionName,
"var chrome;"
"if (!chrome)"
" chrome = {};"
"chrome.loadTimes = function() {"
" native function GetLoadTimes();"
" return GetLoadTimes();"
"};"
"chrome.csi = function() {"
" native function GetCSI();"
" return GetCSI();"
"}") {}
v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
v8::Isolate* isolate,
v8::Local<v8::String> name) override {
if (name->Equals(v8::String::NewFromUtf8(isolate, "GetLoadTimes"))) {
return v8::FunctionTemplate::New(isolate, GetLoadTimes);
} else if (name->Equals(v8::String::NewFromUtf8(isolate, "GetCSI"))) {
return v8::FunctionTemplate::New(isolate, GetCSI);
}
return v8::Local<v8::FunctionTemplate>();
}
static const char* GetNavigationType(WebNavigationType nav_type) {
switch (nav_type) {
case blink::kWebNavigationTypeLinkClicked:
return "LinkClicked";
case blink::kWebNavigationTypeFormSubmitted:
return "FormSubmitted";
case blink::kWebNavigationTypeBackForward:
return "BackForward";
case blink::kWebNavigationTypeReload:
return "Reload";
case blink::kWebNavigationTypeFormResubmitted:
return "Resubmitted";
case blink::kWebNavigationTypeOther:
return "Other";
}
return "";
}
static int GetCSITransitionType(WebNavigationType nav_type) {
switch (nav_type) {
case blink::kWebNavigationTypeLinkClicked:
case blink::kWebNavigationTypeFormSubmitted:
case blink::kWebNavigationTypeFormResubmitted:
return kTransitionLink;
case blink::kWebNavigationTypeBackForward:
return kTransitionForwardBack;
case blink::kWebNavigationTypeReload:
return kTransitionReload;
case blink::kWebNavigationTypeOther:
return kTransitionOther;
}
return kTransitionOther;
}
static void LoadtimesGetter(
v8::Local<v8::Name> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
if (WebLocalFrame* frame = WebLocalFrame::FrameForCurrentContext()) {
frame->UsageCountChromeLoadTimes(
blink::WebString::FromUTF8(*v8::String::Utf8Value(name)));
}
info.GetReturnValue().Set(info.Data());
}
static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().SetNull();
WebLocalFrame* frame = WebLocalFrame::FrameForCurrentContext();
if (!frame) {
return;
}
WebDataSource* data_source = frame->DataSource();
if (!data_source) {
return;
}
DocumentState* document_state = DocumentState::FromDataSource(data_source);
if (!document_state) {
return;
}
WebPerformance web_performance = frame->Performance();
// Though request time now tends to be used to describe the time that the
// request for the main resource was issued, when chrome.loadTimes() was
// added, it was used to describe 'The time the request to load the page was
// received', which is the time now known as navigation start. For backward
// compatibility, we continue to provide request_time, setting its value to
// navigation start.
double request_time = web_performance.NavigationStart();
// Developers often use start_load_time as the time the navigation was
// started, so we return navigationStart for this value as well. See
// https://gist.github.com/search?utf8=%E2%9C%93&q=startLoadTime.
// Note that, historically, start_load_time reported the time that a
// provisional load was first processed in the render process. For
// browser-initiated navigations, this is some time after navigation start,
// which means that developers who used this value as a way to track the
// start of a navigation were misusing this timestamp and getting the wrong
// value - they should be using navigationStart intead. Additionally,
// once plznavigate ships, provisional loads will not be processed by the
// render process for browser-initiated navigations, so reporting the time a
// provisional load was processed in the render process will no longer make
// sense. Thus, we now report the time for navigationStart, which is a value
// more consistent with what developers currently use start_load_time for.
double start_load_time = web_performance.NavigationStart();
// TODO(bmcquade): Remove this. 'commit' time is a concept internal to
// chrome that shouldn't be exposed to the web platform.
double commit_load_time = web_performance.ResponseStart();
double finish_document_load_time =
web_performance.DomContentLoadedEventEnd();
double finish_load_time = web_performance.LoadEventEnd();
double first_paint_time = web_performance.FirstPaint();
// TODO(bmcquade): remove this. It's misleading to track the first paint
// after the load event, since many pages perform their meaningful paints
// long before the load event fires. We report a time of zero for the
// time being.
double first_paint_after_load_time = 0.0;
std::string navigation_type =
GetNavigationType(data_source->GetNavigationType());
bool was_fetched_via_spdy = document_state->was_fetched_via_spdy();
bool was_alpn_negotiated = document_state->was_alpn_negotiated();
std::string alpn_negotiated_protocol =
document_state->alpn_negotiated_protocol();
bool was_alternate_protocol_available =
document_state->was_alternate_protocol_available();
std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString(
document_state->connection_info());
// Important: |frame|, |data_source| and |document_state| should not be
// referred to below this line, as JS setters below can invalidate these
// pointers.
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context> ctx = isolate->GetCurrentContext();
v8::Local<v8::Object> load_times = v8::Object::New(isolate);
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "requestTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, request_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "startLoadTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, start_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "commitLoadTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, commit_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "finishDocumentLoadTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, finish_document_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "finishLoadTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, finish_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "firstPaintTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate, first_paint_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "firstPaintAfterLoadTime", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Number::New(isolate,first_paint_after_load_time))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "navigationType", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::String::NewFromUtf8(isolate, navigation_type.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "wasFetchedViaSpdy", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Boolean::New(isolate, was_fetched_via_spdy))
.FromMaybe(false)) {
return;
}
if (!load_times
->SetAccessor(ctx,
v8::String::NewFromUtf8(isolate, "wasNpnNegotiated",
v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter, nullptr,
v8::Boolean::New(isolate, was_alpn_negotiated))
.FromMaybe(false)) {
return;
}
if (!load_times
->SetAccessor(
ctx, v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol",
v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter, nullptr,
v8::String::NewFromUtf8(isolate,
alpn_negotiated_protocol.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "wasAlternateProtocolAvailable",
v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::Boolean::New(isolate, was_alternate_protocol_available))
.FromMaybe(false)) {
return;
}
if (!load_times->SetAccessor(
ctx,
v8::String::NewFromUtf8(
isolate, "connectionInfo", v8::NewStringType::kNormal)
.ToLocalChecked(),
LoadtimesGetter,
nullptr,
v8::String::NewFromUtf8(isolate, connection_info.c_str(),
v8::NewStringType::kNormal)
.ToLocalChecked())
.FromMaybe(false)) {
return;
}
args.GetReturnValue().Set(load_times);
}
static void GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) {
args.GetReturnValue().SetNull();
WebLocalFrame* frame = WebLocalFrame::FrameForCurrentContext();
if (!frame) {
return;
}
WebDataSource* data_source = frame->DataSource();
if (!data_source) {
return;
}
WebPerformance web_performance = frame->Performance();
base::Time now = base::Time::Now();
base::Time start =
base::Time::FromDoubleT(web_performance.NavigationStart());
base::Time dom_content_loaded_end =
base::Time::FromDoubleT(web_performance.DomContentLoadedEventEnd());
base::TimeDelta page = now - start;
int navigation_type =
GetCSITransitionType(data_source->GetNavigationType());
// Important: |frame| and |data_source| should not be referred to below this
// line, as JS setters below can invalidate these pointers.
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context> ctx = isolate->GetCurrentContext();
v8::Local<v8::Object> csi = v8::Object::New(isolate);
if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "startE",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, floor(start.ToDoubleT() * 1000)))
.FromMaybe(false)) {
return;
}
// NOTE: historically, the CSI onload field has reported the time the
// document finishes parsing, which is DOMContentLoaded. Thus, we continue
// to report that here, despite the fact that the field is named onloadT.
if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "onloadT",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate,
floor(dom_content_loaded_end.ToDoubleT() *
1000))).FromMaybe(false)) {
return;
}
if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "pageT",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, page.InMillisecondsF()))
.FromMaybe(false)) {
return;
}
if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "tran",
v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::Number::New(isolate, navigation_type))
.FromMaybe(false)) {
return;
}
args.GetReturnValue().Set(csi);
}
};
v8::Extension* LoadTimesExtension::Get() {
return new LoadTimesExtensionWrapper();
}
} // namespace extensions_v8
|
# Example program to showcase assembler syntax
# This example doesn't actually do anything useful!
# constants
FOO = 42
BAR = FOO * 2
ADDR = 0x20000000
# basic labels, jumping, and branching
start:
addi t0, zero, BAR
jal zero, end
middle:
beq t0, zero, main
addi t0, t0, -1
end:
jal zero, middle
# string literals (regex: "string (.*)")
string hello
string "world"
string "hello world"
string hello ## world
string hello\nworld
string hello\\nworld
# bytes literals
bytes 1 2 0x03 0b100 5 0x06 0b111 8
# packed values
pack <B, 0
pack <B, 255
pack <I, ADDR
# align to 4-byte (32-bit) boundary
align 4
main:
# set t0 to location of "main" relative to ADDR
li t0 %position(main, ADDR)
|
//
// Copyright 2019 The Abseil Authors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/flags/internal/usage.h"
#include <stdint.h>
#include <functional>
#include <map>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/config.h"
#include "absl/flags/commandlineflag.h"
#include "absl/flags/flag.h"
#include "absl/flags/internal/flag.h"
#include "absl/flags/internal/path_util.h"
#include "absl/flags/internal/private_handle_accessor.h"
#include "absl/flags/internal/program_name.h"
#include "absl/flags/internal/registry.h"
#include "absl/flags/usage_config.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
ABSL_FLAG(bool, help, false,
"show help on important flags for this binary [tip: all flags can "
"have two dashes]");
ABSL_FLAG(bool, helpfull, false, "show help on all flags");
ABSL_FLAG(bool, helpshort, false,
"show help on only the main module for this program");
ABSL_FLAG(bool, helppackage, false,
"show help on all modules in the main package");
ABSL_FLAG(bool, version, false, "show version and build info and exit");
ABSL_FLAG(bool, only_check_args, false, "exit after checking all flags");
ABSL_FLAG(std::string, helpon, "",
"show help on the modules named by this flag value");
ABSL_FLAG(std::string, helpmatch, "",
"show help on modules whose name contains the specified substr");
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace flags_internal {
namespace {
// This class is used to emit an XML element with `tag` and `text`.
// It adds opening and closing tags and escapes special characters in the text.
// For example:
// std::cout << XMLElement("title", "Milk & Cookies");
// prints "<title>Milk & Cookies</title>"
class XMLElement {
public:
XMLElement(absl::string_view tag, absl::string_view txt)
: tag_(tag), txt_(txt) {}
friend std::ostream& operator<<(std::ostream& out,
const XMLElement& xml_elem) {
out << "<" << xml_elem.tag_ << ">";
for (auto c : xml_elem.txt_) {
switch (c) {
case '"':
out << """;
break;
case '\'':
out << "'";
break;
case '&':
out << "&";
break;
case '<':
out << "<";
break;
case '>':
out << ">";
break;
default:
out << c;
break;
}
}
return out << "</" << xml_elem.tag_ << ">";
}
private:
absl::string_view tag_;
absl::string_view txt_;
};
// --------------------------------------------------------------------
// Helper class to pretty-print info about a flag.
class FlagHelpPrettyPrinter {
public:
// Pretty printer holds on to the std::ostream& reference to direct an output
// to that stream.
FlagHelpPrettyPrinter(int max_line_len, std::ostream& out)
: out_(out),
max_line_len_(max_line_len),
line_len_(0),
first_line_(true) {}
void Write(absl::string_view str, bool wrap_line = false) {
// Empty string - do nothing.
if (str.empty()) return;
std::vector<absl::string_view> tokens;
if (wrap_line) {
for (auto line : absl::StrSplit(str, absl::ByAnyChar("\n\r"))) {
if (!tokens.empty()) {
// Keep line separators in the input string.
tokens.push_back("\n");
}
for (auto token :
absl::StrSplit(line, absl::ByAnyChar(" \t"), absl::SkipEmpty())) {
tokens.push_back(token);
}
}
} else {
tokens.push_back(str);
}
for (auto token : tokens) {
bool new_line = (line_len_ == 0);
// Respect line separators in the input string.
if (token == "\n") {
EndLine();
continue;
}
// Write the token, ending the string first if necessary/possible.
if (!new_line && (line_len_ + token.size() >= max_line_len_)) {
EndLine();
new_line = true;
}
if (new_line) {
StartLine();
} else {
out_ << ' ';
++line_len_;
}
out_ << token;
line_len_ += token.size();
}
}
void StartLine() {
if (first_line_) {
out_ << " ";
line_len_ = 4;
first_line_ = false;
} else {
out_ << " ";
line_len_ = 6;
}
}
void EndLine() {
out_ << '\n';
line_len_ = 0;
}
private:
std::ostream& out_;
const int max_line_len_;
int line_len_;
bool first_line_;
};
void FlagHelpHumanReadable(const CommandLineFlag& flag, std::ostream& out) {
FlagHelpPrettyPrinter printer(80, out); // Max line length is 80.
// Flag name.
printer.Write(absl::StrCat("--", flag.Name()));
// Flag help.
printer.Write(absl::StrCat("(", flag.Help(), ");"), /*wrap_line=*/true);
// The listed default value will be the actual default from the flag
// definition in the originating source file, unless the value has
// subsequently been modified using SetCommandLineOption() with mode
// SET_FLAGS_DEFAULT.
std::string dflt_val = flag.DefaultValue();
std::string curr_val = flag.CurrentValue();
bool is_modified = curr_val != dflt_val;
if (flag.IsOfType<std::string>()) {
dflt_val = absl::StrCat("\"", dflt_val, "\"");
}
printer.Write(absl::StrCat("default: ", dflt_val, ";"));
if (is_modified) {
if (flag.IsOfType<std::string>()) {
curr_val = absl::StrCat("\"", curr_val, "\"");
}
printer.Write(absl::StrCat("currently: ", curr_val, ";"));
}
printer.EndLine();
}
// Shows help for every filename which matches any of the filters
// If filters are empty, shows help for every file.
// If a flag's help message has been stripped (e.g. by adding '#define
// STRIP_FLAG_HELP 1' then this flag will not be displayed by '--help'
// and its variants.
void FlagsHelpImpl(std::ostream& out, flags_internal::FlagKindFilter filter_cb,
HelpFormat format, absl::string_view program_usage_message) {
if (format == HelpFormat::kHumanReadable) {
out << flags_internal::ShortProgramInvocationName() << ": "
<< program_usage_message << "\n\n";
} else {
// XML schema is not a part of our public API for now.
out << "<?xml version=\"1.0\"?>\n"
<< "<!-- This output should be used with care. We do not report type "
"names for flags with user defined types -->\n"
<< "<!-- Prefer flag only_check_args for validating flag inputs -->\n"
// The document.
<< "<AllFlags>\n"
// The program name and usage.
<< XMLElement("program", flags_internal::ShortProgramInvocationName())
<< '\n'
<< XMLElement("usage", program_usage_message) << '\n';
}
// Map of package name to
// map of file name to
// vector of flags in the file.
// This map is used to output matching flags grouped by package and file
// name.
std::map<std::string,
std::map<std::string, std::vector<const absl::CommandLineFlag*>>>
matching_flags;
flags_internal::ForEachFlag([&](absl::CommandLineFlag& flag) {
// Ignore retired flags.
if (flag.IsRetired()) return;
// If the flag has been stripped, pretend that it doesn't exist.
if (flag.Help() == flags_internal::kStrippedFlagHelp) return;
std::string flag_filename = flag.Filename();
// Make sure flag satisfies the filter
if (!filter_cb || !filter_cb(flag_filename)) return;
matching_flags[std::string(flags_internal::Package(flag_filename))]
[flag_filename]
.push_back(&flag);
});
absl::string_view package_separator; // controls blank lines between packages
absl::string_view file_separator; // controls blank lines between files
for (const auto& package : matching_flags) {
if (format == HelpFormat::kHumanReadable) {
out << package_separator;
package_separator = "\n\n";
}
file_separator = "";
for (const auto& flags_in_file : package.second) {
if (format == HelpFormat::kHumanReadable) {
out << file_separator << " Flags from " << flags_in_file.first
<< ":\n";
file_separator = "\n";
}
for (const auto* flag : flags_in_file.second) {
flags_internal::FlagHelp(out, *flag, format);
}
}
}
if (format == HelpFormat::kHumanReadable) {
if (filter_cb && matching_flags.empty()) {
out << " No modules matched: use -helpfull\n";
}
} else {
// The end of the document.
out << "</AllFlags>\n";
}
}
} // namespace
// --------------------------------------------------------------------
// Produces the help message describing specific flag.
void FlagHelp(std::ostream& out, const CommandLineFlag& flag,
HelpFormat format) {
if (format == HelpFormat::kHumanReadable)
flags_internal::FlagHelpHumanReadable(flag, out);
}
// --------------------------------------------------------------------
// Produces the help messages for all flags matching the filter.
// If filter is empty produces help messages for all flags.
void FlagsHelp(std::ostream& out, absl::string_view filter, HelpFormat format,
absl::string_view program_usage_message) {
flags_internal::FlagKindFilter filter_cb = [&](absl::string_view filename) {
return filter.empty() || filename.find(filter) != absl::string_view::npos;
};
flags_internal::FlagsHelpImpl(out, filter_cb, format, program_usage_message);
}
// --------------------------------------------------------------------
// Checks all the 'usage' command line flags to see if any have been set.
// If so, handles them appropriately.
int HandleUsageFlags(std::ostream& out,
absl::string_view program_usage_message) {
if (absl::GetFlag(FLAGS_helpshort)) {
flags_internal::FlagsHelpImpl(
out, flags_internal::GetUsageConfig().contains_helpshort_flags,
HelpFormat::kHumanReadable, program_usage_message);
return 1;
}
if (absl::GetFlag(FLAGS_helpfull)) {
// show all options
flags_internal::FlagsHelp(out, "", HelpFormat::kHumanReadable,
program_usage_message);
return 1;
}
if (!absl::GetFlag(FLAGS_helpon).empty()) {
flags_internal::FlagsHelp(
out, absl::StrCat("/", absl::GetFlag(FLAGS_helpon), "."),
HelpFormat::kHumanReadable, program_usage_message);
return 1;
}
if (!absl::GetFlag(FLAGS_helpmatch).empty()) {
flags_internal::FlagsHelp(out, absl::GetFlag(FLAGS_helpmatch),
HelpFormat::kHumanReadable,
program_usage_message);
return 1;
}
if (absl::GetFlag(FLAGS_help)) {
flags_internal::FlagsHelpImpl(
out, flags_internal::GetUsageConfig().contains_help_flags,
HelpFormat::kHumanReadable, program_usage_message);
out << "\nTry --helpfull to get a list of all flags.\n";
return 1;
}
if (absl::GetFlag(FLAGS_helppackage)) {
flags_internal::FlagsHelpImpl(
out, flags_internal::GetUsageConfig().contains_helppackage_flags,
HelpFormat::kHumanReadable, program_usage_message);
out << "\nTry --helpfull to get a list of all flags.\n";
return 1;
}
if (absl::GetFlag(FLAGS_version)) {
if (flags_internal::GetUsageConfig().version_string)
out << flags_internal::GetUsageConfig().version_string();
// Unlike help, we may be asking for version in a script, so return 0
return 0;
}
if (absl::GetFlag(FLAGS_only_check_args)) {
return 0;
}
return -1;
}
} // namespace flags_internal
ABSL_NAMESPACE_END
} // namespace absl
|
// Original test: ./tschaefe/hw4/problem6/j_0.asm
// Author: tschaefe
// Test source code follows
// j test 0
// Jump instruction should move on to add, effectively doing nothing
j 0x0
add r1, r2, r3
halt
|
/**
* VKTS - VulKan ToolS.
*
* The MIT License (MIT)
*
* Copyright (c) since 2014 Norbert Nopper
*
* 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.
*/
#ifndef VKTS_FN_TEXTURE_OBJECT_HPP_
#define VKTS_FN_TEXTURE_OBJECT_HPP_
#include <vkts/vulkan/composition/vkts_composition.hpp>
namespace vkts
{
/**
*
* @ThreadSafe
*/
VKTS_APICALL ITextureObjectSP VKTS_APIENTRY textureObjectCreate(const IContextObjectSP& contextObject, const std::string& name, const IImageObjectSP& imageObject, const ISamplerSP& sampler);
}
#endif /* VKTS_FN_TEXTURE_OBJECT_HPP_ */
|
; A005586: a(n) = n(n+4)(n+5)/6.
; 0,5,14,28,48,75,110,154,208,273,350,440,544,663,798,950,1120,1309,1518,1748,2000,2275,2574,2898,3248,3625,4030,4464,4928,5423,5950,6510,7104,7733,8398,9100,9840,10619,11438,12298,13200,14145,15134,16168,17248,18375,19550,20774,22048,23373,24750,26180,27664,29203,30798,32450,34160,35929,37758,39648,41600,43615,45694,47838,50048,52325,54670,57084,59568,62123,64750,67450,70224,73073,75998,79000,82080,85239,88478,91798,95200,98685,102254,105908,109648,113475,117390,121394,125488,129673,133950,138320,142784,147343,151998,156750,161600,166549,171598,176748
add $0,4
mov $1,$0
bin $0,3
sub $0,$1
|
; A017642: a(n) = (12*n+10)^2.
; 100,484,1156,2116,3364,4900,6724,8836,11236,13924,16900,20164,23716,27556,31684,36100,40804,45796,51076,56644,62500,68644,75076,81796,88804,96100,103684,111556,119716,128164,136900,145924,155236,164836,174724,184900,195364,206116,217156,228484,240100,252004,264196,276676,289444,302500,315844,329476,343396,357604,372100,386884,401956,417316,432964,448900,465124,481636,498436,515524,532900,550564,568516,586756,605284,624100,643204,662596,682276,702244,722500,743044,763876,784996,806404,828100,850084,872356,894916,917764,940900,964324,988036,1012036,1036324,1060900,1085764,1110916,1136356,1162084,1188100,1214404,1240996,1267876,1295044,1322500,1350244,1378276,1406596,1435204,1464100,1493284,1522756,1552516,1582564,1612900,1643524,1674436,1705636,1737124,1768900,1800964,1833316,1865956,1898884,1932100,1965604,1999396,2033476,2067844,2102500,2137444,2172676,2208196,2244004,2280100,2316484,2353156,2390116,2427364,2464900,2502724,2540836,2579236,2617924,2656900,2696164,2735716,2775556,2815684,2856100,2896804,2937796,2979076,3020644,3062500,3104644,3147076,3189796,3232804,3276100,3319684,3363556,3407716,3452164,3496900,3541924,3587236,3632836,3678724,3724900,3771364,3818116,3865156,3912484,3960100,4008004,4056196,4104676,4153444,4202500,4251844,4301476,4351396,4401604,4452100,4502884,4553956,4605316,4656964,4708900,4761124,4813636,4866436,4919524,4972900,5026564,5080516,5134756,5189284,5244100,5299204,5354596,5410276,5466244,5522500,5579044,5635876,5692996,5750404,5808100,5866084,5924356,5982916,6041764,6100900,6160324,6220036,6280036,6340324,6400900,6461764,6522916,6584356,6646084,6708100,6770404,6832996,6895876,6959044,7022500,7086244,7150276,7214596,7279204,7344100,7409284,7474756,7540516,7606564,7672900,7739524,7806436,7873636,7941124,8008900,8076964,8145316,8213956,8282884,8352100,8421604,8491396,8561476,8631844,8702500,8773444,8844676,8916196,8988004
mul $0,12
add $0,10
pow $0,2
mov $1,$0
|
; A274009: 1's distance from a number in its binary expansion.
; 1,0,2,1,2,1,3,2,2,1,3,2,3,2,4,3,2,1,3,2,3,2,4,3,3,2,4,3,4,3,5,4,2,1,3,2,3,2,4,3,3,2,4,3,4,3,5,4,3,2,4,3,4,3,5,4,4,3,5,4,5,4,6,5,2,1,3,2,3,2,4,3,3,2,4,3,4,3,5,4,3,2,4,3,4,3,5,4,4,3
mov $4,$0
div $4,2
mov $3,$4
mov $5,1
add $5,$0
mov $6,1
lpb $6,1
sub $6,1
lpb $4,1
div $4,2
sub $3,$4
lpe
mov $1,$3
mov $2,$5
lpb $2,1
gcd $2,2
lpe
sub $1,$2
lpe
add $4,3
add $1,$4
sub $1,1
|
/*
This file is part of the sample code for the article,
"Processing XML with Xerces and the DOM" by Ethan McCallum (2005/09/08)
Published on ONLamp.com (http://www.onlamp.com/)
http://www.onlamp.com/pub/a/onlamp/2005/09/08/xerces_dom.html
*/
#include "helper-classes.h"
#include<list>
#include<iterator>
#include<algorithm>
#include<stdexcept>
#include<xercesc/util/XMLString.hpp>
// = = = = = = = = = = = = = = = = = = = =
/*
class FreeXercesString is a template and thus
defined in its entirety in the header
*/
// = = = = = = = = = = = = = = = = = = = =
#include<string>
#include<xercesc/util/XMLString.hpp>
DualString::DualString( const XMLCh* const original )
:
cString_( xercesc::XMLString::transcode( original ) ) ,
xmlString_( xercesc::XMLString::replicate( original ) )
{
return ;
} // DualString::ctor( const XMLCh* )
DualString::DualString( const char* const original )
:
cString_( xercesc::XMLString::replicate( original ) ) ,
xmlString_( xercesc::XMLString::transcode( original ) )
{
return ;
} // DualString::ctor( const char* )
DualString::DualString( const std::string& original )
:
cString_( xercesc::XMLString::replicate( original.c_str() ) ) ,
xmlString_( xercesc::XMLString::transcode( original.c_str() ) )
{
return ;
} // DualString::ctor( const std::string& )
DualString::~DualString() throw() {
xercesc::XMLString::release( &cString_ ) ;
xercesc::XMLString::release( &xmlString_ ) ;
return ;
} // DualString::dtor()
const char* DualString::asCString() const throw() {
return( cString_ ) ;
} // DualString::asCString()
const XMLCh* DualString::asXMLString() const throw() {
return( xmlString_ ) ;
} // DualString::asXMLString()
std::ostream& DualString::print( std::ostream& s ) const {
s << cString_ ;
return( s ) ;
} // DualString::print()
std::ostream& operator<<( std::ostream& s, const DualString& obj ) {
return( obj.print( s ) ) ;
} // operator<< for DualString
// = = = = = = = = = = = = = = = = = = = =
StringManager::StringManager()
:
xmlStrings_() ,
cStrings_()
{
return ;
} // StringManager::ctor
StringManager::~StringManager() throw(){
drain() ;
return ;
} // StringManager::dtor
void StringManager::drain() throw() {
std::for_each(
xmlStrings_.begin() ,
xmlStrings_.end() ,
FreeXercesString::releaseXMLString
) ;
std::for_each(
cStrings_.begin() ,
cStrings_.end() ,
FreeXercesString::releaseCString
) ;
return ;
} // StringManager::drain()
char* StringManager::disown( char* str ) throw( std::logic_error ){
CStringList::iterator item = std::find( cStrings_.begin() , cStrings_.end() , str ) ;
if( cStrings_.end() == item ){
throw( std::logic_error( "Request to disown a string not owned by this container." ) ) ;
}
char* result = *item ;
// the call to list<>::remove has the added benefit of nailing duplicates
cStrings_.remove( str ) ;
return( result ) ;
} // StringManager::disown( char* str )
XMLCh* StringManager::disown( XMLCh* str ) throw( std::logic_error ){
XMLStringList::iterator item = std::find( xmlStrings_.begin() , xmlStrings_.end() , str ) ;
if( xmlStrings_.end() == item ){
throw( std::logic_error( "Request to disown a string not owned by this container." ) ) ;
}
XMLCh* result = *item ;
// the call to list<>::remove has the added benefit of nailing duplicates
xmlStrings_.remove( str ) ;
return( result ) ;
} // StringManager::disown( XMLCh* str )
XMLCh* StringManager::convert( const char* str ){
XMLCh* result = xercesc::XMLString::transcode( str ) ;
xmlStrings_.push_back( result ) ;
return( result ) ;
} // StringManager::convert( const char* )
XMLCh* StringManager::convert( const std::string& str ){
XMLCh* result = xercesc::XMLString::transcode( str.c_str() ) ;
xmlStrings_.push_back( result ) ;
return( result ) ;
} // StringManager::convert( const std::string& )
char* StringManager::convert( const XMLCh* str ){
char* result = xercesc::XMLString::transcode( str ) ;
cStrings_.push_back( result ) ;
return( result ) ;
} // StringManager::convert( const XMLCh* )
// = = = = = = = = = = = = = = = = = = = =
|
; A058031: a(n) = n^4 - 2*n^3 + 3*n^2 - 2*n + 1, the Alexander polynomial for reef and granny knots.
; 1,1,9,49,169,441,961,1849,3249,5329,8281,12321,17689,24649,33489,44521,58081,74529,94249,117649,145161,177241,214369,257049,305809,361201,423801,494209,573049,660969,758641,866761,986049,1117249,1261129,1418481,1590121,1776889,1979649,2199289,2436721,2692881,2968729,3265249,3583449,3924361,4289041,4678569,5094049,5536609,6007401,6507601,7038409,7601049,8196769,8826841,9492561,10195249,10936249,11716929,12538681,13402921,14311089,15264649,16265089,17313921,18412681,19562929,20766249,22024249,23338561,24710841,26142769,27636049,29192409,30813601,32501401,34257609,36084049,37982569,39955041,42003361,44129449,46335249,48622729,50993881,53450721,55995289,58629649,61355889,64176121,67092481,70107129,73222249,76440049,79762761,83192641,86731969,90383049,94148209,98029801,102030201,106151809,110397049,114768369,119268241,123899161,128663649,133564249,138603529,143784081,149108521,154579489,160199649,165971689,171898321,177982281,184226329,190633249,197205849,203946961,210859441,217946169,225210049,232654009,240281001,248094001,256096009,264290049,272679169,281266441,290054961,299047849,308248249,317659329,327284281,337126321,347188689,357474649,367987489,378730521,389707081,400920529,412374249,424071649,436016161,448211241,460660369,473367049,486334809,499567201,513067801,526840209,540888049,555214969,569824641,584720761,599907049,615387249,631165129,647244481,663629121,680322889,697329649,714653289,732297721,750266881,768564729,787195249,806162449,825470361,845123041,865124569,885479049,906190609,927263401,948701601,970509409,992691049,1015250769,1038192841,1061521561,1085241249,1109356249,1133870929,1158789681,1184116921,1209857089,1236014649,1262594089,1289599921,1317036681,1344908929,1373221249,1401978249,1431184561,1460844841,1490963769,1521546049,1552596409,1584119601,1616120401,1648603609,1681574049,1715036569,1748996041,1783457361,1818425449,1853905249,1889901729,1926419881,1963464721,2001041289,2039154649,2077809889,2117012121,2156766481,2197078129,2237952249,2279394049,2321408761,2364001641,2407177969,2450943049,2495302209,2540260801,2585824201,2631997809,2678787049,2726197369,2774234241,2822903161,2872209649,2922159249,2972757529,3024010081,3075922521,3128500489,3181749649,3235675689,3290284321,3345581281,3401572329,3458263249,3515659849,3573767961,3632593441,3692142169,3752420049,3813433009
bin $0,2
mul $0,2
add $0,1
pow $0,2
mov $1,$0
|
; ===============================================================
; Dec 2013
; ===============================================================
;
; void *calloc(size_t nmemb, size_t size)
;
; Allocate nmemb * size bytes from the current thread's heap and
; initialize that memory to 0.
;
; Returns 0 if nmemb*size == 0 without indicating error.
;
; ===============================================================
INCLUDE "clib_cfg.asm"
SECTION code_clib
SECTION code_alloc_malloc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC asm_calloc
EXTERN __malloc_heap
EXTERN asm_heap_calloc
asm_calloc:
; Allocate zero-initialized memory from the thread's default heap
;
; enter : hl = uint nmemb
; bc = uint size
;
; exit : success
;
; hl = address of allocated memory, 0 if size == 0
; carry reset
;
; fail on insufficient memory
;
; hl = 0
; carry set, errno = ENOMEM
;
; fail on lock acquisition
;
; hl = 0
; carry set, errno = ENOLCK
;
; uses : af, bc, de, hl
ld de,(__malloc_heap)
jp asm_heap_calloc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ELSE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC asm_calloc
EXTERN asm_calloc_unlocked
defc asm_calloc = asm_calloc_unlocked
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
;--------------------------------------------------------------------------------
PreOverworld_LoadProperties_ChooseMusic:
; A: scratch space (value never used)
; Y: set to overworld animated tileset
; X: set to music track/command id
JSL.l FixFrogSmith ; Just a convenient spot to install this hook
LDY.b #$58 ; death mountain animated tileset.
LDX.b #$02 ; Default light world theme
LDA $8A : ORA #$40 ; check both light and dark world DM at the same time
CMP.b #$43 : BEQ .endOfLightWorldChecks
CMP.b #$45 : BEQ .endOfLightWorldChecks
CMP.b #$47 : BEQ .endOfLightWorldChecks
LDY.b #$5A ; Main overworld animated tileset
; Skip village and lost woods checks if entering dark world or a special area
LDA $8A : CMP.b #$40 : !BGE .notVillageOrWoods
LDX.b #$07 ; Default village theme
; Check what phase we're in
;LDA $7EF3C5 : CMP.b #$03 : !BLT +
; LDX.b #$02 ; Default light world theme (phase >=3)
;+
; Check if we're entering the village
LDA $8A : CMP.b #$18 : BEQ .endOfLightWorldChecks
; For NA release would we also branch on indexes #$22 #$28 #$29
LDX.b #$05 ; Lost woods theme
; check if we've pulled from the master sword pedestal
LDA $7EF300 : AND.b #$40 : BEQ +
LDX.b #$02 ; Default light world theme
+
; check if we are entering lost woods
LDA $8A : BEQ .endOfLightWorldChecks
.notVillageOrWoods
; Use the normal overworld (light world) music
LDX.b #$02
; Check phase ; In phase >= 2
LDA $7EF3C5 : CMP.b #$02 : !BGE +
; If phase < 2, play the legend music
LDX.b #$03
+
.endOfLightWorldChecks
; if we are in the light world go ahead and set chosen selection
LDA $7EF3CA : BEQ .checkInverted+4
LDX.b #$0F ; dark woods theme
; This music is used in dark woods
LDA $8A
CMP.b #$40 : BEQ +
LDX.b #$0D ; dark death mountain theme
; This music is used in dark death mountain
CMP.b #$43 : BEQ + : CMP.b #$45 : BEQ + : CMP.b #$47 : BEQ +
LDX.b #$09 ; dark overworld theme
+
; if not inverted and light world, or inverted and dark world, skip moon pearl check
.checkInverted
LDA $7EF3CA : CLC : ROL #$03 : CMP InvertedMode : BEQ .lastCheck
; Does Link have a moon pearl?
LDA $7EF357 : BNE +
LDX.b #$04 ; bunny theme
+
.lastCheck
LDA $0132 : CMP.b #$F2 : BNE +
CPX $0130 : BNE +
; If the last played command ($0132) was half volume (#$F2)
; and the actual song playing ($0130) is same as the one for this area (X)
; then play the full volume command (#F3) instead of restarting the song
LDX.b #$F3
+
JML.l PreOverworld_LoadProperties_SetSong
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
Overworld_FinishMirrorWarp:
REP #$20
LDA.w #$2641 : STA $4370
LDX.b #$3E
LDA.w #$FF00
.clear_hdma_table
STA $1B00, X : STA $1B40, X
STA $1B80, X : STA $1BC0, X
STA $1C00, X : STA $1C40, X
STA $1C80, X
DEX #2 : BPL .clear_hdma_table
LDA.w #$0000 : STA $7EC007 : STA $7EC009
SEP #$20
JSL $00D7C8 ; $57C8 IN ROM
LDA.b #$80 : STA $9B
LDX.b #$04 ; bunny theme
; if not inverted and light world, or inverted and dark world, skip moon pearl check
LDA $7EF3CA : CLC : ROL #$03 : CMP InvertedMode : BEQ +
LDA $7EF357 : BEQ .endOfLightWorldChecks
+
LDX.b #$09 ; default dark world theme
LDA $8A : CMP.b #$40 : !BGE .endOfLightWorldChecks
LDX.b #$02 ; hyrule field theme
; Check if we're entering the lost woods
CMP.b #$00 : BNE +
LDA $7EF300 : AND.b #$40 : BNE .endOfLightWorldChecks
LDX.b #$05 ; lost woods theme
BRA .endOfLightWorldChecks
+
; Check if we're entering the village
CMP.b #$18 : BNE .endOfLightWorldChecks
; Check what phase we're in
; LDA $7EF3C5 : CMP.b #$03 : !BGE .endOfLightWorldChecks
LDX.b #$07 ; Default village theme (phase <3)
.endOfLightWorldChecks
STX $012C
LDA $8A : CMP.b #$40 : BNE +
LDX #$0F ; dark woods theme
BRA .bunny
+
CMP.b #$43 : BEQ .darkMountain
CMP.b #$45 : BEQ .darkMountain
CMP.b #$47 : BNE .notDarkMountain
.darkMountain
LDA.b #$09 : STA $012D ; set storm ambient SFX
LDX.b #$0D ; dark mountain theme
.bunny
LDA $7EF357 : ORA InvertedMode : BNE +
LDX #$04 ; bunny theme
+
STX $012C
.notDarkMountain
LDA $11 : STA $010C
STZ $11
STZ $B0
STZ $0200
STZ $0710
RTL
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
BirdTravel_LoadTargetAreaMusic:
; Skip village and lost woods checks if entering dark world or a special area
LDA $8A : CMP.b #$43 : BEQ .endOfLightWorldChecks
CMP.b #$40 : !BGE .notVillageOrWoods
LDX.b #$07 ; Default village theme
; Check what phase we're in
;LDA $7EF3C5 : CMP.b #$03 : !BLT +
; LDX.b #$02 ; Default light world theme (phase >=3)
;+
; Check if we're entering the village
LDA $8A : CMP.b #$18 : BEQ .endOfLightWorldChecks
; For NA release would we also branch on indexes #$22 #$28 #$29
;LDX.b #$05 ; Lost woods theme
; check if we've pulled from the master sword pedestal
;LDA $7EF300 : AND.b #$40 : BEQ +
; LDX.b #$02 ; Default light world theme
;+
; check if we are entering lost woods
LDA $8A : BEQ .endOfLightWorldChecks
.notVillageOrWoods
; Use the normal overworld (light world) music
LDX.b #$02
; Check phase ; In phase >= 2
LDA $7EF3C5 : CMP.b #$02 : !BGE +
; If phase < 2, play the legend music
LDX.b #$03
+
.endOfLightWorldChecks
; if we are in the light world go ahead and set chosen selection
LDA $7EF3CA : BEQ .checkInverted+4
LDX.b #$09 ; dark overworld theme
LDA $8A
; Misery Mire rain SFX
CMP.b #$70 : BNE ++
LDA $7EF2F0 : AND.b #$20 : BNE ++
LDA.b #$01 : CMP $0131 : BEQ +
STA $012D
+ : BRA .checkInverted
++
; This music is used in dark death mountain
CMP.b #$43 : BEQ .darkMountain
; CMP.b #$45 : BEQ .darkMountain
; CMP.b #$47 : BEQ .darkMountain
LDA.b #$05 : STA $012D
BRA .checkInverted
.darkMountain
LDA $7EF37A : CMP.b #$7F : BEQ +
LDX.b #$0D ; dark death mountain theme
+ : LDA.b #$09 : STA $012D
; if not inverted and light world, or inverted and dark world, skip moon pearl check
.checkInverted
LDA $7EF3CA : CLC : ROL #$03 : CMP InvertedMode : BEQ .lastCheck
; Does Link have a moon pearl?
LDA $7EF357 : BNE +
LDX.b #$04 ; bunny theme
+
.lastCheck
RTL
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
;0 = Is Kakariko Overworld
;1 = Not Kakariko Overworld
PsychoSolder_MusicCheck:
LDA $040A : CMP.b #$18 : BNE .done ; thing we overwrote - check if overworld location is Kakariko
LDA $1B ; Also check that we are outdoors
.done
RTL
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
; Additional dark world checks to determine whether or not to fade out music
; on mosaic transitions
;
; On entry, A = $8A (overworld area being loaded)
Overworld_MosaicDarkWorldChecks:
CMP.b #$40 : beq .checkCrystals
CMP.b #$42 : beq .checkCrystals
CMP.b #$50 : beq .checkCrystals
CMP.b #$51 : bne .doFade
.checkCrystals
LDA $7EF37A : CMP.b #$7F : BEQ .done
.doFade
LDA.b #$F1 : STA $012C ; thing we wrote over, fade out music
.done
RTL
;--------------------------------------------------------------------------------
|
; A093132: Third binomial transform of Fibonacci(3n+2).
; 1,8,60,440,3200,23200,168000,1216000,8800000,63680000,460800000,3334400000,24128000000,174592000000,1263360000000,9141760000000,66150400000000,478668800000000,3463680000000000,25063424000000000,181360640000000000,1312337920000000000,9496166400000000000,68714905600000000000,497225728000000000000,3597959168000000000000,26035077120000000000000,188391587840000000000000,1363214336000000000000000,9864311603200000000000000,71378829312000000000000000,516502061056000000000000000,3737444024320000000000000000,27044399022080000000000000000,195695109734400000000000000000,1416063116902400000000000000000,10246728974336000000000000000000,74146027405312000000000000000000,536525694566400000000000000000000,3882336397557760000000000000000000,28092850084249600000000000000000000,203281772891340800000000000000000000
mov $2,$0
add $2,2
seq $2,93145 ; Third binomial transform of Fibonacci(3n)/Fibonacci(3).
mov $0,$2
div $0,10
|
; A315247: Coordination sequence Gal.5.87.3 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,6,10,15,19,25,31,35,40,44,50,56,60,65,69,75,81,85,90,94,100,106,110,115,119,125,131,135,140,144,150,156,160,165,169,175,181,185,190,194,200,206,210,215,219,225,231,235,240,244
mov $2,70
mov $3,$0
add $0,3
lpb $2
add $2,$0
sub $0,1
mul $2,2
div $2,7
lpe
add $0,2
mov $4,$3
mul $4,4
add $0,$4
|
;******************************************************************************
.define dir_reg, 0x00
.define port_reg, 0x01
.define pin_reg, 0x02
.define prescaler_l, 0x03
.define prescaler_h, 0x04
.define count_ctrl, 0x05
.define uart_baud, 0x0A
.define uart_ctrl, 0x0B
.define uart_buffer, 0x0C
.define motor_control, 0x0D
.define motor_enable, 0x0E
.define motor_pwm0, 0x0F
.define motor_pwm1, 0x10
.define servo, 0x11
.define sonar_control, 0x12
.define sonar_range, 0x13
.define gpu_addr, 0x2000
.define gpu_ctrl_reg, 0x80
;******************************************************************************
.code
ldi r14, 0xff ; set up the stack pointer
ldi r15, 0x00
ldi r0, 128 ; move the servo straight ahead
out r0, servo
ldi r0, 8 ; set the baud rate to 115200
out r0, uart_baud
;******************************************************************************
start: ldi r0, 0x01 ; trigger a reading
out r0, sonar_control
;******************************************************************************
poll0: in r0, sonar_control ; poll for reading ready
ani r0, 1
bnz poll0
in r0, sonar_range
mov r1, r0
srl r1
srl r1
srl r1
srl r1
cpi r1, 0x09
bc alpha1
adi r1, 48
br print1
alpha1: adi r1, 55
print1: call print
ani r0, 0x0f
cpi r0, 0x09
bc alpha2
adi r0, 48
br print2
alpha2: adi r0, 55
print2: mov r1, r0
call print
ldi r1, 10
call print
br start
;******************************************************************************
print: in r2, uart_ctrl ; poll for empty tx buffer
ani r2, 2
bz print
out r1, uart_buffer ; write to the uart
ret
;****************************************************************************** |
*
* PROGRAM: ZFAM040
* AUTHOR: Rich Jackson and Randy Frerking
* COMMENTS: zFAM - z/OS File Access Manager
*
* This program is executed as the Query Mode DELETE
* service called by zFAM001 control program.
*
* This program will delete primary column index and
* delete secondary column indexes when present.
*
***********************************************************************
* Start Dynamic Storage Area *
***********************************************************************
DFHEISTG DSECT
REGSAVE DS 16F Register Save Area
*
BAS_REG DS F BAS return register
APPLID DS CL08 CICS Applid
SYSID DS CL04 CICS SYSID
USERID DS CL08 CICS USERID
PA_ADDR DS F Parser Array address
PA_LEN DS F Parser Array length
FK_ADDR DS F zFAM Key record address
FK_LEN DS F zFAM Key record length
FF_ADDR DS F zFAM File record address
FF_LEN DS F zFAM File record length
FD_ADDR DS F Field container address
FD_LEN DS F Field container length
*
FA_ADDR DS F FAxxFD document address
FA_LEN DS F FAxxFD document length
FA_RESP DS F FAxxFD container response
*
DS 0F
W_INDEX DS F Parser array index
W_ADDR DS F Beginning data area address
W_COUNT DS CL08 Packed decimal field count
W_COLUMN DS CL08 Packed decimal field column
DS 0F
C_NAME DS CL16 Container name
C_LENGTH DS F Container data length
C_RESP DS F Container response
DS 0F
W_PRI_ID DS CL01 Primary column ID flag
DS 0F
SI_PTR DS F Secondary Index pointer
SI_FIELD DS CL56 Secondary Index field
*
***********************************************************************
* zFAM090 communication area *
* Logging for ZFAM040 exceptional conditions *
***********************************************************************
C_LOG DS 0F
C_STATUS DS CL03 HTTP Status code
C_REASON DS CL02 Reason Code
C_USERID DS CL08 UserID
C_PROG DS CL08 Service program name
C_FILE DS CL08 File name
C_FIELD DS CL16 Field name
E_LOG EQU *-C_LOG Commarea Data length
L_LOG DS H Commarea length
*
***********************************************************************
* File resources. *
***********************************************************************
WK_FCT DS 0F zFAM Key structure FCT name
WK_TRAN DS CL04 zFAM transaction ID
WK_DD DS CL04 zFAM KEY DD name
*
WK_LEN DS H zFAM Key structure length
*
WF_FCT DS 0F zFAM File structure FCT name
WF_TRAN DS CL04 zFAM transaction ID
WF_DD DS CL04 zFAM FILE DD name
*
WF_LEN DS H zFAM File structure length
*
***********************************************************************
* Primary Index information *
***********************************************************************
DS 0F
PI_TYPE DS CL01 Actual key type
DS 0F
PI_COL DS CL04 Actual key column
DS 0F
PI_LEN DS CL04 Actual key lenth
***********************************************************************
* FAxxKEY record key. *
***********************************************************************
DS 0F
WK_KEY DS CL255 zFAM Key record key
*
***********************************************************************
* FAxxFILE record key. *
***********************************************************************
WF_KEY DS 0F zFAM File description
WF_IDN DS CL06 IDN
WF_NC DS CL02 NC
WF_SEG DS H Segment number
WF_SUFX DS H Suffix number
WF_NULL DS F Zeroes (not used)
*
***********************************************************************
* Spanned Segment number *
***********************************************************************
DS 0F
SS_SEG DS H Spanned segment number
*
***********************************************************************
* Spanned segment status information *
***********************************************************************
DS 0F
W_LENGTH DS CL08 Field length (spanned/remaining)
W_WIDTH DS F Field width
W_RA_B DS F Response array base
W_FF_A DS F FAxxFILE data address
W_LO DS F Column range low
W_HI DS F Column range high
W_REL_D DS F Relative displacement
W_REL_L DS F Relative length
W_SEG DS H Current segment number
*
***********************************************************************
* Trace entry *
***********************************************************************
DS 0F
W_46_M DS CL08 Trace entry paragraph
*
***********************************************************************
* zFAM column index resources *
***********************************************************************
CI_FCT DS 0F zFAM Column Index (FAxxSIxx)
CI_TRAN DS CL04 zFAM transaction ID
DS CL02 zFAM SI
CI_SI DS CL02 zFAM ID
*
CI_LEN DS H zFAM Column Index length
CI_ID DS CL03 Column Index (zone decimal)
*
W_ID DS CL02 Column Index (packed decimal)
*
***********************************************************************
* zFAM CI store record buffer *
***********************************************************************
COPY ZFAMCIA
*
***********************************************************************
* Start zFAM102 DFHCOMMAREA *
***********************************************************************
DS 0F
ZP_COMM DS 0CL261 zFAM102 DFHCOMMAREA
ZP_TYPE DS CL06 Type of request
* DELETE
* CREATE
* UPDATE
DS CL02 alignment
ZP_NAME DS CL16 zFAM record key name
ZP_KEY_L DS H zFAM record key length
ZP_KEY DS CL255 zFAM record key
ZP_L EQU *-ZP_COMM DFHCOMMAREA length
DS 0H
ZP_LEN DS H DFHCOMMAREA length (LINK)
*
***********************************************************************
* End zFAM102 DFHCOMMAREA *
***********************************************************************
*
***********************************************************************
* Start Data Center document template resources *
***********************************************************************
DS 0F
DC_RESP DS F FD response code
DC_LEN DS F FD document length
DC_TOKEN DS CL16 FD document token
DC_DOCT DS 0CL48
DC_TRAN DS CL04 FD EIBTRNID
DC_TYPE DS CL02 FD Type
DC_SPACE DS CL42 FD Spaces
*
DS 0F
DC_REC DS 0CL172 Data Center record
DS CL06
DC_ENV DS CL02 Replication environment
DS CL02
DC_HOST DS CL160 Replication host name
DS CL02
***********************************************************************
* End Data Center document template resources *
***********************************************************************
*
*
***********************************************************************
* End Dynamic Storage Area *
***********************************************************************
*
***********************************************************************
* Start Parser Array (maximum 256 fields) *
***********************************************************************
*
PA_DSECT DSECT
P_ID DS PL02 Field ID
P_SEC DS PL02 Field level security
P_COL DS PL04 Field column
P_LEN DS PL04 Field length
P_TYPE DS CL01 Field type
P_WHERE DS CL01 WHERE indicator
P_SEG DS H Field record segment
P_NAME DS CL16 Field Name
E_PA EQU *-P_ID PA entry length
***********************************************************************
* End Parser Array *
***********************************************************************
*
***********************************************************************
* Start Field Data buffer *
***********************************************************************
FD_DSECT DSECT
*
*
***********************************************************************
* End Field Data buffer *
***********************************************************************
*
***********************************************************************
* zFAM KEY store record buffer *
***********************************************************************
COPY ZFAMDKA
*
***********************************************************************
* zFAM FILE store record buffer *
***********************************************************************
COPY ZFAMDFA
*
*
***********************************************************************
* Start FAxxFD DOCTEMPLATE buffer (Field Definitions) *
***********************************************************************
*
FA_DSECT DSECT
DS CL03 ID=
F_ID DS CL03 Field ID
DS CL05 ,Col=
F_COL DS CL07 Field column number
DS CL05 ,Len=
F_LEN DS CL06 Field length
DS CL06 ,Type=
F_TYPE DS CL01 Field type (Character or Numeric)
DS CL05 ,Sec=
F_SEC DS CL02 Field security level
DS CL06 ,Name=
F_NAME DS CL16 Field name
DS CL01 end of field marker
DS CL02 CRLF
E_FA EQU *-FA_DSECT Field Definition entry length
***********************************************************************
* End FAxxSD DOCTEMPLATE buffer *
***********************************************************************
*
***********************************************************************
***********************************************************************
* Control Section - ZFAM040 *
***********************************************************************
***********************************************************************
ZFAM040 DFHEIENT CODEREG=(R2,R3),DATAREG=R11,EIBREG=R12
ZFAM040 AMODE 31
ZFAM040 RMODE 31
B SYSDATE BRANCH AROUND LITERALS
DC CL08'ZFAM040 '
DC CL48' -- Query Mode DELETE service '
DC CL08' '
DC CL08'&SYSDATE'
DC CL08' '
DC CL08'&SYSTIME'
SYSDATE DS 0H
* *
***********************************************************************
* Issue GETMAIN for parser array *
***********************************************************************
SY_0000 DS 0H
EXEC CICS GETMAIN X
SET(R5) X
FLENGTH(S_PA_LEN) X
INITIMG(HEX_00) X
NOHANDLE
*
L R4,PA_LEN Load GETMAIN length
ST R5,PA_ADDR Save GETMAIN address
LA R6,E_PA Load parser array entry length
USING PA_DSECT,R5 ... tell assembler
*
***********************************************************************
* Issue GET CONTAINER for FAxxFD document template *
***********************************************************************
SY_0010 DS 0H
MVC C_NAME,C_FAXXFD Move FAXXFD container name
MVC C_LENGTH,S_FD_LEN Move FAXXFD container length
BAS R14,GC_0010 Issue GET CONTAINER
MVC FA_RESP,C_RESP Save FAxxFD container response
ST R1,FA_ADDR Save FAXXFD address
MVC FA_LEN,C_LENGTH Move FAXXFD length
*
L R7,FA_LEN Load FAXXFD length
L R8,FA_ADDR Load FAXXFD address
LA R9,E_FA Load FAXXFD entry length
USING FA_DSECT,R8 ... tell assembler
***********************************************************************
* Scan FAXXFD for secondary column index fields, which will be used *
* to build the Parser Array. *
***********************************************************************
SY_0012 DS 0H
CLC F_ID,ZD_ONE+1 Column index?
BC B'0100',SY_0014 ... no, get next FD entry
*
MVC P_NAME,F_NAME Move field name to PA
MVC P_TYPE,F_TYPE Move field type to PA
PACK P_SEC,F_SEC Pack field security to PA
PACK P_ID,F_ID Pack field ID to PA
PACK P_COL,F_COL Pack field column to PA
PACK P_LEN,F_LEN Pack field length to PA
*
LA R5,0(R6,R5) Point to next PA entry
L R4,PA_LEN Load PA length
LA R4,0(R6,R4) Add PA length
ST R4,PA_LEN Save PA length
***********************************************************************
* Continue scan of FAxxFD until EOFD. *
***********************************************************************
SY_0014 DS 0H
LA R8,0(R9,R8) Point to next FD entry
SR R7,R9 Reduce by an FD entry length
BC B'0010',SY_0012 Continue FD scan
***********************************************************************
* Reset Parser Array registers. *
***********************************************************************
SY_0030 DS 0H
L R4,PA_LEN Load parser array length
L R5,PA_ADDR Load parser array address
USING PA_DSECT,R5 ... tell assembler
LA R6,E_PA Load parser array entry length
*
CLC FA_RESP,=F'0' FAxxFD container available?
BC B'0111',SY_0060 ... no,
***********************************************************************
* Scan parser array and mark the segment *
***********************************************************************
SY_0040 DS 0H
XR R14,R14 Clear sign bits in register
ZAP W_COLUMN,P_COL Move PA column to work area
CVB R15,W_COLUMN Convert to binary
D R14,=F'32000' Divide column by segment size
LA R15,1(,R15) Relative to one
STH R15,P_SEG Mark segment number
***********************************************************************
* Continue scan of parser array until EOPA *
***********************************************************************
SY_0042 DS 0H
LA R5,0(R6,R5) Point to next PA entry
SR R4,R6 Subtract PA entry length
BC B'0011',SY_0040 Continue PA scan
***********************************************************************
* Prepare to scan parser array for Primary Key. *
***********************************************************************
SY_0048 DS 0H
L R4,PA_LEN Load parser array length
L R5,PA_ADDR Load parser array address
USING PA_DSECT,R5 ... tell assembler
LA R6,E_PA Load parser array entry length
***********************************************************************
* Scan parser array for Primary Key *
***********************************************************************
SY_0050 DS 0H
CLC P_ID,PD_ONE Primary key?
BC B'1000',SY_0060 ... yes, GET the primary key
LA R5,0(R6,R5) Point to next PA entry
SR R4,R6 Subtract field entry length
BC B'0011',SY_0050 Continue scan until EOT
BC B'1111',ER_40001 EOT, STATUS(400)
***********************************************************************
* Issue GET CONTAINER for Primary Column Index *
***********************************************************************
SY_0060 DS 0H
MVC PI_TYPE,P_TYPE Move field type
MVC PI_LEN,P_LEN Move field length
MVC PI_COL,P_COL Move field column
*
ZAP W_LENGTH,P_LEN Move field length to work area
CVB R1,W_LENGTH Convert to binary
ST R1,C_LENGTH Move field length
MVC C_NAME,P_NAME Move container name
*
STH R1,ZP_KEY_L Move primary key length
MVC ZP_NAME,P_NAME Move primary key name
*
BAS R14,GC_0010 Issue GET CONTAINER
*
ST R1,FD_ADDR Save field data address
MVC FD_LEN,C_LENGTH Move field data length
***********************************************************************
* Determine Primary Index field type and branch accordingly. *
***********************************************************************
SY_0070 DS 0H
OI PI_TYPE,X'40' Set upper case bit
CLI PI_TYPE,C'N' Numeric?
BC B'1000',SY_0090 ... yes, set key accordingly
BC B'1111',SY_0080 ... no, set key accordingly
***********************************************************************
* Set key as character. *
***********************************************************************
SY_0080 DS 0H
ZAP W_LENGTH,PI_LEN Move PA length to work area
CVB R6,W_LENGTH Convert to binary
MVI WK_KEY,X'40' Set first byte of key to space
LR R1,R6 Load PI field length
S R1,=F'1' Subtract one for space
S R1,=F'1' Subtract one for EX MVC
LA R14,WK_KEY Load target field address
LA R14,1(,R14) Point past space
LA R15,WK_KEY Load source field address
EX R1,MVC_0080 Execute MVC instruction
*
L R1,FD_LEN Load field data length
S R1,=F'1' Subtract one for EX MVC
LA R14,WK_KEY Load FAxxKEY key address
L R15,FD_ADDR Load field data address
EX R1,MVC_0081 Execute MVC instruction
*
BC B'1111',SY_0100 Read FAxxKEY
MVC_0080 MVC 0(0,R14),0(R15) Initial with spaces
MVC_0081 MVC 0(0,R14),0(R15) Move PI to key
***********************************************************************
* Set key as numeric. *
***********************************************************************
SY_0090 DS 0H
ZAP W_LENGTH,PI_LEN Move PA length to work area
CVB R6,W_LENGTH Convert to binary
MVI WK_KEY,X'F0' Set first byte of key to zero
LR R1,R6 Load PI field length
S R1,=F'1' Subtract one for zero
S R1,=F'1' Subtract one for EX MVC
LA R14,WK_KEY Load target field address
LA R14,1(,R14) Point past zero
LA R15,WK_KEY Load source field address
EX R1,MVC_0090 Execute MVC instruction
*
L R1,FD_LEN Load field data length
SR R6,R1 Subtract PI from maximum
*
S R1,=F'1' Subtract one for EX MVC
LA R14,WK_KEY Load FAxxKEY key address
LA R14,0(R6,R14) Adjust for field length
L R15,FD_ADDR Load field data address
EX R1,MVC_0091 Execute MVC instruction
*
BC B'1111',SY_0100 Read FAxxKEY
MVC_0090 MVC 0(0,R14),0(R15) Initial with zeroes
MVC_0091 MVC 0(0,R14),0(R15) Move PI to key
***********************************************************************
* Issue READ for FAxxKEY using Primary Column Index. *
***********************************************************************
SY_0100 DS 0H
LA R1,E_DK Load KEY record length
STH R1,WK_LEN Save KEY record length
BAS R14,FK_0010 Issue READ for KEY structure
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ER_20401 ... no, STATUS(204)
ST R10,FK_ADDR Save KEY buffer address
MVC FK_LEN,WK_LEN Save KEY buffer length
USING DK_DSECT,R10 ... tell assembler
***********************************************************************
* Issue READ for FAxxFILE using Primary Column Index. *
***********************************************************************
SY_0110 DS 0H
DROP R10 ... tell assembler
L R5,PA_ADDR Load parser array address
MVC WF_LEN,S_DF_LEN Move FILE record length
MVC WF_SEG,P_SEG Set segment number
BAS R14,FF_0010 Issue READ for FILE structure
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ER_20402 ... no, STATUS(204)
ST R10,FF_ADDR Save FILE buffer address
USING DF_DSECT,R10 ... tell assembler
MVC FF_LEN,WF_LEN Save FILE buffer length
LA R1,DF_DATA Load data portion
ST R1,W_FF_A Save data portion
***********************************************************************
***********************************************************************
SY_0120 DS 0H
***********************************************************************
***********************************************************************
SY_0130 DS 0H
***********************************************************************
* Prepare to scan parser array for secondary column index fields. *
***********************************************************************
SY_0140 DS 0H
DROP R5 ... tell assembler
L R8,PA_LEN Load parser array length
L R9,PA_ADDR Load parser array address
USING PA_DSECT,R9 ... tell assembler
***********************************************************************
* Scan Parser Array for field definitions. *
***********************************************************************
SY_0150 DS 0H
CLC P_ID,PD_ONE Primary index?
BC B'1000',SY_0160 ... yes, get next entry
CLC P_ID,PD_NINES Entry already processed?
BC B'1000',SY_0160 ... yes, get next entry
BC B'1111',SY_0170 ... no, check HI/LO range
***********************************************************************
* Adjust Parser Array address and length *
***********************************************************************
SY_0160 DS 0H
LA R1,E_PA Load parser array entry length
LA R9,0(R1,R9) Point to next PA entry
SR R8,R1 Subtract PA entry length
BC B'0011',SY_0150 Continue when more entries
BC B'1111',SY_0250 Scan PA for unprocessed entries
***********************************************************************
* Check column number for HI/LO range for current segment *
***********************************************************************
SY_0170 DS 0H
MVC W_ID,P_ID Save Parser Array column ID
ZAP W_COLUMN,P_COL Move PA column to work area
CVB R1,W_COLUMN Load in R1
C R1,W_HI Is column beyond segment range?
BC B'0011',SY_0160 ... yes, get next PA entry
C R1,W_LO Is column before segment range?
BC B'0100',SY_0160 ... yes, get next PA entry
*
MVC P_ID,PD_NINES Mark field as processed
*
***********************************************************************
* Calculate relative offset from current segment. *
* *
* To calculate relative offset from current segment: *
* 1). Subtract 1 from current segment number, giving the *
* relative segment number. *
* 2). Multiple relative segment number by 32,000 giving the *
* segment displacement. *
* 3). Subtract segment displacement from column number giving *
* relative displacement. *
* *
* For example, column 50 would be calculated as such: *
* 1). Subtract 1 from current segment. Segment 1 will contain *
* columns 1 thru 32,000. So for column 50, the relative segment *
* number for step 1 would be zero. *
* 2). Multiply relative segment zero by 32,000 giving segment *
* displacement, which in this case is zero. *
* 3). Subtract segment displacement from the column, which in this *
* case is 50, giving the relative displacement of 50. *
* *
* Another example, column 64,075 would be calculated as such: *
* 1). Subtract 1 from current segment. Segment 3 will contain *
* columns 64,001 thru 96,000, so for column 64,075 the relative *
* segment for step 1 would be two. *
* 2). Multiply relative segment two by 32,000, giving segment *
* displacement, which in this case would be 64,000. *
* 3). Subtract segment displacement from the column, which in this *
* case would be 64,000 from 64,075 resulting in a relative *
* displacement of 75 *
* *
***********************************************************************
SY_0180 DS 0H
XR R6,R6 Clear R6
* LH R7,DF_SEG Load segment number
LH R7,W_SEG Load current segment number
S R7,=F'1' Get relative segment number
M R6,S_32K Multiply by max segment size
* ... giving segment displacement
ZAP W_COLUMN,P_COL Load column number
CVB R1,W_COLUMN Convert from PD to binary
SR R1,R7 Subtract segment displacement
* ... giving relative displacement
S R1,=F'1' ... then make relative to zero
ST R1,W_REL_D Save relative displacement
*
ZAP W_LENGTH,P_LEN Set source length
XC SI_FIELD,SI_FIELD Clear Secondary Index field
LA R4,SI_FIELD Load Secondary Index field
ST R4,SI_PTR Save as Secondary Index pointer
*
***********************************************************************
* Calculate width to determine if field spans a segment. *
***********************************************************************
SY_0185 DS 0H
L R1,W_REL_D Load relative displacement
CVB R6,W_LENGTH Convert length to binary
AR R6,R1 Add relative displacement
ST R6,W_WIDTH Save field width
C R6,S_32K Wider than 32K?
BC B'0011',SY_0200 ... yes, spanned segment
***********************************************************************
* Move field to Secondary Index field. *
***********************************************************************
SY_0190 DS 0H
STM 0,15,REGSAVE Save registers
CVB R7,W_LENGTH Set source length
L R1,W_REL_D Load relative displacement
L R6,W_FF_A Set source address
LA R6,0(R1,R6) Add relative displacement
LR R5,R7 Set target length
*
L R4,SI_PTR Set target address
*
MVCL R4,R6 Move field to Secondary Index
LM 0,15,REGSAVE Load registers
*
BC B'1111',SY_0300 Delete Secondary Column Index
***********************************************************************
* Field spans segments. *
***********************************************************************
SY_0200 DS 0H
STM 0,15,REGSAVE Save registers
L R1,W_REL_D Load relative displacement
L R6,W_WIDTH Load field width
SR R6,R1 Subtract relative displacement
ST R6,W_WIDTH Save field width
***********************************************************************
* Move spanned segment field to Secondary Index *
***********************************************************************
SY_0210 DS 0H
L R6,W_REL_D Load relative displacement
L R1,S_32K Load 32K length
SR R1,R6 Subtract relative displacement
ST R1,W_REL_L Set relative length
L R6,W_FF_A Set source address
L R15,W_REL_D Load relative displacement
LA R6,0(R15,R6) Adjust relative displacement
LR R5,R1 Set source length
LR R7,R1 Set target length
*
L R4,SI_PTR Set target address
*
MVCL R4,R6 Move field to Response Array
*
L R1,W_REL_L Load relative length
L R4,SI_PTR Load current SI pointer
LA R4,0(R1,R4) Load the new SI pointer
ST R4,SI_PTR Save the new SI pointer
*
CVB R1,W_LENGTH Convert current field length
S R1,W_REL_L Subtract relative length
CVD R1,W_LENGTH Save remaining length
*
XC W_REL_D,W_REL_D Zero relative displacement
L R1,W_WIDTH Load width
L R15,W_REL_L Load relative length
SR R1,R15 Subtract relative length
ST R1,W_WIDTH Save width
*
LH R1,WF_SEG Load segment number
LA R1,1(0,R1) Increment by one
STH R1,WF_SEG Save segment number
*
MVC WF_LEN,S_DF_LEN Move FILE record length
BAS R14,FF_0010 Issue READ for FILE structure
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ER_20403 ... no, STATUS(204)
ST R10,FF_ADDR Save FILE buffer address
USING DF_DSECT,R10 ... tell assembler
LA R1,DF_DATA Load data portion
ST R1,W_FF_A Save data portion
MVC FF_LEN,WF_LEN Save FILE buffer length
MVC SS_SEG,WF_SEG Save spanned segment number
*
CLC W_WIDTH,S_32K Width more than 32K?
BC B'0011',SY_0210 ... yes, move spanned segments
*
***********************************************************************
* Move remainder of spanned segment field to Response Array. *
***********************************************************************
SY_0220 DS 0H
L R1,W_REL_D Load relative displacement
BC B'1111',SY_0185 Move remainder to RA
***********************************************************************
* Scan parser array if there are any fields that are yet to be *
* processed. When fields in the parser array are not on the current *
* record segment, the entry is skipped requiring the parser array to *
* be scanned until all entries are tagged as processed by the '999' *
* P_ID. *
***********************************************************************
SY_0250 DS 0H
L R8,PA_LEN Load parser array length
L R9,PA_ADDR Load parser array address
LA R1,E_PA Load parser array entry length
***********************************************************************
* Search for unprocessed parser array entry *
***********************************************************************
SY_0260 DS 0H
CLC P_ID,PD_ONE Primary index?
BC B'1000',SY_0270 ... yes, continue
CLC P_ID,PD_NINES Processed entry?
BC B'1000',SY_0270 ... yes, continue
L R8,PA_LEN Load parser array length
L R9,PA_ADDR Load parser array address
*
MVC WF_LEN,S_DF_LEN Move FILE record length
MVC WF_SEG,P_SEG Set segment number
BAS R14,FF_0010 Issue READ for FILE structure
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ER_20405 ... no, STATUS(204)
ST R10,FF_ADDR Save FILE buffer address
USING DF_DSECT,R10 ... tell assembler
MVC FF_LEN,WF_LEN Save FILE buffer length
LA R1,DF_DATA Load data portion
ST R1,W_FF_A Save data portion
*
BC B'1111',SY_0300 Delete Secondary Column Index
***********************************************************************
* Check parser array entries until EOPA *
***********************************************************************
SY_0270 DS 0H
LA R9,0(R1,R9) Point to next PA entry
SR R8,R1 Subtract PA entry length
BC B'0011',SY_0260 Continue when more PA entries
BC B'1111',SY_0800 Delete Primary key/file records
*
***********************************************************************
* Create Secondary Column Index key *
***********************************************************************
SY_0300 DS 0H
XC CI_KEY,CI_KEY Clear column index key
ZAP W_LENGTH,P_LEN Move field length to work area
CVB R1,W_LENGTH Convert to binary
*
S R1,=F'1' Subtract one for EX MVC
LA R14,CI_FIELD Load FAxxCIxx key address
LA R15,SI_FIELD Load secondary index
EX R1,MVC_0300 Execute MVC instruction
*
BC B'1111',SY_0310 Delete FAxxCIxx
MVC_0300 MVC 0(0,R14),0(R15) Move secondary index key
*
***********************************************************************
* Delete Secondary Column Index *
***********************************************************************
SY_0310 DS 0H
L R10,FK_ADDR Load KEY buffer address
USING DK_DSECT,R10 ... tell assembler
*
MVC CI_FCT(8),SI_FCT Move SI FCT template
MVC CI_FCT+2(2),EIBTRNID+2 Move TrandID as SI prefix
* MVC CI_FCT(4),EIBTRNID Move TrandID as SI prefix
UNPK CI_SI,W_ID Unpack secondary index
OI CI_SI+1,X'F0' Set sign bit
*
MVC CI_NC,DK_F_NC Move named counter to key
MVC CI_IDN,DK_F_IDN Move ID number to key
*
*
EXEC CICS DELETE FILE(CI_FCT) X
RIDFLD (CI_KEY) X
NOHANDLE
*
BC B'1111',SY_0140 Process parser array
*
***********************************************************************
* Delete Primary Key and File records. *
***********************************************************************
SY_0800 DS 0H
L R10,FK_ADDR Load KEY buffer address
USING DK_DSECT,R10 ... tell assembler
EXEC CICS DELETE FILE(WK_FCT) X
RIDFLD(DK_KEY) X
NOHANDLE
*
DROP R10 ... tell assembler
L R10,FF_ADDR Load KEY buffer address
USING DF_DSECT,R10 ... tell assembler
MVC WF_TRAN,=C'FA' Move FILE prefix
MVC WF_TRAN+2(2),EIBTRNID+2 Move FILE structure ID
* MVC WF_TRAN,EIBTRNID Move FILE structure ID
EXEC CICS DELETE FILE(WF_FCT) X
RIDFLD(WF_KEY) X
KEYLENGTH(S_GEN_L) X
GENERIC X
NOHANDLE
*
*
BAS R14,ZR_0010 zFAM replication when enabled
BAS R14,WS_0010 Issue WEB SEND
BC B'1111',RETURN Return to CICS
*
***********************************************************************
* Return to caller *
**********************************************************************
RETURN DS 0H
EXEC CICS RETURN
*
***********************************************************************
* Issue GET CONTAINER (SET Register) *
* This is used for Parser Array, Primary Index and individual fields *
***********************************************************************
GC_0010 DS 0H
ST R14,BAS_REG Save return register
*
EXEC CICS GET CONTAINER(C_NAME) X
SET(R1) X
FLENGTH(C_LENGTH) X
CHANNEL(C_CHAN) X
RESP (C_RESP) X
NOHANDLE
*
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
*
***********************************************************************
* Issue GETMAIN for Response Array *
***********************************************************************
GM_0010 DS 0H
ST R14,BAS_REG Save return register
*
EXEC CICS GETMAIN X
SET(R9) X
FLENGTH(C_LENGTH) X
INITIMG(HEX_00) X
NOHANDLE
*
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
***********************************************************************
* Issue READ for FAxxKEY structure *
***********************************************************************
FK_0010 DS 0H
ST R14,BAS_REG Save return register
MVC WK_FCT(08),SK_FCT Move KEY structure name
MVC WK_TRAN(2),=C'FA' Move KEY structure ID
MVC WK_TRAN+2(2),EIBTRNID+2 Move KEY structure ID
* MVC WK_TRAN,EIBTRNID Move KEY structure ID
*
EXEC CICS READ FILE(WK_FCT) X
SET(R10) X
RIDFLD (WK_KEY) X
LENGTH (WK_LEN) X
NOHANDLE
*
USING DK_DSECT,R10 ... tell assembler
*
MVC WF_DD,DK_DD Move FILE structure name
MVC WF_IDN,DK_F_IDN Move FILE IDN
MVC WF_NC,DK_F_NC Move FILE NC
*
DROP R10 ... tell assembler
*
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
***********************************************************************
* Issue READ for FAxxFILE structure *
* When the spanned segment number is equal to the WF_SEG, then the *
* segment has already been read during spanned segment processing. *
***********************************************************************
FF_0010 DS 0H
ST R14,BAS_REG Save return register
*
CLC SS_SEG,WF_SEG Segment numbers equal?
BC B'1000',FF_0020 ... yes, record is in the buffer
*
MVC WF_TRAN(2),=C'FA' Move FILE structure ID
MVC WF_TRAN+2(2),EIBTRNID+2 Move FILE structure ID
* MVC WF_TRAN,EIBTRNID Move FILE structure ID
*
EXEC CICS READ FILE(WF_FCT) X
SET(R10) X
RIDFLD (WF_KEY) X
LENGTH (WF_LEN) X
NOHANDLE
*
USING DF_DSECT,R10 ... tell assembler
*
MVC W_SEG,DF_SEG Save segment number
LH R1,DF_SEG Load segment number
XR R6,R6 Clear R6
L R7,S_32K Load maximum segment size
MR R6,R1 Create Column HI range
ST R7,W_HI Save as segment HI range
S R7,S_32K Subtract segment size
A R7,=F'1' Add one to create segment LO
ST R7,W_LO Save as segment LO range
*
FF_0020 DS 0H
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
DROP R10 ... tell assembler
*
***********************************************************************
* Issue REWRITE for FAxxFILE structure. *
***********************************************************************
FF_0030 DS 0H
ST R14,BAS_REG Save return register
*
L R10,FF_ADDR Load FAxxFILE record buffer
USING DF_DSECT,R10 ... tell assembler
*
EXEC CICS REWRITE FILE(WF_FCT) X
FROM(DF_DSECT) X
LENGTH (WF_LEN) X
NOHANDLE
*
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
DROP R10 ... tell assembler
*
***********************************************************************
* Transfer control to error logging program zFAM090 *
***********************************************************************
PC_0010 DS 0H
LA R1,E_LOG Load COMMAREA length
STH R1,L_LOG Save COMMAREA length
*
EXEC CICS XCTL PROGRAM(ZFAM090) X
COMMAREA(C_LOG) X
LENGTH (L_LOG) X
NOHANDLE
*
EXEC CICS WEB SEND X
FROM (H_CRLF) X
FROMLENGTH(H_TWO) X
ACTION (H_ACTION) X
MEDIATYPE (H_MEDIA) X
STATUSCODE(H_500) X
STATUSTEXT(H_500_T) X
STATUSLEN (H_500_L) X
SRVCONVERT X
NOHANDLE
*
BC B'1111',RETURN Return (if XCTL fails)
***********************************************************************
* Send response (WEB SEND) *
***********************************************************************
WS_0010 DS 0H
ST R14,BAS_REG Save return register
*
EXEC CICS WEB SEND X
FROM (H_200_T) X
FROMLENGTH(H_200_L) X
ACTION (H_ACTION) X
MEDIATYPE (H_MEDIA) X
STATUSCODE(H_200) X
STATUSTEXT(H_200_T) X
STATUSLEN (H_200_L) X
SRVCONVERT X
NOHANDLE
*
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
***********************************************************************
* Issue TRACE command. *
***********************************************************************
TR_0010 DS 0H
ST R14,BAS_REG Save return register
STM 0,15,REGSAVE Save registers
*
* BC B'1111',TR_0020 Bypass trace
*
EXEC CICS ENTER TRACENUM(T_46) X
FROM(W_46_M) X
FROMLENGTH(T_LEN) X
RESOURCE(T_RES) X
NOHANDLE
*
TR_0020 DS 0H
LM 0,15,REGSAVE Load registers
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
***********************************************************************
* zFAM Replication - start *
***********************************************************************
ZR_0010 DS 0H
ST R14,BAS_REG Save return register
*
***********************************************************************
* Retrieve Data Center document template *
***********************************************************************
ZR_0020 DS 0H
MVC DC_LEN,DC_DT_L Set document length
MVC DC_TRAN(2),=C'FA' Set document TransID
MVC DC_TRAN+2(2),EIBTRNID+2 Set document TransID
* MVC DC_TRAN,EIBTRNID Set document TransID
MVC DC_TYPE,=C'DC' Set document type
MVI DC_SPACE,X'40' Set first byte
MVC DC_SPACE+1(41),DC_SPACE Set remainder of bytes
*
EXEC CICS DOCUMENT CREATE DOCTOKEN(DC_TOKEN) X
TEMPLATE(DC_DOCT) X
RESP (DC_RESP) X
NOHANDLE
*
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ZR_0099 ... no, bypass RETRIEVE
*
EXEC CICS DOCUMENT RETRIEVE DOCTOKEN(DC_TOKEN) X
INTO (DC_REC) X
LENGTH (DC_LEN) X
MAXLENGTH(DC_LEN) X
RESP (DC_RESP) X
DATAONLY X
NOHANDLE
*
OC EIBRESP,EIBRESP Normal response?
BC B'0111',ZR_0099 ... no, bypass zFAM102
*
CLC DC_ENV,ZP_AS Active/Standby environment?
BC B'0111',ZR_0099 ... no, bypass zFAM102
*
***********************************************************************
* LINK to zFAM replication program zFAM102 (Query Mode) *
***********************************************************************
ZR_0030 DS 0H
MVC ZP_TYPE,ZP_DEL Move DELETE replication type
MVC ZP_KEY,WK_KEY Move primary key
LA R1,ZP_L Load DFHCOMMAREA length
STH R1,ZP_LEN Save DFHCOMMAREA length
*
EXEC CICS LINK X
PROGRAM (ZFAM102) X
COMMAREA(ZP_COMM) X
LENGTH (ZP_LEN) X
NOHANDLE
*
***********************************************************************
* zFAM Replication - end *
***********************************************************************
ZR_0099 DS 0H
L R14,BAS_REG Load return register
BCR B'1111',R14 Return to caller
*
DS 0F
ZFAM102 DC CL08'ZFAM102 ' Replication program
ZP_CRE DC CL06'CREATE' CREATE replication type
ZP_UPD DC CL06'UPDATE' UPDATE replication type
ZP_DEL DC CL06'DELETE' DELETE replication type
*
ZP_AA DC CL02'AA' Active/Active environment
ZP_AS DC CL02'AS' Active/Standby environment
ZP_A1 DC CL02'A1' Active/Single environment
*
DC_DT_L DC F'00172' FAxxDC Document template length
*
***********************************************************************
* STATUS(204) *
***********************************************************************
ER_20401 DS 0H
MVC C_STATUS,S_204 Set STATUS
MVC C_REASON,=C'01' Set REASON
BC B'1111',PC_0010 Transfer control to logging
***********************************************************************
* STATUS(204) *
***********************************************************************
ER_20402 DS 0H
MVC C_STATUS,S_204 Set STATUS
MVC C_REASON,=C'02' Set REASON
BC B'1111',PC_0010 Transfer control to logging
***********************************************************************
* STATUS(204) *
***********************************************************************
ER_20403 DS 0H
MVC C_STATUS,S_204 Set STATUS
MVC C_REASON,=C'03' Set REASON
BC B'1111',PC_0010 Transfer control to logging
***********************************************************************
* STATUS(204) *
***********************************************************************
ER_20404 DS 0H
MVC C_STATUS,S_204 Set STATUS
MVC C_REASON,=C'04' Set REASON
BC B'1111',PC_0010 Transfer control to logging
***********************************************************************
* STATUS(204) *
***********************************************************************
ER_20405 DS 0H
MVC C_STATUS,S_204 Set STATUS
MVC C_REASON,=C'05' Set REASON
BC B'1111',PC_0010 Transfer control to logging
***********************************************************************
* STATUS(400) *
***********************************************************************
ER_40001 DS 0H
MVC C_STATUS,S_400 Set STATUS
MVC C_REASON,=C'01' Set REASON
BC B'1111',PC_0010 Transfer control to logging
*
***********************************************************************
* Define Constant fields *
***********************************************************************
*
DS 0F
HEX_00 DC XL01'00' Nulls
DS 0F
HEX_40 DC 16XL01'40' Spaces
DS 0F
S_204 DC CL03'204' HTTP STATUS(204)
DS 0F
S_400 DC CL03'400' HTTP STATUS(400)
DS 0F
ONE DC F'1' One
FIVE DC F'5' Five
S_OT_LEN DC F'80' OPTIONS table maximum length
S_PA_LEN DC F'8192' Parser Array maximum length
S_FD_LEN DC F'65000' Field Define maximum length
DS 0F
S_DF_LEN DC H'32700' FAxxFILE maximum length
DS 0F
S_32K DC F'32000' Maximum segment length
DS 0F
S_GEN_L DC H'8' Generic keylength for DELETE
DS 0F
PD_ZERO DC XL02'000F' Packed decimal zeroes
PD_ONE DC XL02'001F' Packed decimal zeroes
PD_NINES DC XL02'999F' Packed decimal nines
ZD_ZERO DC CL05'00000' Zoned decimal 00000
ZD_ONE DC CL04'0001' Zoned decimal 0001
DS 0F
ZFAM090 DC CL08'ZFAM090 ' zFAM Logging and error program
SK_FCT DC CL08'FAxxKEY ' zFAM KEY structure
SF_FCT DC CL08'FAxxFILE' zFAM FILE structure
SI_FCT DC CL08'FAxxCIxx' zFAM CI structure
C_CHAN DC CL16'ZFAM-CHANNEL ' zFAM channel
C_OPTION DC CL16'ZFAM-OPTIONS ' OPTIONS container
C_TTL DC CL16'ZFAM-TTL ' TTL container
C_ARRAY DC CL16'ZFAM-ARRAY ' ARRAY container
C_FAXXFD DC CL16'ZFAM-FAXXFD ' Field description document
DS 0F
***********************************************************************
* HTTP resources *
***********************************************************************
H_TWO DC F'2' Length of CRLF
H_CRLF DC XL02'0D25' Carriage Return Line Feed
H_500 DC H'500' HTTP STATUS(500)
H_500_L DC F'48' HTTP STATUS TEXT Length
H_500_T DC CL16'03 Service unava' HTTP STATUS TEXT Length
DC CL16'ilable and loggi' ... continued
DC CL16'ng disabled ' ... and complete
DS 0F
H_200 DC H'200' HTTP STATUS(200)
H_200_L DC F'32' HTTP STATUS TEXT Length
H_200_T DC CL16'00 Request succe' HTTP STATUS TEXT Length
DC CL16'ssful. ' ... continued
DS 0F
H_ACTION DC F'02' HTTP SEND ACTION(IMMEDIATE)
H_MEDIA DC CL56'text/plain' HTTP Media type
DS 0F
***********************************************************************
* Trace resources *
***********************************************************************
T_46 DC H'46' Trace number
T_RES DC CL08'ZFAM040 ' Trace resource
T_LEN DC H'08' Trace resource length
*
***********************************************************************
* Literal Pool *
***********************************************************************
LTORG
*
*
***********************************************************************
* Register assignment *
***********************************************************************
DS 0F
R0 EQU 0
R1 EQU 1
R2 EQU 2
R3 EQU 3
R4 EQU 4
R5 EQU 5
R6 EQU 6
R7 EQU 7
R8 EQU 8
R9 EQU 9
R10 EQU 10
R11 EQU 11
R12 EQU 12
R13 EQU 13
R14 EQU 14
R15 EQU 15
*
PRINT ON
***********************************************************************
* End of Program - ZFAM040 *
**********************************************************************
END ZFAM040 |
#include <code/include/CustomView.hpp>
#include <code/include/Game.hpp>
#include <QDebug>
#include <QScrollBar>
CustomView::CustomView(QGraphicsScene *scene, QWidget *parent)
: QGraphicsView(scene, parent)
{
setTransformationAnchor(QGraphicsView::NoAnchor);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//showFullScreen();
}
void CustomView::enableMouseMovement(){
cameraEnabled = true;
connect(Game::game().gameTimer, &QTimer::timeout, this, &CustomView::cameraMoveTick);
}
void CustomView::mouseMoveEvent(QMouseEvent* event) {
if(!cameraEnabled) return;
const QRect& windowRect = geometry();
qint32 mouseXPos = event->x();
qint32 mouseYPos = event->y();
qint32 cameraEdgeOffset = Game::game().tileWidth*2;
qint32 right = windowRect.width();
qint32 bottom = windowRect.height();
if(!animatingCameraMovement) {
if(mouseXPos >= right-cameraEdgeOffset) {
animateCamera(CameraDir::EAST);
} else if (mouseXPos <= 0+cameraEdgeOffset) {
animateCamera(CameraDir::WEST);
} else if (mouseYPos <= 0+cameraEdgeOffset) {
animateCamera(CameraDir::NORTH);
} else if (mouseYPos >= bottom-cameraEdgeOffset) {
animateCamera(CameraDir::SOUTH);
}
} else {
if(mouseXPos <= right-cameraEdgeOffset &&
mouseXPos >= 0+cameraEdgeOffset &&
mouseYPos >= 0+cameraEdgeOffset &&
mouseYPos <= bottom-cameraEdgeOffset) {
animatingCameraMovement = false;
}
}
event->accept();
QGraphicsView::mouseMoveEvent(event);
}
void CustomView::leaveEvent(QEvent *event) {
const QRect& windowRect = geometry();
QPoint mousePosition = QCursor::pos();
qint32 x = qBound(windowRect.left(), mousePosition.x(), windowRect.right());
qint32 y = qBound(windowRect.top(), mousePosition.y(), windowRect.bottom());
if(x != mousePosition.x() || y != mousePosition.y())
QCursor::setPos(x, y);
event->accept();
QGraphicsView::leaveEvent(event);
}
void CustomView::keyPressEvent(QKeyEvent *event) {
// Options window (quits the game atm)
if(event->key() == Qt::Key_Escape) {
Game::game().getGameApp()->quit();
}
if(event->key() == Qt::Key_S) {
Game::game().saveScore();
}
// Zoom controls
// TODO: animate this, and add it to mouseWheel event aswell
else if(event->key() == Qt::Key_Plus) {
scale(2, 2);
scaleScores(0.5);
adjustScores();
}
else if(event->key() == Qt::Key_Minus) {
scale(0.5, 0.5);
scaleScores(2);
adjustScores();
}
// Camera controls
else
if(!animatingCameraMovement && cameraEnabled) {
if(event->key() == Qt::Key_Right) {
animateCamera(CameraDir::EAST);
} else if(event->key() == Qt::Key_Left) {
animateCamera(CameraDir::WEST);
} else if(event->key() == Qt::Key_Up) {
animateCamera(CameraDir::NORTH);
} else if(event->key() == Qt::Key_Down) {
animateCamera(CameraDir::SOUTH);
}
}
}
void CustomView::keyReleaseEvent(QKeyEvent* event) {
if(event->key() == Qt::Key_Right ||
event->key() == Qt::Key_Left ||
event->key() == Qt::Key_Up ||
event->key() == Qt::Key_Down) {
animatingCameraMovement = false;
}
}
void CustomView::animateCamera(const CustomView::CameraDir &dir) {
if(animatingCameraMovement)
return;
if(dir == CameraDir::EAST) {
yOffset = 0;
xOffset = defaultOffset;
} else if(dir == CameraDir::WEST) {
xOffset = -defaultOffset;
yOffset = 0;
} else if(dir == CameraDir::NORTH) {
yOffset = -defaultOffset;
xOffset = 0;
} else if(dir == CameraDir::SOUTH) {
yOffset = defaultOffset;
xOffset = 0;
}
animatingCameraMovement = true;
}
void CustomView::cameraMoveTick() {
if(!animatingCameraMovement) return;
translate(-xOffset, -yOffset);
//Jako ratchet resenje da fiksiram poene gde treba
//Bez da menjam klasu koju je neko vec uradio
//bozemiteprosti
adjustScores();
/*horizontalScrollBar()->setValue( horizontalScrollBar()->value() + xOffset);
verticalScrollBar()->setValue( verticalScrollBar()->value() + yOffset);*/
}
//When camera moves move the scores so that they are always on top right
void CustomView::adjustScores(){
QPointF pos = this->mapToScene(0, 0);
qreal currScale = Game::game().health->scale();
Game::game().gold->setPos(pos.x(), pos.y());
Game::game().health->setPos(pos.x(), pos.y()+(20*currScale));
Game::game().score->setPos(pos.x(), pos.y()+ (40*currScale));
}
//If theres is a zoom then set scaling of scores
void CustomView::scaleScores(qreal x){
Game::game().health->setScale(
Game::game().health->scale()*x
);
Game::game().score->setScale(
Game::game().score->scale()*x
);
Game::game().gold->setScale(
Game::game().gold->scale()*x
);
}
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld c, 41
ld b, 02
ld d, 03
lbegin_waitm2:
ldff a, (c)
and a, d
cmp a, b
jrnz lbegin_waitm2
ld a, 08
ldff(c), a
ld a, 02
ldff(ff), a
ei
ld c, 0f
.text@1000
lstatint:
xor a, a
ldff(41), a
.text@113b
ld a, 08
ldff(41), a
ldff a, (c)
and a, 03
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
object_const_def ; object_event constants
const BATTLETOWER1F_RECEPTIONIST
const BATTLETOWER1F_YOUNGSTER
const BATTLETOWER1F_COOLTRAINER_F
const BATTLETOWER1F_BUG_CATCHER
const BATTLETOWER1F_GRANNY
BattleTower1F_MapScripts:
db 2 ; scene scripts
scene_script .Scene0 ; SCENE_DEFAULT
scene_script .Scene1 ; SCENE_FINISHED
db 0 ; callbacks
.Scene0:
setval BATTLETOWERACTION_CHECKSAVEFILEISYOURS
special BattleTowerAction
iffalse .SkipEverything
setval BATTLETOWERACTION_GET_CHALLENGE_STATE ; readmem sBattleTowerChallengeState
special BattleTowerAction
ifequal $0, .SkipEverything
ifequal $2, .LeftWithoutSaving
ifequal $3, .SkipEverything
ifequal $4, .SkipEverything
opentext
writetext Text_WeveBeenWaitingForYou
waitbutton
closetext
prioritysjump Script_ResumeBattleTowerChallenge
end
.LeftWithoutSaving
prioritysjump BattleTower_LeftWithoutSaving
setval BATTLETOWERACTION_CHALLENGECANCELED
special BattleTowerAction
setval BATTLETOWERACTION_06
special BattleTowerAction
.SkipEverything:
setscene SCENE_FINISHED
.Scene1:
end
BattleTower1FRulesSign:
opentext
writetext Text_ReadBattleTowerRules
yesorno
iffalse .skip
writetext Text_BattleTowerRules
waitbutton
.skip:
closetext
end
BattleTower1FReceptionistScript:
setval BATTLETOWERACTION_GET_CHALLENGE_STATE ; readmem sBattleTowerChallengeState
special BattleTowerAction
ifequal $3, Script_BeatenAllTrainers2 ; maps/BattleTowerBattleRoom.asm
opentext
writetext Text_BattleTowerWelcomesYou
buttonsound
setval BATTLETOWERACTION_CHECK_EXPLANATION_READ ; if new save file: bit 1, [sBattleTowerSaveFileFlags]
special BattleTowerAction
ifnotequal $0, Script_Menu_ChallengeExplanationCancel
sjump Script_BattleTowerIntroductionYesNo
Script_Menu_ChallengeExplanationCancel:
writetext Text_WantToGoIntoABattleRoom
setval TRUE
special Menu_ChallengeExplanationCancel
ifequal 1, Script_ChooseChallenge
ifequal 2, Script_BattleTowerExplanation
sjump Script_BattleTowerHopeToServeYouAgain
Script_ChooseChallenge:
setval BATTLETOWERACTION_RESETDATA ; ResetBattleTowerTrainerSRAM
special BattleTowerAction
special CheckForBattleTowerRules
ifnotequal FALSE, Script_WaitButton
writetext Text_SaveBeforeEnteringBattleRoom
yesorno
iffalse Script_Menu_ChallengeExplanationCancel
setscene SCENE_DEFAULT
special TryQuickSave
iffalse Script_Menu_ChallengeExplanationCancel
setscene SCENE_FINISHED
setval BATTLETOWERACTION_SET_EXPLANATION_READ ; set 1, [sBattleTowerSaveFileFlags]
special BattleTowerAction
special BattleTowerRoomMenu
ifequal $a, Script_Menu_ChallengeExplanationCancel
ifnotequal $0, Script_MobileError
setval BATTLETOWERACTION_11
special BattleTowerAction
writetext Text_RightThisWayToYourBattleRoom
waitbutton
closetext
setval BATTLETOWERACTION_CHOOSEREWARD
special BattleTowerAction
sjump Script_WalkToBattleTowerElevator
Script_ResumeBattleTowerChallenge:
closetext
setval BATTLETOWERACTION_LOADLEVELGROUP ; load choice of level group
special BattleTowerAction
Script_WalkToBattleTowerElevator:
musicfadeout MUSIC_NONE, 8
setmapscene BATTLE_TOWER_BATTLE_ROOM, SCENE_DEFAULT
setmapscene BATTLE_TOWER_ELEVATOR, SCENE_DEFAULT
setmapscene BATTLE_TOWER_HALLWAY, SCENE_DEFAULT
follow BATTLETOWER1F_RECEPTIONIST, PLAYER
applymovement BATTLETOWER1F_RECEPTIONIST, MovementData_BattleTower1FWalkToElevator
setval BATTLETOWERACTION_0A
special BattleTowerAction
warpsound
disappear BATTLETOWER1F_RECEPTIONIST
stopfollow
applymovement PLAYER, MovementData_BattleTowerHallwayPlayerEntersBattleRoom
warpcheck
end
Script_GivePlayerHisPrize:
setval BATTLETOWERACTION_1C
special BattleTowerAction
setval BATTLETOWERACTION_GIVEREWARD
special BattleTowerAction
ifequal POTION, Script_YourPackIsStuffedFull
getitemname STRING_BUFFER_4, USE_SCRIPT_VAR
giveitem ITEM_FROM_MEM, 5
writetext Text_PlayerGotFive
setval BATTLETOWERACTION_1D
special BattleTowerAction
closetext
end
Script_YourPackIsStuffedFull:
writetext Text_YourPackIsStuffedFull
waitbutton
closetext
end
Script_BattleTowerIntroductionYesNo:
writetext Text_WouldYouLikeToHearAboutTheBattleTower
yesorno
iffalse Script_BattleTowerSkipExplanation
Script_BattleTowerExplanation:
writetext Text_BattleTowerIntroduction_2
Script_BattleTowerSkipExplanation:
setval BATTLETOWERACTION_SET_EXPLANATION_READ
special BattleTowerAction
sjump Script_Menu_ChallengeExplanationCancel
Script_BattleTowerHopeToServeYouAgain:
writetext Text_WeHopeToServeYouAgain
waitbutton
closetext
end
UnreferencedScript_0x9e4b6:
special BattleTowerMobileError
closetext
end
Script_WaitButton:
waitbutton
closetext
end
UnreferencedScript_0x9e4be:
writetext Text_SaveBeforeEnteringBattleRoom
yesorno
iffalse Script_Menu_ChallengeExplanationCancel
special TryQuickSave
iffalse Script_Menu_ChallengeExplanationCancel
setval BATTLETOWERACTION_SET_EXPLANATION_READ
special BattleTowerAction
special Function1700ba
ifequal $a, Script_Menu_ChallengeExplanationCancel
ifnotequal $0, Script_MobileError
writetext Text_ReceivedAListOfLeadersOnTheHonorRoll
turnobject BATTLETOWER1F_RECEPTIONIST, LEFT
writetext Text_PleaseConfirmOnThisMonitor
waitbutton
turnobject BATTLETOWER1F_RECEPTIONIST, DOWN
closetext
end
UnreferencedScript_0x9e4ea:
setval BATTLETOWERACTION_LEVEL_CHECK
special BattleTowerAction
ifnotequal $0, Script_AMonLevelExceeds
setval BATTLETOWERACTION_UBERS_CHECK
special BattleTowerAction
ifnotequal $0, Script_MayNotEnterABattleRoomUnderL70
special CheckForBattleTowerRules
ifnotequal FALSE, Script_WaitButton
setval BATTLETOWERACTION_05
special BattleTowerAction
ifequal $0, .zero
writetext Text_CantBeRegistered_PreviousRecordDeleted
sjump continue
.zero
writetext Text_CantBeRegistered
continue:
yesorno
iffalse Script_Menu_ChallengeExplanationCancel
writetext Text_SaveBeforeReentry
yesorno
iffalse Script_Menu_ChallengeExplanationCancel
setscene SCENE_DEFAULT
special TryQuickSave
iffalse Script_Menu_ChallengeExplanationCancel
setscene SCENE_FINISHED
setval BATTLETOWERACTION_06
special BattleTowerAction
setval BATTLETOWERACTION_12
special BattleTowerAction
writetext Text_RightThisWayToYourBattleRoom
waitbutton
sjump Script_ResumeBattleTowerChallenge
UnreferencedScript_0x9e53b:
writetext Text_FiveDayBattleLimit_Mobile
waitbutton
sjump Script_BattleTowerHopeToServeYouAgain
Script_AMonLevelExceeds:
writetext Text_AMonLevelExceeds
waitbutton
sjump Script_Menu_ChallengeExplanationCancel
Script_MayNotEnterABattleRoomUnderL70:
writetext Text_MayNotEnterABattleRoomUnderL70
waitbutton
sjump Script_Menu_ChallengeExplanationCancel
Script_MobileError:
special BattleTowerMobileError
closetext
end
BattleTower_LeftWithoutSaving:
opentext
writetext Text_BattleTower_LeftWithoutSaving
waitbutton
sjump Script_BattleTowerHopeToServeYouAgain
BattleTower1FYoungsterScript:
faceplayer
opentext
writetext Text_BattleTowerYoungster
waitbutton
closetext
turnobject BATTLETOWER1F_YOUNGSTER, RIGHT
end
BattleTower1FCooltrainerFScript:
jumptextfaceplayer Text_BattleTowerCooltrainerF
BattleTower1FBugCatcherScript:
jumptextfaceplayer Text_BattleTowerBugCatcher
BattleTower1FGrannyScript:
jumptextfaceplayer Text_BattleTowerGranny
MovementData_BattleTower1FWalkToElevator:
step UP
step UP
step UP
step UP
step UP
MovementData_BattleTowerHallwayPlayerEntersBattleRoom:
step UP
step_end
MovementData_BattleTowerElevatorExitElevator:
step DOWN
step_end
MovementData_BattleTowerHallwayWalkTo1020Room:
step RIGHT
step RIGHT
MovementData_BattleTowerHallwayWalkTo3040Room:
step RIGHT
step RIGHT
step UP
step RIGHT
turn_head LEFT
step_end
MovementData_BattleTowerHallwayWalkTo90100Room:
step LEFT
step LEFT
MovementData_BattleTowerHallwayWalkTo7080Room:
step LEFT
step LEFT
MovementData_BattleTowerHallwayWalkTo5060Room:
step LEFT
step LEFT
step UP
step LEFT
turn_head RIGHT
step_end
MovementData_BattleTowerBattleRoomPlayerWalksIn:
step UP
step UP
step UP
step UP
turn_head RIGHT
step_end
MovementData_BattleTowerBattleRoomOpponentWalksIn:
slow_step DOWN
slow_step DOWN
slow_step DOWN
turn_head LEFT
step_end
MovementData_BattleTowerBattleRoomOpponentWalksOut:
turn_head UP
slow_step UP
slow_step UP
slow_step UP
step_end
MovementData_BattleTowerBattleRoomReceptionistWalksToPlayer:
slow_step RIGHT
slow_step RIGHT
slow_step UP
slow_step UP
step_end
MovementData_BattleTowerBattleRoomReceptionistWalksAway:
slow_step DOWN
slow_step DOWN
slow_step LEFT
slow_step LEFT
turn_head RIGHT
step_end
MovementData_BattleTowerBattleRoomPlayerTurnsToFaceReceptionist:
turn_head DOWN
step_end
MovementData_BattleTowerBattleRoomPlayerTurnsToFaceNextOpponent:
turn_head RIGHT
step_end
Text_BattleTowerWelcomesYou:
text "BATTLE TOWER"
line "welcomes you!"
para "I could show you"
line "to a BATTLE ROOM."
done
Text_WantToGoIntoABattleRoom:
text "Want to go into a"
line "BATTLE ROOM?"
done
Text_RightThisWayToYourBattleRoom:
text "Right this way to"
line "your BATTLE ROOM."
done
Text_BattleTowerIntroduction_1:
text "BATTLE TOWER is a"
line "facility made for"
cont "#MON battles."
para "Countless #MON"
line "trainers gather"
para "from all over to"
line "hold battles in"
para "specially designed"
line "BATTLE ROOMS."
para "There are many"
line "BATTLE ROOMS in"
cont "the BATTLE TOWER."
para "Each ROOM holds"
line "seven trainers."
para "If you defeat the"
line "seven in a ROOM,"
para "and you have a"
line "good record, you"
para "could become the"
line "ROOM's LEADER."
para "All LEADERS will"
line "be recorded in the"
para "HONOR ROLL for"
line "posterity."
para "You may challenge"
line "in up to five"
para "BATTLE ROOMS each"
line "day."
para "However, you may"
line "battle only once a"
para "day in any given"
line "ROOM."
para "To interrupt a"
line "session, you must"
para "SAVE. If not, you"
line "won't be able to"
para "resume your ROOM"
line "challenge."
para ""
done
Text_BattleTowerIntroduction_2:
text "BATTLE TOWER is a"
line "facility made for"
cont "#MON battles."
para "Countless #MON"
line "trainers gather"
para "from all over to"
line "hold battles in"
para "specially designed"
line "BATTLE ROOMS."
para "There are many"
line "BATTLE ROOMS in"
cont "the BATTLE TOWER."
para "Each ROOM holds"
line "seven trainers."
para "Beat them all, and"
line "win a prize."
para "To interrupt a"
line "session, you must"
para "SAVE. If not, you"
line "won't be able to"
para "resume your ROOM"
line "challenge."
para ""
done
Text_ReceivedAListOfLeadersOnTheHonorRoll:
text "Received a list of"
line "LEADERS on the"
cont "HONOR ROLL."
para ""
done
Text_PleaseConfirmOnThisMonitor:
text "Please confirm on"
line "this monitor."
done
Text_ThankYou:
text "Thank you!"
para ""
done
Text_ThanksForVisiting:
text "Thanks for"
line "visiting!"
done
Text_BeatenAllTheTrainers_Mobile:
text "Congratulations!"
para "You've beaten all"
line "the trainers!"
para "Your feat may be"
line "worth registering,"
para "<PLAYER>. With your"
line "results, you may"
para "be chosen as a"
line "ROOM LEADER."
para ""
done
Text_CongratulationsYouveBeatenAllTheTrainers:
text "Congratulations!"
para "You've beaten all"
line "the trainers!"
para "For that, you get"
line "this great prize!"
para ""
done
Text_AskRegisterRecord_Mobile:
text "Would you like to"
line "register your"
para "record with the"
line "CENTER?"
done
Text_PlayerGotFive:
text "<PLAYER> got five"
line "@"
text_ram wStringBuffer4
text "!@"
sound_item
text_waitbutton
text_end
Text_YourPackIsStuffedFull:
text "Oops, your PACK is"
line "stuffed full."
para "Please make room"
line "and come back."
done
Text_YourRegistrationIsComplete:
text "Your registration"
line "is complete."
para "Please come again!"
done
Text_WeHopeToServeYouAgain:
text "We hope to serve"
line "you again."
done
Text_PleaseStepThisWay:
text "Please step this"
line "way."
done
Text_WouldYouLikeToHearAboutTheBattleTower:
text "Would you like to"
line "hear about the"
cont "BATTLE TOWER?"
done
Text_CantBeRegistered:
text "Your record from"
line "the previous"
para "BATTLE ROOM can't"
line "be registered. OK?"
done
Text_CantBeRegistered_PreviousRecordDeleted:
text "Your record from"
line "the previous"
para "BATTLE ROOM can't"
line "be registered."
para "Also, the existing"
line "record will be"
cont "deleted. OK?"
done
Text_CheckTheLeaderHonorRoll:
text "Check the LEADER"
line "HONOR ROLL?"
done
Text_ReadBattleTowerRules:
text "BATTLE TOWER rules"
line "are written here."
para "Read the rules?"
done
Text_BattleTowerRules:
text "Three #MON may"
line "enter battles."
para "All three must be"
line "different."
para "The items they"
line "hold must also be"
cont "different."
para "Certain #MON"
line "may also have"
para "level restrictions"
line "placed on them."
done
Text_BattleTower_LeftWithoutSaving:
text "Excuse me!"
line "You didn't SAVE"
para "before exiting"
line "the BATTLE ROOM."
para "I'm awfully sorry,"
line "but your challenge"
para "will be declared"
line "invalid."
done
Text_YourMonWillBeHealedToFullHealth:
text "Your #MON will"
line "be healed to full"
cont "health."
done
Text_NextUpOpponentNo:
text "Next up, opponent"
line "no.@"
text_ram wStringBuffer3
text ". Ready?"
done
Text_SaveBeforeConnecting_Mobile:
text "Your session will"
line "be SAVED before"
para "connecting with"
line "the CENTER."
done
Text_SaveBeforeEnteringBattleRoom:
text "Before entering"
line "the BATTLE ROOM,"
para "your progress will"
line "be saved."
done
Text_SaveAndEndTheSession:
text "SAVE and end the"
line "session?"
done
Text_SaveBeforeReentry:
text "Your record will"
line "be SAVED before"
para "you go back into"
line "the previous ROOM."
done
Text_CancelYourBattleRoomChallenge:
text "Cancel your BATTLE"
line "ROOM challenge?"
done
Text_RegisterRecordOnFile_Mobile:
text "We have your"
line "previous record on"
para "file. Would you"
line "like to register"
cont "it at the CENTER?"
done
Text_WeveBeenWaitingForYou:
text "We've been waiting"
line "for you. This way"
para "to a BATTLE ROOM,"
line "please."
done
Text_FiveDayBattleLimit_Mobile:
text "You may enter only"
line "five BATTLE ROOMS"
cont "each day."
para "Please come back"
line "tomorrow."
done
Text_TooMuchTimeElapsedNoRegister:
text "Sorry, but it's"
line "not possible to"
para "register your"
line "current record at"
para "the CENTER because"
line "too much time has"
para "elapsed since the"
line "start of your"
cont "challenge."
done
; a dupe?
Text_RegisterRecordTimedOut_Mobile:
text "Sorry, but it's"
line "not possible to"
para "register your most"
line "recent record at"
para "the CENTER because"
line "too much time has"
para "elapsed since the"
line "start of your"
cont "challenge."
done
Text_AMonLevelExceeds:
text "One or more of"
line "your #MON's"
cont "levels exceeds @"
text_decimal wScriptVar, 1, 3
text "."
done
Text_MayNotEnterABattleRoomUnderL70:
text_ram wcd49
text " may not"
line "enter a BATTLE"
cont "ROOM under L70."
para "This BATTLE ROOM"
line "is for L@"
text_decimal wScriptVar, 1, 3
text "."
done
Text_BattleTowerYoungster:
text "Destroyed by the"
line "first opponent in"
para "no time at all…"
line "I'm no good…"
done
Text_BattleTowerCooltrainerF:
text "There are lots of"
line "BATTLE ROOMS, but"
para "I'm going to win"
line "them all!"
done
Text_BattleTowerGranny:
text "It's a grueling"
line "task, not being"
para "able to use items"
line "in battle."
para "Making your"
line "#MON hold items"
para "is the key to"
line "winning battles."
done
Text_BattleTowerBugCatcher:
text "I'm trying to see"
line "how far I can go"
para "using just bug"
line "#MON."
para "Don't let there be"
line "any fire #MON…"
done
BattleTower1F_MapEvents:
db 0, 0 ; filler
db 3 ; warp events
warp_event 7, 9, BATTLE_TOWER_OUTSIDE, 3
warp_event 8, 9, BATTLE_TOWER_OUTSIDE, 4
warp_event 7, 0, BATTLE_TOWER_ELEVATOR, 1
db 0 ; coord events
db 1 ; bg events
bg_event 6, 6, BGEVENT_READ, BattleTower1FRulesSign
db 5 ; object events
object_event 7, 6, SPRITE_RECEPTIONIST, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, BattleTower1FReceptionistScript, -1
object_event 14, 9, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, PAL_NPC_BROWN, OBJECTTYPE_SCRIPT, 0, BattleTower1FYoungsterScript, -1
object_event 4, 9, SPRITE_COOLTRAINER_F, SPRITEMOVEDATA_WALK_LEFT_RIGHT, 1, 0, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, BattleTower1FCooltrainerFScript, -1
object_event 1, 3, SPRITE_BUG_CATCHER, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_SCRIPT, 0, BattleTower1FBugCatcherScript, -1
object_event 14, 3, SPRITE_GRANNY, SPRITEMOVEDATA_WALK_UP_DOWN, 0, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, BattleTower1FGrannyScript, -1
|
%include '../util.asm'
default rel
section .text
global _main
;
;rótulo no código é como se fosse funçao
;rótulo na área de dados é nome de variável
;
_main: ;rotulo inicio do programa
MOV rcx, 10
inicio:
push rcx ; pois readint usa o rcx
call readint
pop rcx
; aqui compara
shr rax,1
jc imp
; qdo for par
add [contpar], byte 1
jmp depois
imp:
add [contimpar], byte 1
depois:
loop inicio
mov rdi, [contpar]
call printint
call endl
mov rdi, [contimpar]
call printint
call endl
call exit ; termina o programa
section .data ; declaração de dados
; int maior;
contpar: dq 0
contimpar: dq 0
|
TITLE DIRCALL - Directory manipulation internal calls
NAME DIRCALL
; $MKDIR
; $CHDIR
; $RMDIR
.xlist
INCLUDE DOSSEG.ASM
CODE SEGMENT BYTE PUBLIC 'CODE'
ASSUME SS:DOSGROUP,CS:DOSGROUP
.xcref
INCLUDE DOSSYM.ASM
INCLUDE DEVSYM.ASM
.cref
.list
ifndef Kanji
Kanji equ 0
endif
i_need AUXSTACK,BYTE
i_need NoSetDir,BYTE
i_need CURBUF, DWORD
i_need DIRSTART,WORD
i_need THISDPB,DWORD
i_need NAME1,BYTE
i_need LASTENT,WORD
i_need ATTRIB,BYTE
i_need THISFCB,DWORD
i_need AUXSTACK,BYTE
i_need CREATING,BYTE
i_need DRIVESPEC,BYTE
i_need ROOTSTART,BYTE
i_need SWITCH_CHARACTER,BYTE
extrn sys_ret_ok:near,sys_ret_err:near
; XENIX CALLS
BREAK <$MkDir - Make a directory entry>
MKNERRJ: JMP MKNERR
NODEEXISTSJ: JMP NODEEXISTS
procedure $MKDIR,NEAR
ASSUME DS:NOTHING,ES:NOTHING
; Inputs:
; DS:DX Points to asciz name
; Function:
; Make a new directory
; Returns:
; STD XENIX Return
; AX = mkdir_path_not_found if path bad
; AX = mkdir_access_denied If
; Directory cannot be created
; Node already exists
; Device name given
; Disk or directory(root) full
invoke validate_path
JC MKNERRJ
MOV SI,DX
MOV WORD PTR [THISFCB+2],SS
MOV WORD PTR [THISFCB],OFFSET DOSGROUP:AUXSTACK-40 ; Scratch space
MOV AL,attr_directory
MOV WORD PTR [CREATING],0E500h
invoke MAKENODE
ASSUME DS:DOSGROUP
MOV AL,mkdir_path_not_found
JC MKNERRJ
JNZ NODEEXISTSJ
LDS DI,[CURBUF]
ASSUME DS:NOTHING
SUB SI,DI
PUSH SI ; Pointer to fcb_FIRCLUS
PUSH [DI.BUFSECNO] ; Sector of new node
PUSH SS
POP DS
ASSUME DS:DOSGROUP
PUSH [DIRSTART] ; Parent for .. entry
XOR AX,AX
MOV [DIRSTART],AX ; Null directory
invoke NEWDIR
JC NODEEXISTSPOPDEL ; No room
invoke GETENT ; First entry
LES DI,[CURBUF]
MOV ES:[DI.BUFDIRTY],1
ADD DI,BUFINSIZ ; Point at buffer
MOV AX,202EH ; ". "
STOSW
MOV DX,[DIRSTART] ; Point at itself
invoke SETDOTENT
MOV AX,2E2EH ; ".."
STOSW
POP DX ; Parent
invoke SETDOTENT
LES BP,[THISDPB]
POP DX ; Entry sector
XOR AL,AL ; Pre read
invoke GETBUFFR
MOV DX,[DIRSTART]
LDS DI,[CURBUF]
ASSUME DS:NOTHING
ZAPENT:
POP SI ; fcb_Firclus pointer
ADD SI,DI
MOV [SI],DX
XOR DX,DX
MOV [SI+2],DX
MOV [SI+4],DX
DIRUP:
MOV [DI.BUFDIRTY],1
PUSH SS
POP DS
ASSUME DS:DOSGROUP
MOV AL,ES:[BP.dpb_drive]
invoke FLUSHBUF
SYS_RET_OKJ:
JMP SYS_RET_OK
NODEEXISTSPOPDEL:
POP DX ; Parent
POP DX ; Entry sector
LES BP,[THISDPB]
XOR AL,AL ; Pre read
invoke GETBUFFR
LDS DI,[CURBUF]
ASSUME DS:NOTHING
POP SI ; dir_first pointer
ADD SI,DI
SUB SI,dir_first ; Point back to start of dir entry
MOV BYTE PTR [SI],0E5H ; Free the entry
CALL DIRUP
NODEEXISTS:
MOV AL,mkdir_access_denied
MKNERR:
JMP SYS_RET_ERR
$MKDIR ENDP
BREAK <$ChDir -- Change current directory on a drive>
procedure $CHDIR,NEAR
ASSUME DS:NOTHING,ES:NOTHING
; Inputs:
; DS:DX Points to asciz name
; Function:
; Change current directory
; Returns:
; STD XENIX Return
; AX = chdir_path_not_found if error
invoke validate_path
JC PathTooLong
PUSH DS
PUSH DX
MOV SI,DX
invoke GETPATH
JC PATHNOGOOD
JNZ PATHNOGOOD
ASSUME DS:DOSGROUP
MOV AX,[DIRSTART]
MOV BX,AX
XCHG BX,ES:[BP.dpb_current_dir]
OR AX,AX
POP SI
POP DS
ASSUME DS:NOTHING
JZ SYS_RET_OKJ
MOV DI,BP
ADD DI,dpb_dir_text
MOV DX,DI
CMP [DRIVESPEC],0
JZ NODRIVESPEC
INC SI
INC SI
NODRIVESPEC:
MOV CX,SI
CMP [ROOTSTART],0
JZ NOTROOTPATH
INC SI
INC CX
JMP SHORT COPYTHESTRINGBXZ
NOTROOTPATH:
OR BX,BX ; Previous path root?
JZ COPYTHESTRING ; Yes
XOR BX,BX
ENDLOOP:
CMP BYTE PTR ES:[DI],0
JZ PATHEND
INC DI
INC BX
JMP SHORT ENDLOOP
PATHEND:
MOV AL,'/'
CMP AL,[switch_character]
JNZ SLASHOK
MOV AL,'\' ; Use the alternate character
SLASHOK:
STOSB
INC BX
JMP SHORT CHECK_LEN
PATHNOGOOD:
POP AX
POP AX
PATHTOOLONG:
error error_path_not_found
ASSUME DS:NOTHING
INCBXCHK:
INC BX
BXCHK:
CMP BX,DIRSTRLEN
return
COPYTHESTRINGBXZ:
XOR BX,BX
COPYTHESTRING:
LODSB
OR AL,AL
JNZ FOOB
JMP CPSTDONE
FOOB:
CMP AL,'.'
JZ SEEDOT
CALL COPYELEM
CHECK_LEN:
CMP BX,DIRSTRLEN
JB COPYTHESTRING
MOV AL,ES:[DI-1]
invoke PATHCHRCMP
JNZ OK_DI
DEC DI
OK_DI:
XOR AL,AL
STOSB ; Correctly terminate the path
MOV ES:[BP.dpb_current_dir],-1 ; Force re-validation
JMP SHORT PATHTOOLONG
SEEDOT:
LODSB
OR AL,AL ; Check for null
JZ CPSTDONEDEC
CMP AL,'.'
JNZ COPYTHESTRING ; eat ./
CALL DELELMES ; have ..
LODSB ; eat the /
OR AL,AL ; Check for null
JZ CPSTDONEDEC
JMP SHORT COPYTHESTRING
; Copy one element from DS:SI to ES:DI include trailing / not trailing null
; LODSB has already been done
COPYELEM:
PUSH DI ; Save in case too long
PUSH CX
MOV CX,800h ; length of filename
MOV AH,'.' ; char to stop on
CALL CopyPiece ; go for it!
CALL BXCHK ; did we go over?
JAE POPCXDI ; yep, go home
CMP AH,AL ; did we stop on .?
JZ CopyExt ; yes, go copy ext
OR AL,AL ; did we end on nul?
JZ DECSIRet ; yes, bye
CopyPathEnd:
STOSB ; save the path char
CALL INCBXCHK ; was there room for it?
JAE POPCXDI ; Nope
INC SI ; guard against following dec
DECSIRET:
DEC SI ; point back at null
POP CX
POP AX ; toss away saved DI
return
POPCXDI:
POP CX ; restore
POP DI ; point back...
return
CopyExt:
STOSB ; save the dot
CALL INCBXCHK ; room?
JAE POPCXDI ; nope.
LODSB ; get next char
XOR AH,AH ; NUL here
MOV CX,300h ; at most 3 chars
CALL CopyPiece ; go copy it
CALL BXCHK ; did we go over
JAE POPCXDI ; yep
OR AL,AL ; sucessful end?
JZ DECSIRET ; yes
JMP CopyPathEnd ; go stash path char
DELELMES:
; Delete one path element from ES:DI
DEC DI ; the '/'
DEC BX
IF KANJI
PUSH AX
PUSH CX
PUSH DI
PUSH DX
MOV CX,DI
MOV DI,DX
DELLOOP:
CMP DI,CX
JZ GOTDELE
MOV AL,ES:[DI]
INC DI
invoke TESTKANJ
JZ NOTKANJ11
INC DI
JMP DELLOOP
NOTKANJ11:
invoke PATHCHRCMP
JNZ DELLOOP
MOV DX,DI ; Point to char after '/'
JMP DELLOOP
GOTDELE:
MOV DI,DX
POP DX
POP AX ; Initial DI
SUB AX,DI ; Distance moved
SUB BX,AX ; Set correct BX
POP CX
POP AX
return
ELSE
DELLOOP:
CMP DI,DX
retz
PUSH AX
MOV AL,ES:[DI-1]
invoke PATHCHRCMP
POP AX
retz
DEC DI
DEC BX
JMP SHORT DELLOOP
ENDIF
CPSTDONEDEC:
DEC DI ; Back up over trailing /
CPSTDONE:
STOSB ; The NUL
JMP SYS_RET_OK
; copy a piece CH chars max until the char in AH (or path or NUL)
CopyPiece:
STOSB ; store the character
INC CL ; moved a byte
CALL INCBXCHK ; room enough?
JAE CopyPieceRet ; no, pop CX and DI
OR AL,AL ; end of string?
JZ CopyPieceRet ; yes, dec si and return
IF KANJI
CALL TestKanj ; was it kanji?
JZ NotKanj ; nope
MOVSB ; move the next byte
CALL INCBXCHK ; room for it?
JAE CopyPieceRet ; nope
INC CL ; moved a byte
NotKanj:
ENDIF
CMP CL,CH ; move too many?
JBE CopyPieceNext ; nope
IF KANJI
CALL TestKanj ; was the last byte kanji
JZ NotKanj2 ; no only single byte backup
DEC DI ; back up a char
DEC BX
NotKanj2:
ENDIF
DEC DI ; back up a char
DEC BX
CopyPieceNext:
LODSB ; get next character
invoke PathChrCmp ; end of road?
JZ CopyPieceRet ; yep, return and don't dec SI
CMP AL,AH ; end of filename?
JNZ CopyPiece ; go do name
CopyPieceRet:
return ; bye!
$CHDIR ENDP
BREAK <$RmDir -- Remove a directory>
NOPATHJ: JMP NOPATH
procedure $RMDIR,NEAR ; System call 47
ASSUME DS:NOTHING,ES:NOTHING
; Inputs:
; DS:DX Points to asciz name
; Function:
; Delete directory if empty
; Returns:
; STD XENIX Return
; AX = rmdir_path_not_found If path bad
; AX = rmdir_access_denied If
; Directory not empty
; Path not directory
; Root directory specified
; Directory malformed (. and .. not first two entries)
; AX = rmdir_current_directory
invoke Validate_path
JC NoPathJ
MOV SI,DX
invoke GETPATH
JC NOPATHJ
ASSUME DS:DOSGROUP
JNZ NOTDIRPATH
MOV DI,[DIRSTART]
OR DI,DI
JZ NOTDIRPATH
MOV CX,ES:[BP.dpb_current_dir]
CMP CX,-1
JNZ rmdir_current_dir_check
invoke GetCurrDir
invoke Get_user_stack
MOV DX,[SI.user_DX]
MOV DS,[SI.user_DS]
JMP $RMDIR
NOTDIRPATHPOP:
POP AX
POP AX
NOTDIRPATH:
error error_access_denied
rmdir_current_dir_check:
CMP DI,CX
JNZ rmdir_get_buf
error error_current_directory
rmdir_get_buf:
LDS DI,[CURBUF]
ASSUME DS:NOTHING
SUB BX,DI
PUSH BX ; Save entry pointer
PUSH [DI.BUFSECNO] ; Save sector number
PUSH SS
POP DS
ASSUME DS:DOSGROUP
PUSH SS
POP ES
MOV DI,OFFSET DOSGROUP:NAME1
MOV AL,'?'
MOV CX,11
REP STOSB
XOR AL,AL
STOSB
invoke STARTSRCH
invoke GETENTRY
MOV DS,WORD PTR [CURBUF+2]
ASSUME DS:NOTHING
MOV SI,BX
LODSW
CMP AX,(' ' SHL 8) OR '.'
JNZ NOTDIRPATHPOP
ADD SI,32-2
LODSW
CMP AX,('.' SHL 8) OR '.'
JNZ NOTDIRPATHPOP
PUSH SS
POP DS
ASSUME DS:DOSGROUP
MOV [LASTENT],2 ; Skip . and ..
invoke GETENTRY
MOV [ATTRIB],attr_directory+attr_hidden+attr_system
invoke SRCH
JNC NOTDIRPATHPOP
LES BP,[THISDPB]
MOV BX,[DIRSTART]
invoke RELEASE
POP DX
XOR AL,AL
invoke GETBUFFR
LDS DI,[CURBUF]
ASSUME DS:NOTHING
POP BX
ADD BX,DI
MOV BYTE PTR [BX],0E5H ; Free the entry
JMP DIRUP
NOPATH:
error error_path_not_found
$RMDIR ENDP
do_ext
CODE ENDS
END
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.