code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ctlcmd
import (
"errors"
"fmt"
"sort"
"text/tabwriter"
"github.com/snapcore/snapd/client/clientutil"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/overlord/servicestate"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/snap"
)
var (
shortServicesHelp = i18n.G("Query the status of services")
longServicesHelp = i18n.G(`
The services command lists information about the services specified.
`)
)
func init() {
addCommand("services", shortServicesHelp, longServicesHelp, func() command { return &servicesCommand{} })
}
type servicesCommand struct {
baseCommand
Positional struct {
ServiceNames []string `positional-arg-name:"<service>"`
} `positional-args:"yes"`
}
var errNoContextForServices = errors.New(i18n.G("cannot query services without a context"))
type byApp []*snap.AppInfo
func (a byApp) Len() int { return len(a) }
func (a byApp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byApp) Less(i, j int) bool {
return a[i].Name < a[j].Name
}
func (c *servicesCommand) Execute([]string) error {
context := c.context()
if context == nil {
return errNoContextForServices
}
st := context.State()
svcInfos, err := getServiceInfos(st, context.InstanceName(), c.Positional.ServiceNames)
if err != nil {
return err
}
sort.Sort(byApp(svcInfos))
sd := servicestate.NewStatusDecorator(progress.Null)
services, err := clientutil.ClientAppInfosFromSnapAppInfos(svcInfos, sd)
if err != nil || len(services) == 0 {
return err
}
w := tabwriter.NewWriter(c.stdout, 5, 3, 2, ' ', 0)
defer w.Flush()
fmt.Fprintln(w, i18n.G("Service\tStartup\tCurrent\tNotes"))
for _, svc := range services {
startup := i18n.G("disabled")
if svc.Enabled {
startup = i18n.G("enabled")
}
current := i18n.G("inactive")
if svc.DaemonScope == snap.UserDaemon {
current = "-"
} else if svc.Active {
current = i18n.G("active")
}
fmt.Fprintf(w, "%s.%s\t%s\t%s\t%s\n", svc.Snap, svc.Name, startup, current, clientutil.ClientAppInfoNotes(&svc))
}
return nil
}
| jhenstridge/snapd | overlord/hookstate/ctlcmd/services.go | GO | gpl-3.0 | 2,720 |
"""Weighted maximum matching in general graphs.
The algorithm is taken from "Efficient Algorithms for Finding Maximum
Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
It is based on the "blossom" method for finding augmenting paths and
the "primal-dual" method for finding a matching of maximum weight, both
due to Jack Edmonds.
Some ideas came from "Implementation of algorithms for maximum matching
on non-bipartite graphs" by H.J. Gabow, Standford Ph.D. thesis, 1973.
A C program for maximum weight matching by Ed Rothberg was used extensively
to validate this new code.
http://jorisvr.nl/article/maximum-matching#ref:4
"""
#
# Changes:
#
# 2013-04-07
# * Added Python 3 compatibility with contributions from Daniel Saunders.
#
# 2008-06-08
# * First release.
#
from __future__ import print_function
# If assigned, DEBUG(str) is called with lots of debug messages.
DEBUG = None
"""def DEBUG(s):
from sys import stderr
print('DEBUG:', s, file=stderr)
"""
# Check delta2/delta3 computation after every substage;
# only works on integer weights, slows down the algorithm to O(n^4).
CHECK_DELTA = False
# Check optimality of solution before returning; only works on integer weights.
CHECK_OPTIMUM = True
def maxWeightMatching(edges, maxcardinality=False):
"""Compute a maximum-weighted matching in the general undirected
weighted graph given by "edges". If "maxcardinality" is true,
only maximum-cardinality matchings are considered as solutions.
Edges is a sequence of tuples (i, j, wt) describing an undirected
edge between vertex i and vertex j with weight wt. There is at most
one edge between any two vertices; no vertex has an edge to itself.
Vertices are identified by consecutive, non-negative integers.
Return a list "mate", such that mate[i] == j if vertex i is
matched to vertex j, and mate[i] == -1 if vertex i is not matched.
This function takes time O(n ** 3)."""
#
# Vertices are numbered 0 .. (nvertex-1).
# Non-trivial blossoms are numbered nvertex .. (2*nvertex-1)
#
# Edges are numbered 0 .. (nedge-1).
# Edge endpoints are numbered 0 .. (2*nedge-1), such that endpoints
# (2*k) and (2*k+1) both belong to edge k.
#
# Many terms used in the comments (sub-blossom, T-vertex) come from
# the paper by Galil; read the paper before reading this code.
#
# Python 2/3 compatibility.
from sys import version as sys_version
if sys_version < '3':
integer_types = (int, long)
else:
integer_types = (int,)
# Deal swiftly with empty graphs.
if not edges:
return [ ]
# Count vertices.
nedge = len(edges)
nvertex = 0
for (i, j, w) in edges:
assert i >= 0 and j >= 0 and i != j
if i >= nvertex:
nvertex = i + 1
if j >= nvertex:
nvertex = j + 1
# Find the maximum edge weight.
maxweight = max(0, max([ wt for (i, j, wt) in edges ]))
# If p is an edge endpoint,
# endpoint[p] is the vertex to which endpoint p is attached.
# Not modified by the algorithm.
endpoint = [ edges[p//2][p%2] for p in range(2*nedge) ]
# If v is a vertex,
# neighbend[v] is the list of remote endpoints of the edges attached to v.
# Not modified by the algorithm.
neighbend = [ [ ] for i in range(nvertex) ]
for k in range(len(edges)):
(i, j, w) = edges[k]
neighbend[i].append(2*k+1)
neighbend[j].append(2*k)
# If v is a vertex,
# mate[v] is the remote endpoint of its matched edge, or -1 if it is single
# (i.e. endpoint[mate[v]] is v's partner vertex).
# Initially all vertices are single; updated during augmentation.
mate = nvertex * [ -1 ]
# If b is a top-level blossom,
# label[b] is 0 if b is unlabeled (free);
# 1 if b is an S-vertex/blossom;
# 2 if b is a T-vertex/blossom.
# The label of a vertex is found by looking at the label of its
# top-level containing blossom.
# If v is a vertex inside a T-blossom,
# label[v] is 2 iff v is reachable from an S-vertex outside the blossom.
# Labels are assigned during a stage and reset after each augmentation.
label = (2 * nvertex) * [ 0 ]
# If b is a labeled top-level blossom,
# labelend[b] is the remote endpoint of the edge through which b obtained
# its label, or -1 if b's base vertex is single.
# If v is a vertex inside a T-blossom and label[v] == 2,
# labelend[v] is the remote endpoint of the edge through which v is
# reachable from outside the blossom.
labelend = (2 * nvertex) * [ -1 ]
# If v is a vertex,
# inblossom[v] is the top-level blossom to which v belongs.
# If v is a top-level vertex, v is itself a blossom (a trivial blossom)
# and inblossom[v] == v.
# Initially all vertices are top-level trivial blossoms.
inblossom = list(range(nvertex))
# If b is a sub-blossom,
# blossomparent[b] is its immediate parent (sub-)blossom.
# If b is a top-level blossom, blossomparent[b] is -1.
blossomparent = (2 * nvertex) * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomchilds[b] is an ordered list of its sub-blossoms, starting with
# the base and going round the blossom.
blossomchilds = (2 * nvertex) * [ None ]
# If b is a (sub-)blossom,
# blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
blossombase = list(range(nvertex)) + nvertex * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomendps[b] is a list of endpoints on its connecting edges,
# such that blossomendps[b][i] is the local endpoint of blossomchilds[b][i]
# on the edge that connects it to blossomchilds[b][wrap(i+1)].
blossomendps = (2 * nvertex) * [ None ]
# If v is a free vertex (or an unreached vertex inside a T-blossom),
# bestedge[v] is the edge to an S-vertex with least slack,
# or -1 if there is no such edge.
# If b is a (possibly trivial) top-level S-blossom,
# bestedge[b] is the least-slack edge to a different S-blossom,
# or -1 if there is no such edge.
# This is used for efficient computation of delta2 and delta3.
bestedge = (2 * nvertex) * [ -1 ]
# If b is a non-trivial top-level S-blossom,
# blossombestedges[b] is a list of least-slack edges to neighbouring
# S-blossoms, or None if no such list has been computed yet.
# This is used for efficient computation of delta3.
blossombestedges = (2 * nvertex) * [ None ]
# List of currently unused blossom numbers.
unusedblossoms = list(range(nvertex, 2*nvertex))
# If v is a vertex,
# dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
# optimization problem (multiplication by two ensures integer values
# throughout the algorithm if all edge weights are integers).
# If b is a non-trivial blossom,
# dualvar[b] = z(b) where z(b) is b's variable in the dual optimization
# problem.
dualvar = nvertex * [ maxweight ] + nvertex * [ 0 ]
# If allowedge[k] is true, edge k has zero slack in the optimization
# problem; if allowedge[k] is false, the edge's slack may or may not
# be zero.
allowedge = nedge * [ False ]
# Queue of newly discovered S-vertices.
queue = [ ]
# Return 2 * slack of edge k (does not work inside blossoms).
def slack(k):
(i, j, wt) = edges[k]
return dualvar[i] + dualvar[j] - 2 * wt
# Generate the leaf vertices of a blossom.
def blossomLeaves(b):
if b < nvertex:
yield b
else:
for t in blossomchilds[b]:
if t < nvertex:
yield t
else:
for v in blossomLeaves(t):
yield v
# Assign label t to the top-level blossom containing vertex w
# and record the fact that w was reached through the edge with
# remote endpoint p.
def assignLabel(w, t, p):
if DEBUG: DEBUG('assignLabel(%d,%d,%d)' % (w, t, p))
b = inblossom[w]
assert label[w] == 0 and label[b] == 0
label[w] = label[b] = t
labelend[w] = labelend[b] = p
bestedge[w] = bestedge[b] = -1
if t == 1:
# b became an S-vertex/blossom; add it(s vertices) to the queue.
queue.extend(blossomLeaves(b))
if DEBUG: DEBUG('PUSH ' + str(list(blossomLeaves(b))))
elif t == 2:
# b became a T-vertex/blossom; assign label S to its mate.
# (If b is a non-trivial blossom, its base is the only vertex
# with an external mate.)
base = blossombase[b]
assert mate[base] >= 0
assignLabel(endpoint[mate[base]], 1, mate[base] ^ 1)
# Trace back from vertices v and w to discover either a new blossom
# or an augmenting path. Return the base vertex of the new blossom or -1.
def scanBlossom(v, w):
if DEBUG: DEBUG('scanBlossom(%d,%d)' % (v, w))
# Trace back from v and w, placing breadcrumbs as we go.
path = [ ]
base = -1
while v != -1 or w != -1:
# Look for a breadcrumb in v's blossom or put a new breadcrumb.
b = inblossom[v]
if label[b] & 4:
base = blossombase[b]
break
assert label[b] == 1
path.append(b)
label[b] = 5
# Trace one step back.
assert labelend[b] == mate[blossombase[b]]
if labelend[b] == -1:
# The base of blossom b is single; stop tracing this path.
v = -1
else:
v = endpoint[labelend[b]]
b = inblossom[v]
assert label[b] == 2
# b is a T-blossom; trace one more step back.
assert labelend[b] >= 0
v = endpoint[labelend[b]]
# Swap v and w so that we alternate between both paths.
if w != -1:
v, w = w, v
# Remove breadcrumbs.
for b in path:
label[b] = 1
# Return base vertex, if we found one.
return base
# Construct a new blossom with given base, containing edge k which
# connects a pair of S vertices. Label the new blossom as S; set its dual
# variable to zero; relabel its T-vertices to S and add them to the queue.
def addBlossom(base, k):
(v, w, wt) = edges[k]
bb = inblossom[base]
bv = inblossom[v]
bw = inblossom[w]
# Create blossom.
b = unusedblossoms.pop()
if DEBUG: DEBUG('addBlossom(%d,%d) (v=%d w=%d) -> %d' % (base, k, v, w, b))
blossombase[b] = base
blossomparent[b] = -1
blossomparent[bb] = b
# Make list of sub-blossoms and their interconnecting edge endpoints.
blossomchilds[b] = path = [ ]
blossomendps[b] = endps = [ ]
# Trace back from v to base.
while bv != bb:
# Add bv to the new blossom.
blossomparent[bv] = b
path.append(bv)
endps.append(labelend[bv])
assert (label[bv] == 2 or
(label[bv] == 1 and labelend[bv] == mate[blossombase[bv]]))
# Trace one step back.
assert labelend[bv] >= 0
v = endpoint[labelend[bv]]
bv = inblossom[v]
# Reverse lists, add endpoint that connects the pair of S vertices.
path.append(bb)
path.reverse()
endps.reverse()
endps.append(2*k)
# Trace back from w to base.
while bw != bb:
# Add bw to the new blossom.
blossomparent[bw] = b
path.append(bw)
endps.append(labelend[bw] ^ 1)
assert (label[bw] == 2 or
(label[bw] == 1 and labelend[bw] == mate[blossombase[bw]]))
# Trace one step back.
assert labelend[bw] >= 0
w = endpoint[labelend[bw]]
bw = inblossom[w]
# Set label to S.
assert label[bb] == 1
label[b] = 1
labelend[b] = labelend[bb]
# Set dual variable to zero.
dualvar[b] = 0
# Relabel vertices.
for v in blossomLeaves(b):
if label[inblossom[v]] == 2:
# This T-vertex now turns into an S-vertex because it becomes
# part of an S-blossom; add it to the queue.
queue.append(v)
inblossom[v] = b
# Compute blossombestedges[b].
bestedgeto = (2 * nvertex) * [ -1 ]
for bv in path:
if blossombestedges[bv] is None:
# This subblossom does not have a list of least-slack edges;
# get the information from the vertices.
nblists = [ [ p // 2 for p in neighbend[v] ]
for v in blossomLeaves(bv) ]
else:
# Walk this subblossom's least-slack edges.
nblists = [ blossombestedges[bv] ]
for nblist in nblists:
for k in nblist:
(i, j, wt) = edges[k]
if inblossom[j] == b:
i, j = j, i
bj = inblossom[j]
if (bj != b and label[bj] == 1 and
(bestedgeto[bj] == -1 or
slack(k) < slack(bestedgeto[bj]))):
bestedgeto[bj] = k
# Forget about least-slack edges of the subblossom.
blossombestedges[bv] = None
bestedge[bv] = -1
blossombestedges[b] = [ k for k in bestedgeto if k != -1 ]
# Select bestedge[b].
bestedge[b] = -1
for k in blossombestedges[b]:
if bestedge[b] == -1 or slack(k) < slack(bestedge[b]):
bestedge[b] = k
if DEBUG: DEBUG('blossomchilds[%d]=' % b + repr(blossomchilds[b]))
# Expand the given top-level blossom.
def expandBlossom(b, endstage):
if DEBUG: DEBUG('expandBlossom(%d,%d) %s' % (b, endstage, repr(blossomchilds[b])))
# Convert sub-blossoms into top-level blossoms.
for s in blossomchilds[b]:
blossomparent[s] = -1
if s < nvertex:
inblossom[s] = s
elif endstage and dualvar[s] == 0:
# Recursively expand this sub-blossom.
expandBlossom(s, endstage)
else:
for v in blossomLeaves(s):
inblossom[v] = s
# If we expand a T-blossom during a stage, its sub-blossoms must be
# relabeled.
if (not endstage) and label[b] == 2:
# Start at the sub-blossom through which the expanding
# blossom obtained its label, and relabel sub-blossoms untili
# we reach the base.
# Figure out through which sub-blossom the expanding blossom
# obtained its label initially.
assert labelend[b] >= 0
entrychild = inblossom[endpoint[labelend[b] ^ 1]]
# Decide in which direction we will go round the blossom.
j = blossomchilds[b].index(entrychild)
if j & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
p = labelend[b]
while j != 0:
# Relabel the T-sub-blossom.
label[endpoint[p ^ 1]] = 0
label[endpoint[blossomendps[b][j-endptrick]^endptrick^1]] = 0
assignLabel(endpoint[p ^ 1], 2, p)
# Step to the next S-sub-blossom and note its forward endpoint.
allowedge[blossomendps[b][j-endptrick]//2] = True
j += jstep
p = blossomendps[b][j-endptrick] ^ endptrick
# Step to the next T-sub-blossom.
allowedge[p//2] = True
j += jstep
# Relabel the base T-sub-blossom WITHOUT stepping through to
# its mate (so don't call assignLabel).
bv = blossomchilds[b][j]
label[endpoint[p ^ 1]] = label[bv] = 2
labelend[endpoint[p ^ 1]] = labelend[bv] = p
bestedge[bv] = -1
# Continue along the blossom until we get back to entrychild.
j += jstep
while blossomchilds[b][j] != entrychild:
# Examine the vertices of the sub-blossom to see whether
# it is reachable from a neighbouring S-vertex outside the
# expanding blossom.
bv = blossomchilds[b][j]
if label[bv] == 1:
# This sub-blossom just got label S through one of its
# neighbours; leave it.
j += jstep
continue
for v in blossomLeaves(bv):
if label[v] != 0:
break
# If the sub-blossom contains a reachable vertex, assign
# label T to the sub-blossom.
if label[v] != 0:
assert label[v] == 2
assert inblossom[v] == bv
label[v] = 0
label[endpoint[mate[blossombase[bv]]]] = 0
assignLabel(v, 2, labelend[v])
j += jstep
# Recycle the blossom number.
label[b] = labelend[b] = -1
blossomchilds[b] = blossomendps[b] = None
blossombase[b] = -1
blossombestedges[b] = None
bestedge[b] = -1
unusedblossoms.append(b)
# Swap matched/unmatched edges over an alternating path through blossom b
# between vertex v and the base vertex. Keep blossom bookkeeping consistent.
def augmentBlossom(b, v):
if DEBUG: DEBUG('augmentBlossom(%d,%d)' % (b, v))
# Bubble up through the blossom tree from vertex v to an immediate
# sub-blossom of b.
t = v
while blossomparent[t] != b:
t = blossomparent[t]
# Recursively deal with the first sub-blossom.
if t >= nvertex:
augmentBlossom(t, v)
# Decide in which direction we will go round the blossom.
i = j = blossomchilds[b].index(t)
if i & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
while j != 0:
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
p = blossomendps[b][j-endptrick] ^ endptrick
if t >= nvertex:
augmentBlossom(t, endpoint[p])
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
if t >= nvertex:
augmentBlossom(t, endpoint[p ^ 1])
# Match the edge connecting those sub-blossoms.
mate[endpoint[p]] = p ^ 1
mate[endpoint[p ^ 1]] = p
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (endpoint[p], endpoint[p^1], p//2))
# Rotate the list of sub-blossoms to put the new base at the front.
blossomchilds[b] = blossomchilds[b][i:] + blossomchilds[b][:i]
blossomendps[b] = blossomendps[b][i:] + blossomendps[b][:i]
blossombase[b] = blossombase[blossomchilds[b][0]]
assert blossombase[b] == v
# Swap matched/unmatched edges over an alternating path between two
# single vertices. The augmenting path runs through edge k, which
# connects a pair of S vertices.
def augmentMatching(k):
(v, w, wt) = edges[k]
if DEBUG: DEBUG('augmentMatching(%d) (v=%d w=%d)' % (k, v, w))
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (v, w, k))
for (s, p) in ((v, 2*k+1), (w, 2*k)):
# Match vertex s to remote endpoint p. Then trace back from s
# until we find a single vertex, swapping matched and unmatched
# edges as we go.
while 1:
bs = inblossom[s]
assert label[bs] == 1
assert labelend[bs] == mate[blossombase[bs]]
# Augment through the S-blossom from s to base.
if bs >= nvertex:
augmentBlossom(bs, s)
# Update mate[s]
mate[s] = p
# Trace one step back.
if labelend[bs] == -1:
# Reached single vertex; stop.
break
t = endpoint[labelend[bs]]
bt = inblossom[t]
assert label[bt] == 2
# Trace one step back.
assert labelend[bt] >= 0
s = endpoint[labelend[bt]]
j = endpoint[labelend[bt] ^ 1]
# Augment through the T-blossom from j to base.
assert blossombase[bt] == t
if bt >= nvertex:
augmentBlossom(bt, j)
# Update mate[j]
mate[j] = labelend[bt]
# Keep the opposite endpoint;
# it will be assigned to mate[s] in the next step.
p = labelend[bt] ^ 1
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (s, t, p//2))
# Verify that the optimum solution has been reached.
def verifyOptimum():
if maxcardinality:
# Vertices may have negative dual;
# find a constant non-negative number to add to all vertex duals.
vdualoffset = max(0, -min(dualvar[:nvertex]))
else:
vdualoffset = 0
# 0. all dual variables are non-negative
assert min(dualvar[:nvertex]) + vdualoffset >= 0
assert min(dualvar[nvertex:]) >= 0
# 0. all edges have non-negative slack and
# 1. all matched edges have zero slack;
for k in range(nedge):
(i, j, wt) = edges[k]
s = dualvar[i] + dualvar[j] - 2 * wt
iblossoms = [ i ]
jblossoms = [ j ]
while blossomparent[iblossoms[-1]] != -1:
iblossoms.append(blossomparent[iblossoms[-1]])
while blossomparent[jblossoms[-1]] != -1:
jblossoms.append(blossomparent[jblossoms[-1]])
iblossoms.reverse()
jblossoms.reverse()
for (bi, bj) in zip(iblossoms, jblossoms):
if bi != bj:
break
s += 2 * dualvar[bi]
assert s >= 0
if mate[i] // 2 == k or mate[j] // 2 == k:
assert mate[i] // 2 == k and mate[j] // 2 == k
assert s == 0
# 2. all single vertices have zero dual value;
for v in range(nvertex):
assert mate[v] >= 0 or dualvar[v] + vdualoffset == 0
# 3. all blossoms with positive dual value are full.
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and dualvar[b] > 0:
assert len(blossomendps[b]) % 2 == 1
for p in blossomendps[b][1::2]:
assert mate[endpoint[p]] == p ^ 1
assert mate[endpoint[p ^ 1]] == p
# Ok.
# Check optimized delta2 against a trivial computation.
def checkDelta2():
for v in range(nvertex):
if label[inblossom[v]] == 0:
bd = None
bk = -1
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if DEBUG and (bestedge[v] != -1 or bk != -1) and (bestedge[v] == -1 or bd != slack(bestedge[v])):
DEBUG('v=' + str(v) + ' bk=' + str(bk) + ' bd=' + str(bd) + ' bestedge=' + str(bestedge[v]) + ' slack=' + str(slack(bestedge[v])))
assert (bk == -1 and bestedge[v] == -1) or (bestedge[v] != -1 and bd == slack(bestedge[v]))
# Check optimized delta3 against a trivial computation.
def checkDelta3():
bk = -1
bd = None
tbk = -1
tbd = None
for b in range(2 * nvertex):
if blossomparent[b] == -1 and label[b] == 1:
for v in blossomLeaves(b):
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if inblossom[w] != b and label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if bestedge[b] != -1:
(i, j, wt) = edges[bestedge[b]]
assert inblossom[i] == b or inblossom[j] == b
assert inblossom[i] != b or inblossom[j] != b
assert label[inblossom[i]] == 1 and label[inblossom[j]] == 1
if tbk == -1 or slack(bestedge[b]) < tbd:
tbk = bestedge[b]
tbd = slack(bestedge[b])
if DEBUG and bd != tbd:
DEBUG('bk=%d tbk=%d bd=%s tbd=%s' % (bk, tbk, repr(bd), repr(tbd)))
assert bd == tbd
# Main loop: continue until no further improvement is possible.
for t in range(nvertex):
# Each iteration of this loop is a "stage".
# A stage finds an augmenting path and uses that to improve
# the matching.
if DEBUG: DEBUG('STAGE %d' % t)
# Remove labels from top-level blossoms/vertices.
label[:] = (2 * nvertex) * [ 0 ]
# Forget all about least-slack edges.
bestedge[:] = (2 * nvertex) * [ -1 ]
blossombestedges[nvertex:] = nvertex * [ None ]
# Loss of labeling means that we can not be sure that currently
# allowable edges remain allowable througout this stage.
allowedge[:] = nedge * [ False ]
# Make queue empty.
queue[:] = [ ]
# Label single blossoms/vertices with S and put them in the queue.
for v in range(nvertex):
if mate[v] == -1 and label[inblossom[v]] == 0:
assignLabel(v, 1, -1)
# Loop until we succeed in augmenting the matching.
augmented = 0
while 1:
# Each iteration of this loop is a "substage".
# A substage tries to find an augmenting path;
# if found, the path is used to improve the matching and
# the stage ends. If there is no augmenting path, the
# primal-dual method is used to pump some slack out of
# the dual variables.
if DEBUG: DEBUG('SUBSTAGE')
# Continue labeling until all vertices which are reachable
# through an alternating path have got a label.
while queue and not augmented:
# Take an S vertex from the queue.
v = queue.pop()
if DEBUG: DEBUG('POP v=%d' % v)
assert label[inblossom[v]] == 1
# Scan its neighbours:
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
# w is a neighbour to v
if inblossom[v] == inblossom[w]:
# this edge is internal to a blossom; ignore it
continue
if not allowedge[k]:
kslack = slack(k)
if kslack <= 0:
# edge k has zero slack => it is allowable
allowedge[k] = True
if allowedge[k]:
if label[inblossom[w]] == 0:
# (C1) w is a free vertex;
# label w with T and label its mate with S (R12).
assignLabel(w, 2, p ^ 1)
elif label[inblossom[w]] == 1:
# (C2) w is an S-vertex (not in the same blossom);
# follow back-links to discover either an
# augmenting path or a new blossom.
base = scanBlossom(v, w)
if base >= 0:
# Found a new blossom; add it to the blossom
# bookkeeping and turn it into an S-blossom.
addBlossom(base, k)
else:
# Found an augmenting path; augment the
# matching and end this stage.
augmentMatching(k)
augmented = 1
break
elif label[w] == 0:
# w is inside a T-blossom, but w itself has not
# yet been reached from outside the blossom;
# mark it as reached (we need this to relabel
# during T-blossom expansion).
assert label[inblossom[w]] == 2
label[w] = 2
labelend[w] = p ^ 1
elif label[inblossom[w]] == 1:
# keep track of the least-slack non-allowable edge to
# a different S-blossom.
b = inblossom[v]
if bestedge[b] == -1 or kslack < slack(bestedge[b]):
bestedge[b] = k
elif label[w] == 0:
# w is a free vertex (or an unreached vertex inside
# a T-blossom) but we can not reach it yet;
# keep track of the least-slack edge that reaches w.
if bestedge[w] == -1 or kslack < slack(bestedge[w]):
bestedge[w] = k
if augmented:
break
# There is no augmenting path under these constraints;
# compute delta and reduce slack in the optimization problem.
# (Note that our vertex dual variables, edge slacks and delta's
# are pre-multiplied by two.)
deltatype = -1
delta = deltaedge = deltablossom = None
# Verify data structures for delta2/delta3 computation.
if CHECK_DELTA:
checkDelta2()
checkDelta3()
# Compute delta1: the minumum value of any vertex dual.
if not maxcardinality:
deltatype = 1
delta = min(dualvar[:nvertex])
# Compute delta2: the minimum slack on any edge between
# an S-vertex and a free vertex.
for v in range(nvertex):
if label[inblossom[v]] == 0 and bestedge[v] != -1:
d = slack(bestedge[v])
if deltatype == -1 or d < delta:
delta = d
deltatype = 2
deltaedge = bestedge[v]
# Compute delta3: half the minimum slack on any edge between
# a pair of S-blossoms.
for b in range(2 * nvertex):
if ( blossomparent[b] == -1 and label[b] == 1 and
bestedge[b] != -1 ):
kslack = slack(bestedge[b])
if isinstance(kslack, integer_types):
assert (kslack % 2) == 0
d = kslack // 2
else:
d = kslack / 2
if deltatype == -1 or d < delta:
delta = d
deltatype = 3
deltaedge = bestedge[b]
# Compute delta4: minimum z variable of any T-blossom.
for b in range(nvertex, 2*nvertex):
if ( blossombase[b] >= 0 and blossomparent[b] == -1 and
label[b] == 2 and
(deltatype == -1 or dualvar[b] < delta) ):
delta = dualvar[b]
deltatype = 4
deltablossom = b
if deltatype == -1:
# No further improvement possible; max-cardinality optimum
# reached. Do a final delta update to make the optimum
# verifyable.
assert maxcardinality
deltatype = 1
delta = max(0, min(dualvar[:nvertex]))
# Update dual variables according to delta.
for v in range(nvertex):
if label[inblossom[v]] == 1:
# S-vertex: 2*u = 2*u - 2*delta
dualvar[v] -= delta
elif label[inblossom[v]] == 2:
# T-vertex: 2*u = 2*u + 2*delta
dualvar[v] += delta
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and blossomparent[b] == -1:
if label[b] == 1:
# top-level S-blossom: z = z + 2*delta
dualvar[b] += delta
elif label[b] == 2:
# top-level T-blossom: z = z - 2*delta
dualvar[b] -= delta
# Take action at the point where minimum delta occurred.
if DEBUG: DEBUG('delta%d=%f' % (deltatype, delta))
if deltatype == 1:
# No further improvement possible; optimum reached.
break
elif deltatype == 2:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
if label[inblossom[i]] == 0:
i, j = j, i
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 3:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 4:
# Expand the least-z blossom.
expandBlossom(deltablossom, False)
# End of a this substage.
# Stop when no more augmenting path can be found.
if not augmented:
break
# End of a stage; expand all S-blossoms which have dualvar = 0.
for b in range(nvertex, 2*nvertex):
if ( blossomparent[b] == -1 and blossombase[b] >= 0 and
label[b] == 1 and dualvar[b] == 0 ):
expandBlossom(b, True)
# Verify that we reached the optimum solution.
if CHECK_OPTIMUM:
verifyOptimum()
# Transform mate[] such that mate[v] is the vertex to which v is paired.
for v in range(nvertex):
if mate[v] >= 0:
mate[v] = endpoint[mate[v]]
for v in range(nvertex):
assert mate[v] == -1 or mate[mate[v]] == v
return mate | bvancsics/TCMC | maximum_matching.py | Python | gpl-3.0 | 35,707 |
package scraper.environment;
/**
* Simple status message class wrapping messages.
*/
public class StatusMessage {
private String message;
protected StatusMessage() {
}
public StatusMessage(String message) {
this.message = message;
}
public StatusMessage(String messageFormat, Object... args) {
this.message = String.format(messageFormat, args);
}
public String getMessage() {
return message;
}
}
| pcimcioch/scraper | src/main/java/scraper/environment/StatusMessage.java | Java | gpl-3.0 | 464 |
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2014 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Shared
* @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
/**
* PHPExcel_Shared_CodePage
*
* @category PHPExcel
* @package PHPExcel_Shared
* @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Shared_CodePage
{
/**
* Convert Microsoft Code Page Identifier to Code Page Name which iconv
* and mbstring understands
*
* @param integer $codePage Microsoft Code Page Indentifier
* @return string Code Page Name
* @throws PHPExcel_Exception
*/
public static function NumberToName($codePage = 1252)
{
switch ($codePage) {
case 367:
return 'ASCII';
break; // ASCII
case 437:
return 'CP437';
break; // OEM US
case 720:
throw new PHPExcel_Exception('Code page 720 not supported.');
break; // OEM Arabic
case 737:
return 'CP737';
break; // OEM Greek
case 775:
return 'CP775';
break; // OEM Baltic
case 850:
return 'CP850';
break; // OEM Latin I
case 852:
return 'CP852';
break; // OEM Latin II (Central European)
case 855:
return 'CP855';
break; // OEM Cyrillic
case 857:
return 'CP857';
break; // OEM Turkish
case 858:
return 'CP858';
break; // OEM Multilingual Latin I with Euro
case 860:
return 'CP860';
break; // OEM Portugese
case 861:
return 'CP861';
break; // OEM Icelandic
case 862:
return 'CP862';
break; // OEM Hebrew
case 863:
return 'CP863';
break; // OEM Canadian (French)
case 864:
return 'CP864';
break; // OEM Arabic
case 865:
return 'CP865';
break; // OEM Nordic
case 866:
return 'CP866';
break; // OEM Cyrillic (Russian)
case 869:
return 'CP869';
break; // OEM Greek (Modern)
case 874:
return 'CP874';
break; // ANSI Thai
case 932:
return 'CP932';
break; // ANSI Japanese Shift-JIS
case 936:
return 'CP936';
break; // ANSI Chinese Simplified GBK
case 949:
return 'CP949';
break; // ANSI Korean (Wansung)
case 950:
return 'CP950';
break; // ANSI Chinese Traditional BIG5
case 1200:
return 'UTF-16LE';
break; // UTF-16 (BIFF8)
case 1250:
return 'CP1250';
break; // ANSI Latin II (Central European)
case 1251:
return 'CP1251';
break; // ANSI Cyrillic
case 0: // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program
case 1252:
return 'CP1252';
break; // ANSI Latin I (BIFF4-BIFF7)
case 1253:
return 'CP1253';
break; // ANSI Greek
case 1254:
return 'CP1254';
break; // ANSI Turkish
case 1255:
return 'CP1255';
break; // ANSI Hebrew
case 1256:
return 'CP1256';
break; // ANSI Arabic
case 1257:
return 'CP1257';
break; // ANSI Baltic
case 1258:
return 'CP1258';
break; // ANSI Vietnamese
case 1361:
return 'CP1361';
break; // ANSI Korean (Johab)
case 10000:
return 'MAC';
break; // Apple Roman
case 10001:
return 'CP932';
break; // Macintosh Japanese
case 10002:
return 'CP950';
break; // Macintosh Chinese Traditional
case 10003:
return 'CP1361';
break; // Macintosh Korean
case 10006:
return 'MACGREEK';
break; // Macintosh Greek
case 10007:
return 'MACCYRILLIC';
break; // Macintosh Cyrillic
case 10008:
return 'CP936';
break; // Macintosh - Simplified Chinese (GB 2312)
case 10029:
return 'MACCENTRALEUROPE';
break; // Macintosh Central Europe
case 10079:
return 'MACICELAND';
break; // Macintosh Icelandic
case 10081:
return 'MACTURKISH';
break; // Macintosh Turkish
case 21010:
return 'UTF-16LE';
break; // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE
case 32768:
return 'MAC';
break; // Apple Roman
case 32769:
throw new PHPExcel_Exception('Code page 32769 not supported.');
break; // ANSI Latin I (BIFF2-BIFF3)
case 65000:
return 'UTF-7';
break; // Unicode (UTF-7)
case 65001:
return 'UTF-8';
break; // Unicode (UTF-8)
}
throw new PHPExcel_Exception('Unknown codepage: ' . $codePage);
}
}
| jvianney/SwiftHR | Classes/PHPExcel/Shared/CodePage.php | PHP | gpl-3.0 | 7,067 |
let html_audio = document.getElementById("audio-source");
let html_open_button = document.getElementById("open-button");
//Setup the audio graph and context
let audioContext = new window.AudioContext();
let audioSource = audioContext.createMediaElementSource($("#audio-source")[0]);
let audioAnalyser = audioContext.createAnalyser();
audioAnalyser.fftSize = 2048;
let audioVolume = audioContext.createGain();
audioVolume.gain.value = 1;
audioSource.connect(audioAnalyser);
audioSource.connect(audioVolume);
audioVolume.connect(audioContext.destination);
//File input
html_open_button.addEventListener("click", () => {
remote.dialog.showOpenDialog({filters: [{name: "Music files" ,extensions: ["mp3"]}], properties: ['openFile']}, (file) => {
if(file) {
readMusicFile(file);
}
});
});
function readMusicFile(file) {
html_audio.pause();
html_audio.src = file[0];
html_audio.load();
MusicMetadata.parseFile(file[0], {duration: true})
.then((metadata) => {
if(metadata.common.artist) {
document.getElementById("audio-artist").innerHTML = metadata.common.artist;
}
else {
document.getElementById("audio-artist").innerHTML = null;
}
if(metadata.common.title) {
document.getElementById("audio-title").innerHTML = metadata.common.title;
}
else {
document.getElementById("audio-title").innerHTML = file[0].slice(file[0].lastIndexOf("\\")+1, file[0].lastIndexOf("."));
}
readNewDirectory(file[0]);
if(metadata.common.picture !== null && typeof metadata.common.picture == "object") {
document.getElementById("album-image").width = 125;
document.getElementById("album-image").height = 125;
let pictureData = new Uint8Array(metadata.common.picture[0].data);
let len = metadata.common.picture[0].data.byteLength;
let pictureDataString = "";
for (let i = 0; i < len; i++) {
pictureDataString += String.fromCharCode(pictureData[i]);
}
let base64String = btoa(pictureDataString);
document.getElementById("album-image").src = "data:image/jpg;base64,"+base64String;
document.getElementById("audio-title").style.marginLeft = "20px";
}
else {
document.getElementById("album-image").width = 0;
document.getElementById("album-image").height = 0;
document.getElementById("album-image").src = "";
document.getElementById("audio-title").style.marginLeft = "0px";
}
document.getElementById("slider").max = Math.floor(metadata.format.duration);
let minutes = Math.floor(metadata.format.duration / 60).toString();
if(minutes < 10) {
minutes = "0" + minutes;
}
let seconds = Math.round(metadata.format.duration % 60).toString();
if(seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("total-time").innerHTML = minutes + ":" + seconds;
})
.catch((err) => console.log(err));
startSliderPositionUpdate();
html_audio.play();
document.getElementById("play-button").innerHTML = "❘❘";
};
//Slider and timestamp
let sliderPositionInterval = 0;
let mousedown = false;
let startSliderPositionUpdate = function() {
sliderPositionInterval = setInterval(() => {
if(!mousedown) {
let minutes = Math.floor(html_audio.currentTime / 60);
if(minutes < 10) {
minutes = "0" + minutes.toString();
}
let seconds = Math.round(html_audio.currentTime % 60);
if(seconds < 10) {
seconds = "0" + seconds.toString();
}
document.getElementById("current-time").innerHTML = minutes + ":" + seconds;
document.getElementById("slider").value = html_audio.currentTime;
}
}, 500);
};
document.getElementById("slider").addEventListener("mousedown", () => {
mousedown = true;
clearInterval(sliderPositionInterval);
sliderPositionInterval = 0;
});
document.getElementById("slider").addEventListener("mouseup", () => {
mousedown = false;
html_audio.currentTime = $("#slider").val();
startSliderPositionUpdate();
});
//Play-pause button
document.getElementById("play-button").addEventListener("click", () => {
if(html_audio.paused) {
html_audio.play();
document.getElementById("play-button").innerHTML = "❘❘";
}
else {
html_audio.pause();
document.getElementById("play-button").innerHTML = "▷";
}
});
//Next song button
document.getElementById("next-song-button").addEventListener("click", () => {
if(currentSong == songsList.length - 1) {
currentSong = 0;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong += 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Previous song button
document.getElementById("previous-song-button").addEventListener("click", () => {
if(html_audio.currentTime >= 15) {
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else if(currentSong == 0) {
currentSong = songsList.length - 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong -= 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Automatically load next song
document.getElementById("audio-source").addEventListener("ended", () => {
if(currentSong == songsList.length - 1) {
currentSong = 0;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong += 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Mouse hover delay in player info
let playerInfoHoverTimer = 0;
$("#audio-info").hover(() => {
if(playerInfoHoverTimer == 0) {
$("#audio-info").css("opacity", 1.0);
$("#audio-info").css("top", "30px");
}
else {
clearTimeout(playerInfoHoverTimer);
}
},
() => {
playerInfoHoverTimer = setTimeout(() => {
$("#audio-info").css("opacity", 0.0);
$("#audio-info").css("top", "0px");
playerInfoHoverTimer = 0;
}, 2500);
});
| Yordrar/pulse | mainWin/js/player.js | JavaScript | gpl-3.0 | 6,544 |
/*
Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Webcampak.
If not, see http://www.gnu.org/licenses/.
*/
console.log('Log: Load: Webcampak.view.permissions.PermissionsWindow');
Ext.define('Webcampak.view.permissions.PermissionsWindow' ,{
extend: 'Ext.window.Window',
alias: 'widget.permissionswindow',
requires: [
'Webcampak.view.permissions.GroupsWindow',
'Webcampak.view.permissions.SourcesWindow',
'Webcampak.view.permissions.UsersWindow'
],
iconCls: 'icon-user',
title: i18n.gettext('Manage Permissions & interface settings'),
layout: 'fit',
width: 900,
//height: 400,
scroll: true,
autoScroll: true,
maximizable: true,
minimizable: true,
closeAction : 'hide',
items: [{
xtype: 'tabpanel',
items: [{
title: i18n.gettext('Users'),
itemID: 'users',
xtype: 'userswindow',
border: 0
}, {
title: i18n.gettext('Groups'),
itemID: 'openGroupsTab',
layout: 'fit',
items: [{
xtype: 'groupwindow'
}]
}, {
title: i18n.gettext('Companies'),
itemID: 'companies',
xtype: 'companylist',
border: 0
}, {
title: i18n.gettext('Sources'),
itemID: 'sources',
layout: 'fit',
items: [{
xtype: 'sourcewindow'
}]
}]
}]
});
| Webcampak/v2.0 | src/www/interface/dev/app/view/permissions/PermissionsWindow.js | JavaScript | gpl-3.0 | 1,869 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cmdr.TsiLib.FormatXml.Base
{
public enum TsiXmlEntryType
{
Boolean = 0,
Integer = 1,
Float = 2,
String = 3,
ListOfBoolean = 4,
ListOfInteger = 5,
ListOfFloat = 6,
ListOfString = 7
}
}
| TakTraum/cmdr | cmdr/cmdr.TsiLib/FormatXml/Base/TsiXmlEntryType.cs | C# | gpl-3.0 | 410 |
/*
* Enesys : An NES Emulator
* Copyright (C) 2017 Rahul Chhabra and Waoss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.waoss.enesys.cpu.instructions;
import com.waoss.enesys.cpu.CentralProcessor;
import com.waoss.enesys.mem.Addressing;
import javafx.beans.property.*;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
/**
* Represents an instruction of the NES processor.<br>
* <p>An instruction object contains all the data : the name of the instruction,the opcode,the addressing mode,the
* arguments required for the instruction (a jump instruction takes in the new value of the program counter along)</p>
* For example,
* {@code
* Instruction instruction = new Instruction(InstructionName.ADC, Addressing.ABSOLUTE);
* instruction.getOpCode(); // works fine
* instruction.setArguments(5); // the arguments
* }
* <p>Addressing is also handled because every time there is a change in the arguments;their is an update according to
* the addressing mode</p>
*/
public final class Instruction {
/**
* This property holds the instruction name
*/
private final AtomicReference<SimpleObjectProperty<InstructionName>> instructionName = new AtomicReference<>(
new SimpleObjectProperty<>(this, "instructionName"));
/**
* This property holds the opcode
*/
private final AtomicReference<SimpleObjectProperty<Integer>> opCode = new AtomicReference<>(
new SimpleObjectProperty<>(this, "opCode"));
/**
* This property holds the addressing mode
*/
private final AtomicReference<SimpleObjectProperty<Addressing>> addressing = new AtomicReference<>(new SimpleObjectProperty<>(this, "addressing"));
/**
* This property stores the arguments<br>
* For example, a branching instruction would have one argument: where to go if condition is true
*/
private final AtomicReference<SimpleObjectProperty<Integer[]>> arguments = new AtomicReference<>(
new SimpleObjectProperty<>(this, "arguments"));
private final AtomicReference<IntegerProperty> size = new AtomicReference<>(
new SimpleIntegerProperty(this, "size", 0));
private final AtomicReference<SimpleObjectProperty<CentralProcessor>> centralProcessor = new AtomicReference<>(
new SimpleObjectProperty<>(this, "centralProcessor"));
{
/*
This ensures that if arguments change the size also changes because size is actually the length of the arguments
and the addressing mode is recognised an the arguments
are parsed accordingly.
*/
arguments.get().addListener((observable, oldValue, newValue) -> size.get().set(newValue.length));
}
/**
* Creates a new Instruction when given the name and addressing
*
* @param instructionName
* The name
* @param addressing
* The Addressing mode
*/
public Instruction(InstructionName instructionName, Addressing addressing) {
this.instructionName.get().set(instructionName);
this.addressing.get().set(addressing);
}
/**
* Creates a new Instruction given the opcode and addressing
*
* @param opcode
* The opcode
* @param addressing
* The addressing mode
*/
public Instruction(Integer opcode, Addressing addressing) {
this.opCode.get().set(opcode);
this.addressing.get().set(addressing);
this.instructionName.get().set(InstructionName.getByOpCode(opcode));
}
public InstructionName getInstructionName() {
return instructionName.get().get();
}
public void setInstructionName(InstructionName instructionName) {
this.instructionName.get().set(instructionName);
}
public final ObjectProperty<InstructionName> instructionNameProperty() {
return instructionName.get();
}
public Integer getOpCode() {
return opCode.get().get();
}
public void setOpCode(Integer opCode) {
this.opCode.get().set(opCode);
}
public final ObjectProperty<Integer> opCodeProperty() {
return opCode.get();
}
public Addressing getAddressing() {
return addressing.get().get();
}
public void setAddressing(Addressing addressing) {
this.addressing.get().set(addressing);
}
public final ObjectProperty<Addressing> addressingProperty() {
return addressing.get();
}
public Integer[] getArguments() {
return arguments.get().get();
}
public void setArguments(Integer... arguments) {
this.arguments.get().set(arguments);
}
public ObjectProperty<Integer[]> argumentsProperty() {
return arguments.get();
}
public int getSize() {
return size.get().get();
}
public void setSize(int size) {
this.size.get().set(size);
}
public final IntegerProperty sizeProperty() {
return size.get();
}
public CentralProcessor getCentralProcessor() {
return centralProcessor.get().get();
}
public void setCentralProcessor(final CentralProcessor centralProcessor) {
this.centralProcessor.get().set(centralProcessor);
}
public final ObjectProperty<CentralProcessor> centralProcessorProperty() {
return centralProcessor.get();
}
/**
* Parses itself according to the arguments and addressing
*/
public void parseArgumentsAccordingToAddressing() {
final Addressing addressing = getAddressing();
final Integer[] givenArguments = argumentsProperty().get();
/*
If there are no arguments it is safe to assume that the instruction does not require any results from us.
This type of addressing is handled but not inferring nullity is shitty af.Wish I was using Kotlin
*/
final Integer[] resultArguments = givenArguments != null ? Arrays.copyOf(givenArguments, givenArguments.length) : null;
final CentralProcessor centralProcessor = getCentralProcessor();
switch (addressing) {
case ABSOLUTE:
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(givenArguments[0]);
}
break;
case ABSOLUTE_X:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0] + centralProcessor.getXRegister().getValue();
}
break;
case ABSOLUTE_Y:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0] + centralProcessor.getYRegister().getValue();
}
break;
case ACCUMULATOR:
break;
case IMMEDIATE:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0];
}
break;
case IMPLIED:
break;
case INDEXED_INDIRECT:
Integer postXAddress = null;
if (givenArguments != null) {
postXAddress = givenArguments[0] + centralProcessor.getXRegister().getValue();
}
Integer mostSignificantByte = centralProcessor.getCompleteMemory().read(postXAddress + 1);
Integer leastSignificantByte = centralProcessor.getCompleteMemory().read(postXAddress);
Integer finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case INDIRECT:
mostSignificantByte = givenArguments != null ? givenArguments[1] : null;
leastSignificantByte = givenArguments != null ? givenArguments[0] : null;
finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case INDIRECT_INDEXED:
Integer addressToLookup = givenArguments != null ? givenArguments[0] : null;
mostSignificantByte = centralProcessor.getCompleteMemory().read(addressToLookup + 1);
leastSignificantByte = centralProcessor.getCompleteMemory().read(addressToLookup);
finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
finalAddress += centralProcessor.getYRegister().getValue();
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case RELATIVE:
Byte rawAddress = givenArguments != null ? givenArguments[0].byteValue() : 0;
if (resultArguments != null) {
resultArguments[0] = rawAddress.intValue();
}
break;
case ZERO_PAGE:
addressToLookup = givenArguments != null ? givenArguments[0] : null;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(addressToLookup);
}
break;
case ZERO_PAGE_X:
Integer zeroPageAddressToLookup = givenArguments != null ? givenArguments[0] : 0;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(zeroPageAddressToLookup);
}
if (resultArguments != null) {
resultArguments[0] += centralProcessor.getXRegister().getValue();
}
break;
case ZERO_PAGE_Y:
zeroPageAddressToLookup = givenArguments != null ? givenArguments[0] : 0;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(zeroPageAddressToLookup);
}
if (resultArguments != null) {
resultArguments[0] += centralProcessor.getYRegister().getValue();
}
break;
}
setArguments(resultArguments);
}
}
| Waoss/Enesys | enesys/src/main/java/com/waoss/enesys/cpu/instructions/Instruction.java | Java | gpl-3.0 | 11,105 |
import datetime
from ecl.util.util import BoolVector
from ecl.util.test import TestAreaContext
from tests import ResTest
from res.enkf import ObsBlock
class ObsBlockTest(ResTest):
def test_create(self):
block = ObsBlock("OBS" , 1000)
self.assertTrue( isinstance( block , ObsBlock ))
self.assertEqual( 1000 , block.totalSize())
self.assertEqual( 0 , block.activeSize())
def test_access(self):
obs_size = 10
block = ObsBlock("OBS" , obs_size)
with self.assertRaises(IndexError):
block[100] = (1,1)
with self.assertRaises(IndexError):
block[-100] = (1,1)
with self.assertRaises(TypeError):
block[4] = 10
with self.assertRaises(TypeError):
block[4] = (1,1,9)
#------
with self.assertRaises(IndexError):
v = block[100]
with self.assertRaises(IndexError):
v = block[-100]
block[0] = (10,1)
v = block[0]
self.assertEqual( v , (10,1))
self.assertEqual( 1 , block.activeSize())
block[-1] = (17,19)
self.assertEqual( block[-1], (17,19))
| andreabrambilla/libres | python/tests/res/enkf/test_obs_block.py | Python | gpl-3.0 | 1,177 |
<?php
require_once __CA_BASE_DIR__ . '/vendor/phpoffice/phpexcel/Classes/PHPExcel.php';
require_once __CA_BASE_DIR__ . '/vendor/phpoffice/phpexcel/Classes/PHPExcel/Writer/Excel2007.php';
$campagnes = $this->getVar('campagnes');
$rd = $this->getVar('rd');
$vo_phpexcel = new PHPExcel();
$vo_phpexcel->getProperties()->setCreator("CollectiveAccess - recolement SMF");
$vo_phpexcel->getProperties()->setLastModifiedBy("CollectiveAccess - recolement SMF");
$vo_phpexcel->getProperties()->setTitle("Tableau de suivi du récolement décennal");
$vo_phpexcel->getProperties()->setSubject("Tableau de suivi du récolement décennal");
$vo_phpexcel->getProperties()->setDescription("Office 2003 XLS – By Webdev – With PHPExel");
$vo_phpexcel->setActiveSheetIndex(0);
$sheet = $vo_phpexcel->getActiveSheet();
$sheet->setTitle('tableau de suivi');
$sheet->SetCellValue('A1', 'Tableau de suivi '.$rd);
if (!isset($campagnes) || !$campagnes) {
$sheet->SetCellValue('A3', "Aucune campagne de récolement n'est accessible.");
} else {
$line = 3;
$sheet->SetCellValue('A3', "Localisation");
$sheet->SetCellValue('B3', "Localisation (code)");
$sheet->SetCellValue('C3', "Caractérisation espace");
$sheet->SetCellValue('D3', "Type de collection\n(champ couvert)");
$sheet->SetCellValue('E3', "Conditionnement des biens à récoler");
$sheet->SetCellValue('F3', "Nombre\nd'objets");
$sheet->SetCellValue('G3', "Accessibilité");
$sheet->SetCellValue('H3', "Campagne");
$sheet->SetCellValue('I3', "Intervenants");
$sheet->SetCellValue('J3', "Dates\nprévisionnelles");
$sheet->SetCellValue('K3', "Dates\neffectives");
$sheet->SetCellValue('L3', "Procès verbal");
for ($column = 'A'; $column <= 'L'; $column++) {
$cell = $column . $line;
//Largeur
$sheet->getColumnDimension($column)->setWidth(16.5);
//Mettre une bordure sur une case
$sheet->getStyle($cell)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getFont()->setBold(true);
}
$line++;
//Reset largeur colonne F (nombre)
$sheet->getColumnDimension('F')->setWidth(10);
foreach ($campagnes as $campagne) {
$sheet->SetCellValue('A' . $line, $campagne["localisation"]);
$sheet->SetCellValue('B' . $line, $campagne["localisation_code"]);
$sheet->SetCellValue('C' . $line, $campagne["caracterisation"]);
$sheet->SetCellValue('D' . $line, $campagne["champs"]);
$sheet->SetCellValue('E' . $line, $campagne["conditionnement"]);
$sheet->SetCellValue('F' . $line, $campagne["nombre"]);
$sheet->SetCellValue('G' . $line, $campagne["accessibilite"]);
$sheet->SetCellValue('H' . $line, $campagne["idno"] . " : " . $campagne["name"]);
$sheet->SetCellValue('I' . $line, $campagne["intervenants"]);
$sheet->SetCellValue('J' . $line, $campagne["date_campagne_prev"]);
$sheet->SetCellValue('K' . $line, $campagne["date_campagne"]);
$sheet->SetCellValue('L' . $line, $campagne["date_campagne_pv"]);
//Bordures
for ($column = 'A'; $column <= 'L'; $column++) {
$cell = $column . $line;
//Mettre une bordure sur une case
$sheet->getStyle($cell)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$sheet->getStyle($cell)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
}
$sheet->getRowDimension(1)->setRowHeight(-1);
$line++;
}
//Gérer le style de la police
$sheet->getStyle('A1')->getFont()->setSize(16);
$sheet->getStyle('A1')->getFont()->setBold(true);
$sheet->getRowDimension('3')->setRowHeight(33);
$sheet->duplicateStyleArray(
array(
'alignment' => array(
'wrap' => true,
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
)
), 'A3:L3');
$sheet->duplicateStyleArray(
array(
'alignment' => array(
'wrap' => true,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
)
), 'A4:L256');
}
$vo_phpexcel_writer = new PHPExcel_Writer_Excel2007($vo_phpexcel);
$vo_phpexcel_writer->save(__CA_BASE_DIR__ . "/app/plugins/museesDeFrance/download/tableau-suivi.xlsx");
?>
<h1><?php print $rd; ?></h1>
<h2>Tableau de suivi</h2>
<p>Vous pouvez télécharger depuis cette page le fichier au format .xls (Microsoft Excel).<br/> Ce fichier est lisible
également avec OpenOffice ou LibreOffice.</p>
<a class="form-button" href="<?php print __CA_URL_ROOT__; ?>/app/plugins/museesDeFrance/download/tableau-suivi.xlsx">
<span class="form-button">
<img class="form-button-left"
src="<?php print __CA_URL_ROOT__; ?>/app/plugins/museesDeFrance/views/images/page_white_excel.png"
align=center>
télécharger
</span>
</a>
| ideesculture/museesDeFrance | views/recolement_tableau_suivi_html.php | PHP | gpl-3.0 | 5,336 |
if (typeof FormTarget === 'undefined') {
FormTarget = {};
}
FormTarget.arrayrun = (function($) {
/*
* Expected config {
* isAdmin: boolean,
* instruments: array
* }
*/
return {
getUserManualUrl: function() {
return Urls.external.userManual('array_runs');
},
getSaveUrl: function(arrayrun) {
return arrayrun.id ? Urls.rest.arrayRuns.update(arrayrun.id) : Urls.rest.arrayRuns.create;
},
getSaveMethod: function(arrayrun) {
return arrayrun.id ? 'PUT' : 'POST';
},
getEditUrl: function(arrayrun) {
return Urls.ui.arrayRuns.edit(arrayrun.id);
},
getSections: function(config, object) {
return [{
title: 'Array Run Information',
fields: [{
title: 'Array Run ID',
data: 'id',
type: 'read-only',
getDisplayValue: function(arrayrun) {
return arrayrun.id || 'Unsaved';
}
}, {
title: 'Instrument',
data: 'instrumentId',
type: 'dropdown',
include: !object.id,
required: true,
nullValue: 'SELECT',
source: config.instruments,
getItemLabel: Utils.array.getName,
getItemValue: Utils.array.getId,
sortSource: Utils.sorting.standardSort('name')
}, {
title: 'Instrument',
data: 'instrumentId',
type: 'read-only',
include: !!object.id,
getDisplayValue: function(arrayrun) {
return arrayrun.instrumentName;
}
}, {
title: 'Alias',
data: 'alias',
type: 'text',
required: true,
maxLength: 255
}, {
title: 'Description',
data: 'description',
type: 'text',
maxLength: 255
}, {
title: 'Run Path',
data: 'filePath',
type: 'text',
maxLength: 255
}, {
title: 'Array',
data: 'arrayId',
type: 'read-only',
getDisplayValue: function(arrayrun) {
return arrayrun.arrayAlias;
},
getLink: function(arrayrun) {
return Urls.ui.arrays.edit(arrayrun.arrayId);
}
}, {
title: 'Change Array',
type: 'special',
makeControls: function(form) {
return [$('<button>').addClass('ui-state-default').attr('type', 'button').text('Search').click(function() {
Utils.showDialog('Array Search', 'Search', [{
label: 'Search',
property: 'query',
type: 'text',
required: true
}], function(formData) {
Utils.ajaxWithDialog('Searching', 'GET', Urls.rest.arrayRuns.arraySearch + '?' + jQuery.param({
q: formData.query
}), null, function(data) {
if (!data || !data.length) {
Utils.showOkDialog('Search Results', ['No matching arrays found']);
return;
} else {
Utils.showWizardDialog('Search Results', data.map(function(array) {
return {
name: array.alias,
handler: function() {
form.updateField('arrayId', {
value: array.id,
label: array.alias,
link: Urls.ui.arrays.edit(array.id)
});
updateSamplesTable(array);
}
};
}));
}
});
});
}), $('<button>').addClass('ui-state-default').attr('type', 'button').text('Remove').click(function() {
if (form.get('arrayId')) {
Utils.showConfirmDialog("Remove Array", "Remove", ["Remove the array from this array run?"], function() {
form.updateField('arrayId', {
value: null,
label: '',
link: null
});
updateSamplesTable(null);
});
} else {
Utils.showOkDialog('Remove Array', ['No array set']);
}
})];
}
}, {
title: 'Status',
data: 'status',
type: 'dropdown',
required: true,
source: Constants.healthTypes,
getItemLabel: function(item) {
return item.label;
},
getItemValue: function(item) {
return item.label;
},
onChange: function(newValue, form) {
var status = getStatus(newValue);
var updates = {
required: status.isDone,
// Editable if run is done and either there's no value set or user is admin
disabled: !status.isDone || (form.get('completionDate') && !config.isAdmin)
};
if (!status.isDone) {
updates.value = null;
}
form.updateField('completionDate', updates);
},
// Only editable by admin if run is done
disabled: !object.status ? false : (getStatus(object.status).isDone && !config.isAdmin)
}, {
title: 'Start Date',
data: 'startDate',
type: 'date',
required: true,
disabled: object.startDate && !config.isAdmin
}, {
title: 'Completion Date',
data: 'completionDate',
type: 'date'
}]
}];
}
}
function getStatus(label) {
return Utils.array.findUniqueOrThrow(function(item) {
return item.label === label;
}, Constants.healthTypes);
}
function updateSamplesTable(array) {
$('#listingSamplesTable').empty();
var data = [];
var lengthOptions = [50, 25, 10];
if (array) {
data = array.samples.map(function(sample) {
return [sample.coordinates, Box.utils.hyperlinkifyBoxable(sample.name, sample.id, sample.name),
Box.utils.hyperlinkifyBoxable(sample.name, sample.id, sample.alias)];
});
lengthOptions.unshift(array.columns * array.rows);
}
$('#listingSamplesTable')
.dataTable(
{
"aaData": data,
"aoColumns": [{
"sTitle": "Position"
}, {
"sTitle": "Sample Name"
}, {
"sTitle": "Sample Alias"
}],
"bJQueryUI": true,
"bDestroy": true,
"aLengthMenu": [lengthOptions, lengthOptions],
"iDisplayLength": lengthOptions[0],
"sPaginationType": "full_numbers",
"sDom": '<"#toolbar.fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"lf>r<t><"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>',
"aaSorting": [[0, "asc"]]
}).css("width", "100%");
}
})(jQuery);
| TGAC/miso-lims | miso-web/src/main/webapp/scripts/form_arrayrun.js | JavaScript | gpl-3.0 | 7,102 |
import { combineReducers } from 'redux';
import { ADDED_ACCEPTOR_CAREER,
DELETED_ACCEPTOR_CAREER,
INIT_ACCEPTOR_CAREER_HISTORY,
FETCH_FAILED, FETCHING } from '../../constants';
const error = (state = null, action) => {
switch (action.type) {
case FETCH_FAILED:
return action.error;
default:
return null;
}
};
const data = (state = [], action) => {
switch (action.type) {
case INIT_ACCEPTOR_CAREER_HISTORY:
return action.careerHistory;
case ADDED_ACCEPTOR_CAREER:
return [...state, action.career];
case DELETED_ACCEPTOR_CAREER:
return state.filter(({ name, year }) =>
name !== action.career.name || year !== action.career.year);
default:
return state;
}
};
const toast = (state = {
show: false,
}, action) => {
switch (action.type) {
case FETCHING:
return {
show: true,
text: '请稍候',
icon: 'loading',
};
case ADDED_ACCEPTOR_CAREER:
case DELETED_ACCEPTOR_CAREER:
return {
show: true,
text: '操作成功',
icon: 'toast',
};
default:
return {
show: false,
};
}
};
export default combineReducers({
data,
error,
toast,
});
| nagucc/jkef-wxe | src/reducers/acceptors/career.js | JavaScript | gpl-3.0 | 1,229 |
# frozen_string_literal: true
module SupplejackCommon
# Scope Class
class Scope
def initialize(klass, options)
@klass = klass
@scope_options = options
end
def attribute(name, options = {})
new_options = @scope_options.dup
if_options = new_options[:if]
if if_options.is_a?(Hash)
new_options[:if] = Hash[if_options.map do |key, value|
value = options.values.first if options.keys.first == value
[key, value]
end]
end
@klass.send(:attribute, name, new_options)
end
def attributes(*args)
options = args.extract_options!
args.each do |attribute|
self.attribute(attribute, options)
end
end
end
end
| DigitalNZ/supplejack_common | lib/supplejack_common/scope.rb | Ruby | gpl-3.0 | 732 |
# -*- coding: utf-8 -*-
"""Configure batch3dfier with the input data."""
import os.path
from subprocess import call
from shapely.geometry import shape
from shapely import geos
from psycopg2 import sql
import fiona
def call_3dfier(db, tile, schema_tiles,
pc_file_name, pc_tile_case, pc_dir,
table_index_pc, fields_index_pc,
table_index_footprint, fields_index_footprint, uniqueid,
extent_ewkb, clip_prefix, prefix_tile_footprint,
yml_dir, tile_out, output_format, output_dir,
path_3dfier, thread):
"""Call 3dfier with the YAML config created by yamlr().
Note
----
For the rest of the parameters see batch3dfier_config.yml.
Parameters
----------
db : db Class instance
tile : str
Name of of the 2D tile.
schema_tiles : str
Schema of the footprint tiles.
pc_file_name : str
Naming convention for the pointcloud files. See 'dataset_name' in batch3dfier_config.yml.
pc_tile_case : str
How the string matching is done for pc_file_name. See 'tile_case' in batch3dfier_config.yml.
pc_dir : str
Directory of the pointcloud files. See 'dataset_dir' in batch3dfier_config.yml.
thread : str
Name/ID of the active thread.
extent_ewkb : str
EWKB representation of 'extent' in batch3dfier_config.yml.
clip_prefix : str
Prefix for naming the clipped/united views. This value shouldn't be a substring of the pointcloud file names.
prefix_tile_footprint : str or None
Prefix prepended to the footprint tile view names. If None, the views are named as
the values in fields_index_fooptrint['unit_name'].
Returns
-------
list
The tiles that are skipped because no corresponding pointcloud file
was found in 'dataset_dir' (YAML)
"""
pc_tiles = find_pc_tiles(db, table_index_pc, fields_index_pc,
table_index_footprint, fields_index_footprint,
extent_ewkb, tile_footprint=tile,
prefix_tile_footprint=prefix_tile_footprint)
pc_path = find_pc_files(pc_tiles, pc_dir, pc_file_name, pc_tile_case)
# prepare output file name
if not tile_out:
tile_out = tile.replace(clip_prefix, '', 1)
# Call 3dfier ------------------------------------------------------------
if pc_path:
# Needs a YAML per thread so one doesn't overwrite it while the other
# uses it
yml_name = thread + "_config.yml"
yml_path = os.path.join(yml_dir, yml_name)
config = yamlr(dbname=db.dbname, host=db.host, user=db.user,
pw=db.password, schema_tiles=schema_tiles,
bag_tile=tile, pc_path=pc_path,
output_format=output_format, uniqueid=uniqueid)
# Write temporary config file
try:
with open(yml_path, "w") as text_file:
text_file.write(config)
except BaseException:
print("Error: cannot write _config.yml")
# Prep output file name
if "obj" in output_format.lower():
o = tile_out + ".obj"
output_path = os.path.join(output_dir, o)
elif "csv" in output_format.lower():
o = tile_out + ".csv"
output_path = os.path.join(output_dir, o)
else:
output_path = os.path.join(output_dir, tile_out)
# Run 3dfier
command = (path_3dfier + " {yml} -o {out}").format(
yml=yml_path, out=output_path)
try:
call(command, shell=True)
except BaseException:
print("\nCannot run 3dfier on tile " + tile)
tile_skipped = tile
else:
print(
"\nPointcloud file(s) " +
str(pc_tiles) +
" not available. Skipping tile.\n")
tile_skipped = tile
return({'tile_skipped': tile_skipped,
'out_path': None})
return({'tile_skipped': None,
'out_path': output_path})
def yamlr(dbname, host, user, pw, schema_tiles,
bag_tile, pc_path, output_format, uniqueid):
"""Parse the YAML config file for 3dfier.
Parameters
----------
See batch3dfier_config.yml.
Returns
-------
string
the YAML config file for 3dfier
"""
pc_dataset = ""
if len(pc_path) > 1:
for p in pc_path:
pc_dataset += "- " + p + "\n" + " "
else:
pc_dataset += "- " + pc_path[0]
# !!! Do not correct the indentation of the config template, otherwise it
# results in 'YAML::TypedBadConversion<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >'
# because every line is indented as here
config = """
input_polygons:
- datasets:
- "PG:dbname={dbname} host={host} user={user} password={pw} schemas={schema_tiles} tables={bag_tile}"
uniqueid: {uniqueid}
lifting: Building
lifting_options:
Building:
height_roof: percentile-90
height_floor: percentile-10
lod: 1
input_elevation:
- datasets:
{pc_path}
omit_LAS_classes:
thinning: 0
options:
building_radius_vertex_elevation: 2.0
radius_vertex_elevation: 1.0
threshold_jump_edges: 0.5
output:
format: {output_format}
building_floor: true
vertical_exaggeration: 0
""".format(dbname=dbname,
host=host,
user=user,
pw=pw,
schema_tiles=schema_tiles,
bag_tile=bag_tile,
uniqueid=uniqueid,
pc_path=pc_dataset,
output_format=output_format)
return(config)
def find_pc_files(pc_tiles, pc_dir, pc_file_name, pc_tile_case):
"""Find pointcloud files in the file system when given a list of pointcloud tile names
"""
# Prepare AHN file names -------------------------------------------------
if pc_tile_case == "upper":
tiles = [pc_file_name.format(tile=t.upper()) for t in pc_tiles]
elif pc_tile_case == "lower":
tiles = [pc_file_name.format(tile=t.lower()) for t in pc_tiles]
elif pc_tile_case == "mixed":
tiles = [pc_file_name.format(tile=t) for t in pc_tiles]
else:
raise "Please provide one of the allowed values for pc_tile_case."
# use the tile list in tiles to parse the pointcloud file names
pc_path = [os.path.join(pc_dir, pc_tile) for pc_tile in tiles]
if all([os.path.isfile(p) for p in pc_path]):
return(pc_path)
else:
return(None)
def find_pc_tiles(db, table_index_pc, fields_index_pc,
table_index_footprint=None, fields_index_footprint=None,
extent_ewkb=None, tile_footprint=None,
prefix_tile_footprint=None):
"""Find pointcloud tiles in tile index that intersect the extent or the footprint tile.
Parameters
----------
prefix_tile_footprint : str or None
Prefix prepended to the footprint tile view names. If None, the views are named as
the values in fields_index_fooptrint['unit_name'].
"""
if extent_ewkb:
tiles = get_2Dtiles(db, table_index_pc, fields_index_pc, extent_ewkb)
else:
schema_pc_q = sql.Identifier(table_index_pc['schema'])
table_pc_q = sql.Identifier(table_index_pc['table'])
field_pc_geom_q = sql.Identifier(fields_index_pc['geometry'])
field_pc_unit_q = sql.Identifier(fields_index_pc['unit_name'])
schema_ftpr_q = sql.Identifier(table_index_footprint['schema'])
table_ftpr_q = sql.Identifier(table_index_footprint['table'])
field_ftpr_geom_q = sql.Identifier(fields_index_footprint['geometry'])
field_ftpr_unit_q = sql.Identifier(fields_index_footprint['unit_name'])
if prefix_tile_footprint:
tile_footprint = tile_footprint.replace(
prefix_tile_footprint, '', 1)
tile_q = sql.Literal(tile_footprint)
query = sql.SQL("""
SELECT
{table_pc}.{field_pc_unit}
FROM
{schema_pc}.{table_pc},
{schema_ftpr}.{table_ftpr}
WHERE
{table_ftpr}.{field_ftpr_unit} = {tile}
AND st_intersects(
{table_pc}.{field_pc_geom},
{table_ftpr}.{field_ftpr_geom}
);
""").format(table_pc=table_pc_q,
field_pc_unit=field_pc_unit_q,
schema_pc=schema_pc_q,
schema_ftpr=schema_ftpr_q,
table_ftpr=table_ftpr_q,
field_ftpr_unit=field_ftpr_unit_q,
tile=tile_q,
field_pc_geom=field_pc_geom_q,
field_ftpr_geom=field_ftpr_geom_q)
resultset = db.getQuery(query)
tiles = [tile[0] for tile in resultset]
return(tiles)
def extent_to_ewkb(db, table_index, file):
"""Reads a polygon from a file and returns its EWKB.
I didn't find a simple way to safely get SRIDs from the input geometry
with Shapely, therefore it is obtained from the database and the CRS of the
polygon is assumed to be the same as of the tile indexes.
Parameters
----------
db : db Class instance
table_index : dict
{'schema' : str, 'table' : str} of the table of tile index.
file : str
Path to the polygon for clipping the input.
Must be in the same CRS as the table_index.
Returns
-------
[Shapely polygon, EWKB str]
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
query = sql.SQL("""SELECT st_srid(geom) AS srid
FROM {schema}.{table}
LIMIT 1;""").format(schema=schema, table=table)
srid = db.getQuery(query)[0][0]
assert srid is not None
# Get clip polygon and set SRID
with fiona.open(file, 'r') as src:
poly = shape(src[0]['geometry'])
# Change a the default mode to add this, if SRID is set
geos.WKBWriter.defaults['include_srid'] = True
# set SRID for polygon
geos.lgeos.GEOSSetSRID(poly._geom, srid)
ewkb = poly.wkb_hex
return([poly, ewkb])
def get_2Dtiles(db, table_index, fields_index, ewkb):
"""Returns a list of tiles that overlap the output extent.
Parameters
----------
db : db Class instance
table_index : dict
{'schema' : str, 'table' : str} of the table of tile index.
fields_index : dict
{'primary_key' : str, 'geometry' : str, 'unit_name' : str}
primary_key: Name of the primary_key field in table_index.
geometry: Name of the geometry field in table_index.
unit: Name of the field in table_index that contains the index unit names.
ewkb : str
EWKB representation of a polygon.
Returns
-------
[tile IDs]
Tiles that are intersected by the polygon that is provided in 'extent' (YAML).
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
field_idx_geom_q = sql.Identifier(fields_index['geometry'])
field_idx_unit_q = sql.Identifier(fields_index['unit_name'])
ewkb_q = sql.Literal(ewkb)
# TODO: user input for a.unit
query = sql.SQL("""
SELECT {table}.{field_idx_unit}
FROM {schema}.{table}
WHERE st_intersects({table}.{field_idx_geom}, {ewkb}::geometry);
""").format(schema=schema,
table=table,
field_idx_unit=field_idx_unit_q,
field_idx_geom=field_idx_geom_q,
ewkb=ewkb_q)
resultset = db.getQuery(query)
tiles = [tile[0] for tile in resultset]
print("Nr. of tiles in clip extent: " + str(len(tiles)))
return(tiles)
def get_2Dtile_area(db, table_index):
"""Get the area of a 2D tile.
Note
----
Assumes that all tiles have equal area. Area is in units of the tile CRS.
Parameters
----------
db : db Class instance
table_index : list of str
{'schema' : str, 'table' : str} of the table of tile index.
Returns
-------
float
"""
schema = sql.Identifier(table_index['schema'])
table = sql.Identifier(table_index['table'])
query = sql.SQL("""
SELECT public.st_area(geom) AS area
FROM {schema}.{table}
LIMIT 1;
""").format(schema=schema, table=table)
area = db.getQuery(query)[0][0]
return(area)
def get_2Dtile_views(db, schema_tiles, tiles):
"""Get View names of the 2D tiles. It tries to find views in schema_tiles
that contain the respective tile ID in their name.
Parameters
----------
db : db Class instance
schema_tiles: str
Name of the schema where the 2D tile views are stored.
tiles : list
Tile IDs
Returns
-------
list
Name of the view that contain the tile ID as substring.
"""
# Get View names for the tiles
t = ["%" + str(tile) + "%" for tile in tiles]
t = sql.Literal(t)
schema_tiles = sql.Literal(schema_tiles)
query = sql.SQL("""SELECT table_name
FROM information_schema.views
WHERE table_schema = {}
AND table_name LIKE any({});
""").format(schema_tiles, t)
resultset = db.getQuery(query)
tile_views = [tile[0] for tile in resultset]
return(tile_views)
def clip_2Dtiles(db, user_schema, schema_tiles, tiles, poly, clip_prefix,
fields_view):
"""Creates views for the clipped tiles.
Parameters
----------
db : db Class instance
user_schema: str
schema_tiles : str
tiles : list
poly : Shapely polygon
clip_prefix : str
Returns
-------
list
Name of the views of the clipped tiles.
"""
user_schema = sql.Identifier(user_schema)
schema_tiles = sql.Identifier(schema_tiles)
tiles_clipped = []
fields_all = fields_view['all']
field_geom_q = sql.Identifier(fields_view['geometry'])
for tile in tiles:
t = clip_prefix + tile
tiles_clipped.append(t)
view = sql.Identifier(t)
tile_view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
wkb = sql.Literal(poly.wkb_hex)
query = sql.SQL("""
CREATE OR REPLACE VIEW {user_schema}.{view} AS
SELECT
{fields}
FROM
{schema_tiles}.{tile_view}
WHERE
st_within({tile_view}.{geom}, {wkb}::geometry)"""
).format(user_schema=user_schema,
schema_tiles=schema_tiles,
view=view,
fields=fields_q,
tile_view=tile_view,
geom=field_geom_q,
wkb=wkb)
db.sendQuery(query)
try:
db.conn.commit()
print(
str(
len(tiles_clipped)) +
" views with prefix '{}' are created in schema {}.".format(
clip_prefix,
user_schema))
except BaseException:
print("Cannot create view {user_schema}.{clip_prefix}{tile}".format(
schema_tiles=schema_tiles, clip_prefix=clip_prefix))
db.conn.rollback()
return(tiles_clipped)
def union_2Dtiles(db, user_schema, tiles_clipped, clip_prefix, fields_view):
"""Union the clipped tiles into a single view.
Parameters
----------
db : db Class instance
user_schema : str
tiles_clipped : list
clip_prefix : str
Returns
-------
str
Name of the united view.
"""
# Check if there are enough tiles to unite
assert len(tiles_clipped) > 1, "Need at least 2 tiles for union"
user_schema = sql.Identifier(user_schema)
u = "{clip_prefix}union".format(clip_prefix=clip_prefix)
union_view = sql.Identifier(u)
sql_query = sql.SQL("CREATE OR REPLACE VIEW {user_schema}.{view} AS ").format(
user_schema=user_schema, view=union_view)
fields_all = fields_view['all']
for tile in tiles_clipped[:-1]:
view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
sql_subquery = sql.SQL("""SELECT {fields}
FROM {user_schema}.{view}
UNION ALL """).format(fields=fields_q,
user_schema=user_schema,
view=view)
sql_query = sql_query + sql_subquery
# The last statement
tile = tiles_clipped[-1]
view = sql.Identifier(tile)
fields_q = parse_sql_select_fields(tile, fields_all)
sql_subquery = sql.SQL("""SELECT {fields}
FROM {user_schema}.{view};
""").format(fields=fields_q,
user_schema=user_schema,
view=view)
sql_query = sql_query + sql_subquery
db.sendQuery(sql_query)
try:
db.conn.commit()
print("View {} created in schema {}.".format(u, user_schema))
except BaseException:
print("Cannot create view {}.{}".format(user_schema, u))
db.conn.rollback()
return(False)
return(u)
def get_view_fields(db, user_schema, tile_views):
"""Get the fields in a 2D tile view
Parameters
----------
tile_views : list of str
Returns
-------
{'all' : list, 'geometry' : str}
"""
if len(tile_views) > 0:
schema_q = sql.Literal(user_schema)
view_q = sql.Literal(tile_views[0])
resultset = db.getQuery(sql.SQL("""
SELECT
column_name
FROM
information_schema.columns
WHERE
table_schema = {schema}
AND table_name = {view};
""").format(schema=schema_q,
view=view_q))
f = [field[0] for field in resultset]
geom_res = db.getQuery(sql.SQL("""
SELECT
f_geometry_column
FROM
public.geometry_columns
WHERE
f_table_schema = {schema}
AND f_table_name = {view};
""").format(schema=schema_q,
view=view_q))
f_geom = geom_res[0][0]
fields = {}
fields['all'] = f
fields['geometry'] = f_geom
return(fields)
else:
return(None)
def parse_sql_select_fields(table, fields):
"""Parses a list of field names into "table"."field" to insert into a SELECT ... FROM table
Parameters
----------
fields : list of str
Returns
-------
psycopg2.sql.Composable
"""
s = []
for f in fields:
s.append(sql.SQL('.').join([sql.Identifier(table), sql.Identifier(f)]))
sql_fields = sql.SQL(', ').join(s)
return(sql_fields)
def drop_2Dtiles(db, user_schema, views_to_drop):
"""Drops Views in a given schema.
Note
----
Used for dropping the views created by clip_2Dtiles() and union_2Dtiles().
Parameters
----------
db : db Class instance
user_schema : str
views_to_drop : list
Returns
-------
bool
"""
user_schema = sql.Identifier(user_schema)
for view in views_to_drop:
view = sql.Identifier(view)
query = sql.SQL("DROP VIEW IF EXISTS {user_schema}.{view} CASCADE;").format(
user_schema=user_schema, view=view)
db.sendQuery(query)
try:
db.conn.commit()
print("Dropped {} in schema {}.".format(views_to_drop, user_schema))
# sql.Identifier("tile_index").as_string(dbs.conn)
return(True)
except BaseException:
print("Cannot drop views ", views_to_drop)
db.conn.rollback()
return(False) | balazsdukai/batch3dfier | batch3dfier/config.py | Python | gpl-3.0 | 20,894 |
package main.java.model;
import java.io.Serializable;
/**
* Abstrakte Oberklasse die den Namen und die Anzahl der Wahlberechtigten eines
* Gebiets haltet.
*/
public abstract class Gebiet implements Serializable {
/**
* Automatisch generierte serialVersionUID die fuer das De-/Serialisieren
* verwendet wird.
*/
private static final long serialVersionUID = -5067472345236494574L;
/** Der Name des Gebiets. */
private String name;
/** Zweitstimmenanzahl in ganz Deutschland. */
protected int zweitstimmeGesamt;
/**
* Gibt die Erststimmenanzahl aller Kandidaten im Gebiet.
*
* @return die Erststimmenanzahl aller Kandidaten.
*/
public abstract int getAnzahlErststimmen();
/**
* Gibt die anzahl der Zweitstimmen einer bestimmten Partei zur�ck.
*
* @param partei
* Die Partei zu der die Stimmen gegeben werden sollen.
* @return Die anzahl der Zweitstimmen einer bestimmten Partei.
*/
abstract public int getAnzahlErststimmen(Partei partei);
/**
* Gibt die Zweitstimmenanzahl aller Parteien im Gebiet.
*
* @return die Zweistimmenanzahl aller Partein.
*/
public abstract int getAnzahlZweitstimmen();
/**
* Gibt die anzahl der Zweitstimmen einer bestimmten Partei zur�ck.
*
* @param partei
* Die Partei zu der die Stimmen gegeben werden sollen.
* @return Die anzahl der Zweitstimmen einer bestimmten Partei.
*/
abstract public int getAnzahlZweitstimmen(Partei partei);
/**
* Gibt den Namen des Gebietes zurueck.
*
* @return der Name des Gebiets.
*/
public String getName() {
return this.name;
}
/**
* Gibt die Anzahl der Wahlberechtigten zurueck.
*
* @return die Anzahl der Wahlberechtigten.
*/
abstract public int getWahlberechtigte();
/**
* Setzt einen Namen fuer das Gebiet.
*
* @param name
* der Name des Gebiets.
* @throws IllegalArgumentException
* wenn der Name leer ist.
*/
public void setName(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException(
"Der Parameter \"name\" ist null oder ein leerer String!");
}
this.name = name;
}
/**
* Beschreibt dieses Gebiet.
*
* @return einen String der dieses Gebiet beschreibt.
*/
@Override
public String toString() {
return this.name;
}
}
| smolvo/OpenBundestagswahl | Implementierung/Mandatsrechner/src/main/java/model/Gebiet.java | Java | gpl-3.0 | 2,449 |
# Released under the GNU General Public License version 3 by J2897.
def get_page(page):
import urllib2
source = urllib2.urlopen(page)
return source.read()
title = 'WinSCP Updater'
target = 'Downloading WinSCP'
url = 'http://winscp.net/eng/download.php'
print 'Running: ' + title
print 'Target: ' + target
print 'URL: ' + url
try:
page = get_page(url)
except:
page = None
else:
print 'Got page...'
def msg_box(message, box_type):
import win32api
user_input = win32api.MessageBox(0, message, title, box_type)
return user_input
def stop():
import sys
sys.exit()
if page == None:
msg_box('Could not download the page. You may not be connected to the internet.', 0)
stop()
def find_site_ver(page):
T1 = page.find(target)
if T1 == -1:
return None, None
T2 = page.find('>WinSCP ', T1)
T3 = page.find('<', T2)
T4 = page.find('winscp', T3)
T5 = page.find('.exe', T4)
return page[T2+8:T3], page[T4:T5+4] # 5.1.5, winscp515setup.exe
try:
site_version, FN = find_site_ver(page)
except:
msg_box('Could not search the page.', 0)
stop()
else:
print 'Found: ' + site_version
if site_version == None:
msg_box('The search target has not been found on the page. The formatting, or the text on the page, may have been changed.', 0)
stop()
import os
tmp = os.getenv('TEMP')
PF = os.getenv('PROGRAMFILES')
WinSCP_exe = PF + '\\WinSCP\\WinSCP.exe'
DL = tmp + '\\' + FN
command = [DL, '/SILENT', '/NORESTART']
def DL_file():
import urllib
url = 'http://downloads.sourceforge.net/project/winscp/WinSCP/' + site_version + '/' + FN
urllib.urlretrieve(url, DL)
def sub_proc(command):
import subprocess
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return p.returncode # is 0 if success
def download_install():
try:
DL_file()
except:
msg_box('Failed to download ' + FN + ' to ' + tmp + '.', 0)
stop()
else:
print 'Downloaded: ' + FN
try:
RC = sub_proc(command)
except:
RC = None
if RC == None:
msg_box('Failed to execute ' + FN + '.', 0)
stop()
elif RC == 0:
msg_box('Successfully updated to version ' + site_version + '.', 0)
stop()
else:
msg_box('Successfully spawned new process for ' + FN + '. But the installation appears to have failed.', 0)
stop()
# Check if the WinSCP.exe file exists...
if not os.path.isfile(WinSCP_exe):
# No: Download and install WinSCP, and quit.
print 'WinSCP.exe file doesn\'t exist.'
print 'Installing WinSCP for the first time...'
download_install()
print 'Ending...'
delay(5)
stop()
import win32api
try:
info = win32api.GetFileVersionInfo(WinSCP_exe, "\\")
ms = info['FileVersionMS']
ls = info['FileVersionLS']
file_version = "%d.%d.%d.%d" % (win32api.HIWORD(ms), win32api.LOWORD (ms),
win32api.HIWORD (ls), win32api.LOWORD (ls))
except:
msg_box('Cannot find the file version of the local WinSCP.exe file.', 0)
stop()
else:
print 'Got local file version information...'
# Check if the site_version numbers are in the file_version numbers...
def clean(text):
import re
return re.sub('[^0-9]', '', text)
clean_site_version = clean(site_version)
clean_file_version = clean(file_version)[:len(clean_site_version)]
print 'Local version: ' + clean_file_version
print 'Site version: ' + clean_site_version
def delay(sec):
import time
time.sleep(sec)
if clean_file_version.find(clean_site_version) != -1:
# Yes: Quit.
print 'Match!'
print 'Ending...'
delay(5)
stop()
# Check if WinSCP is running...
def find_proc(exe):
import subprocess
cmd = 'WMIC PROCESS get Caption'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
if line.find(exe) != -1:
return True
while find_proc('WinSCP.exe'):
print 'WinSCP is running. Close WinSCP now!'
user_input = msg_box('There is a new version of WinSCP available. Please close WinSCP and press OK to continue.', 1)
if user_input == 1:
pass
elif user_input == 2:
stop()
# Now download and install the new file...
user_input = msg_box('If you use a custom WinSCP.ini file, back it up now and then press OK when you are ready to proceed with the update.', 1)
if user_input == 2:
stop()
download_install()
print 'Ending...'
delay(5)
| J2897/WinSCP_Updater | Update_WinSCP.py | Python | gpl-3.0 | 4,220 |
/******************************************************************************
*******************************************************************************
*******************************************************************************
libferris
Copyright (C) 2001 Ben Martin
libferris is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libferris is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with libferris. If not, see <http://www.gnu.org/licenses/>.
For more details see the COPYING file in the root directory of this
distribution.
$Id: UAsyncIO.hh,v 1.2 2010/09/24 21:31:06 ben Exp $
*******************************************************************************
*******************************************************************************
******************************************************************************/
#ifndef _ALREADY_INCLUDED_FERRIS_UASYNCIO_H_
#define _ALREADY_INCLUDED_FERRIS_UASYNCIO_H_
#include <Ferris/HiddenSymbolSupport.hh>
#include <Ferris/Ferris.hh>
#include <Ferris/Runner.hh>
#include <Ferris/AsyncIO.hh>
namespace Ferris
{
template <class StreamClass = fh_stringstream >
class FERRISEXP_API GTK_StreamCollector
:
public StreamCollector< StreamClass >
{
typedef GTK_StreamCollector< StreamClass > _Self;
typedef StreamCollector< StreamClass > _Base;
GtkProgressBar* w_progress;
public:
GTK_StreamCollector( GtkProgressBar* w, StreamClass oss = StreamClass() )
:
_Base( oss ),
w_progress( w )
{}
virtual fh_istream io_cb( fh_istream iss )
{
iss = _Base::io_cb( iss );
if( this->m_totalsz > 0 )
{
double d = this->m_donesz;
d /= this->m_totalsz;
gtk_progress_set_percentage( GTK_PROGRESS(w_progress), d );
}
if( this->w_progress )
{
fh_stringstream ss;
ss << this->m_donesz << " / " << this->m_totalsz;
gtk_progress_bar_set_text( GTK_PROGRESS_BAR(w_progress), tostr(ss).c_str() );
}
return iss;
}
};
typedef GTK_StreamCollector< fh_stringstream > GTK_StringStreamCollector;
FERRIS_SMARTPTR( GTK_StringStreamCollector, fh_gtk_sstreamcol );
typedef GTK_StreamCollector< fh_fstream > GTK_FileStreamCollector;
FERRIS_SMARTPTR( GTK_FileStreamCollector, fh_gtk_fstreamcol );
namespace Factory
{
FERRISEXP_API fh_sstreamcol MakeGTKStringStreamCol( GtkProgressBar* w );
FERRISEXP_API fh_fstreamcol MakeGTKFileStreamCol(
GtkProgressBar* w,
const std::string& s,
std::ios_base::openmode m = std::ios_base::out );
};
};
#endif
| monkeyiq/ferris | FerrisUI/UAsyncIO.hh | C++ | gpl-3.0 | 3,389 |
/*!
* tablesorter pager plugin
* updated 5/27/2013
*/
/*jshint browser:true, jquery:true, unused:false */
;(function($) {
"use strict";
/*jshint supernew:true */
$.extend({ tablesorterPager: new function() {
this.defaults = {
// target the pager markup
container: null,
// use this format: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}"
// where {page} is replaced by the page number, {size} is replaced by the number of records to show,
// {sortList:col} adds the sortList to the url into a "col" array, and {filterList:fcol} adds
// the filterList to the url into an "fcol" array.
// So a sortList = [[2,0],[3,0]] becomes "&col[2]=0&col[3]=0" in the url
// and a filterList = [[2,Blue],[3,13]] becomes "&fcol[2]=Blue&fcol[3]=13" in the url
ajaxUrl: null,
// modify the url after all processing has been applied
customAjaxUrl: function(table, url) { return url; },
// modify the $.ajax object to allow complete control over your ajax requests
ajaxObject: {
dataType: 'json'
},
// process ajax so that the following information is returned:
// [ total_rows (number), rows (array of arrays), headers (array; optional) ]
// example:
// [
// 100, // total rows
// [
// [ "row1cell1", "row1cell2", ... "row1cellN" ],
// [ "row2cell1", "row2cell2", ... "row2cellN" ],
// ...
// [ "rowNcell1", "rowNcell2", ... "rowNcellN" ]
// ],
// [ "header1", "header2", ... "headerN" ] // optional
// ]
ajaxProcessing: function(ajax){ return [ 0, [], null ]; },
// output default: '{page}/{totalPages}'
// possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}'
// apply disabled classname to the pager arrows when the rows at either extreme is visible
updateArrows: true,
// starting page of the pager (zero based index)
page: 0,
// Number of visible rows
size: 10,
// if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty
// table row set to a height to compensate; default is false
fixedHeight: false,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
removeRows: false, // removing rows in larger tables speeds up the sort
// css class names of pager arrows
cssFirst: '.first', // go to first page arrow
cssPrev: '.prev', // previous page arrow
cssNext: '.next', // next page arrow
cssLast: '.last', // go to last page arrow
cssGoto: '.gotoPage', // go to page selector - select dropdown that sets the current page
cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
cssErrorRow: 'tablesorter-errorRow', // error information row
// class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled: 'disabled', // Note there is no period "." in front of this class name
// stuff not set by the user
totalRows: 0,
totalPages: 0,
filteredRows: 0,
filteredPages: 0
};
var $this = this,
// hide arrows at extremes
pagerArrows = function(c, disable) {
var a = 'addClass',
r = 'removeClass',
d = c.cssDisabled,
dis = !!disable,
tp = Math.min( c.totalPages, c.filteredPages );
if ( c.updateArrows ) {
c.$container.find(c.cssFirst + ',' + c.cssPrev)[ ( dis || c.page === 0 ) ? a : r ](d);
c.$container.find(c.cssNext + ',' + c.cssLast)[ ( dis || c.page === tp - 1 ) ? a : r ](d);
}
},
updatePageDisplay = function(table, c, flag) {
var i, p, s, t, out,
tc = table.config,
f = $(table).hasClass('hasFilters') && !c.ajaxUrl;
c.totalPages = Math.ceil( c.totalRows / c.size ); // needed for "pageSize" method
c.filteredRows = (f) ? tc.$tbodies.eq(0).children('tr:not(.' + (tc.widgetOptions && tc.widgetOptions.filter_filteredRow || 'filtered') + ',' + tc.selectorRemove + ')').length : c.totalRows;
c.filteredPages = (f) ? Math.ceil( c.filteredRows / c.size ) || 1 : c.totalPages;
if ( Math.min( c.totalPages, c.filteredPages ) >= 0 ) {
t = (c.size * c.page > c.filteredRows);
c.startRow = (t) ? 1 : (c.filteredRows === 0 ? 0 : c.size * c.page + 1);
c.page = (t) ? 0 : c.page;
c.endRow = Math.min( c.filteredRows, c.totalRows, c.size * ( c.page + 1 ) );
out = c.$container.find(c.cssPageDisplay);
// form the output string
s = c.output.replace(/\{(page|filteredRows|filteredPages|totalPages|startRow|endRow|totalRows)\}/gi, function(m){
return {
'{page}' : c.page + 1,
'{filteredRows}' : c.filteredRows,
'{filteredPages}' : c.filteredPages,
'{totalPages}' : c.totalPages,
'{startRow}' : c.startRow,
'{endRow}' : c.endRow,
'{totalRows}' : c.totalRows
}[m];
});
if (out.length) {
out[ (out[0].tagName === 'INPUT') ? 'val' : 'html' ](s);
if ( c.$goto.length ) {
t = '';
p = Math.min( c.totalPages, c.filteredPages );
for ( i = 1; i <= p; i++ ) {
t += '<option>' + i + '</option>';
}
c.$goto.html(t).val( c.page + 1 );
}
}
}
pagerArrows(c);
if (c.initialized && flag !== false) { $(table).trigger('pagerComplete', c); }
},
fixHeight = function(table, c) {
var d, h, $b = table.config.$tbodies.eq(0);
if (c.fixedHeight) {
$b.find('tr.pagerSavedHeightSpacer').remove();
h = $.data(table, 'pagerSavedHeight');
if (h) {
d = h - $b.height();
if ( d > 5 && $.data(table, 'pagerLastSize') === c.size && $b.children('tr:visible').length < c.size ) {
$b.append('<tr class="pagerSavedHeightSpacer ' + table.config.selectorRemove.replace(/(tr)?\./g,'') + '" style="height:' + d + 'px;"></tr>');
}
}
}
},
changeHeight = function(table, c) {
var $b = table.config.$tbodies.eq(0);
$b.find('tr.pagerSavedHeightSpacer').remove();
$.data(table, 'pagerSavedHeight', $b.height());
fixHeight(table, c);
$.data(table, 'pagerLastSize', c.size);
},
hideRows = function(table, c){
if (!c.ajaxUrl) {
var i,
tc = table.config,
rows = tc.$tbodies.eq(0).children('tr:not(.' + tc.cssChildRow + ')'),
l = rows.length,
s = ( c.page * c.size ),
e = s + c.size,
f = tc.widgetOptions && tc.widgetOptions.filter_filteredRow || 'filtered',
j = 0; // size counter
for ( i = 0; i < l; i++ ){
if ( !rows[i].className.match(f) ) {
rows[i].style.display = ( j >= s && j < e ) ? '' : 'none';
j++;
}
}
}
},
hideRowsSetup = function(table, c){
c.size = parseInt( c.$size.val(), 10 ) || c.size;
$.data(table, 'pagerLastSize', c.size);
pagerArrows(c);
if ( !c.removeRows ) {
hideRows(table, c);
$(table).bind('sortEnd.pager filterEnd.pager', function(){
hideRows(table, c);
});
}
},
renderAjax = function(data, table, c, xhr, exception){
// process data
if ( typeof(c.ajaxProcessing) === "function" ) {
// ajaxProcessing result: [ total, rows, headers ]
var i, j, hsh, $f, $sh, th, d, l, $err, rr_count,
$t = $(table),
tc = table.config,
result = c.ajaxProcessing(data, table) || [ 0, [] ],
hl = $t.find('thead th').length, tds = '',
// allow [ total, rows, headers ] or [ rows, total, headers ]
t = isNaN(result[0]) && !isNaN(result[1]);
$t.find('thead tr.' + c.cssErrorRow).remove(); // Clean up any previous error.
if ( exception ) {
$err = $('<tr class="' + c.cssErrorRow + '"><td style="text-align:center;" colspan="' + hl + '">' + (
xhr.status === 0 ? 'Not connected, verify Network' :
xhr.status === 404 ? 'Requested page not found [404]' :
xhr.status === 500 ? 'Internal Server Error [500]' :
exception === 'parsererror' ? 'Requested JSON parse failed' :
exception === 'timeout' ? 'Time out error' :
exception === 'abort' ? 'Ajax Request aborted' :
'Uncaught error: ' + xhr.statusText + ' [' + xhr.status + ']' ) + '</td></tr>')
.click(function(){
$(this).remove();
})
// add error row to thead instead of tbody, or clicking on the header will result in a parser error
.appendTo( $t.find('thead:first') );
tc.$tbodies.eq(0).empty();
} else {
//ensure a zero returned row count doesn't fail the logical ||
rr_count = result[t ? 1 : 0];
c.totalRows = isNaN(rr_count) ? c.totalRows || 0 : rr_count;
d = result[t ? 0 : 1] || []; // row data
l = d.length;
th = result[2]; // headers
if (d instanceof jQuery) {
// append jQuery object
tc.$tbodies.eq(0).empty().append(d);
} else if (d.length) {
// build table from array
if ( l > 0 ) {
for ( i = 0; i < l; i++ ) {
tds += '<tr>';
for ( j = 0; j < d[i].length; j++ ) {
// build tbody cells
tds += '<td>' + d[i][j] + '</td>';
}
tds += '</tr>';
}
}
// add rows to first tbody
tc.$tbodies.eq(0).html( tds );
}
// only add new header text if the length matches
if ( th && th.length === hl ) {
hsh = $t.hasClass('hasStickyHeaders');
$sh = hsh ? tc.$sticky.children('thead:first').children().children() : '';
$f = $t.find('tfoot tr:first').children();
$t.find('th.' + tc.cssHeader).each(function(j){
var $t = $(this), icn;
// add new test within the first span it finds, or just in the header
if ( $t.find('.' + tc.cssIcon).length ) {
icn = $t.find('.' + tc.cssIcon).clone(true);
$t.find('.tablesorter-header-inner').html( th[j] ).append(icn);
if ( hsh && $sh.length ) {
icn = $sh.eq(j).find('.' + tc.cssIcon).clone(true);
$sh.eq(j).find('.tablesorter-header-inner').html( th[j] ).append(icn);
}
} else {
$t.find('.tablesorter-header-inner').html( th[j] );
if (hsh && $sh.length) {
$sh.eq(j).find('.tablesorter-header-inner').html( th[j] );
}
}
$f.eq(j).html( th[j] );
});
}
}
if (tc.showProcessing) {
$.tablesorter.isProcessing(table); // remove loading icon
}
$t.trigger('update');
c.totalPages = Math.ceil( c.totalRows / c.size );
updatePageDisplay(table, c);
fixHeight(table, c);
if (c.initialized) { $t.trigger('pagerChange', c); }
}
if (!c.initialized) {
c.initialized = true;
$(table).trigger('pagerInitialized', c);
}
},
getAjax = function(table, c){
var url = getAjaxUrl(table, c),
$doc = $(document),
tc = table.config;
if ( url !== '' ) {
if (tc.showProcessing) {
$.tablesorter.isProcessing(table, true); // show loading icon
}
$doc.bind('ajaxError.pager', function(e, xhr, settings, exception) {
//show the error message on the table
if (url === settings.url) {
renderAjax(null, table, c, xhr, exception);
$doc.unbind('ajaxError.pager');
}
});
c.ajaxObject.url = url; // from the ajaxUrl option and modified by customAjaxUrl
c.ajaxObject.success = function(data) {
renderAjax(data, table, c);
$doc.unbind('ajaxError.pager');
if (typeof c.oldAjaxSuccess === 'function') {
c.oldAjaxSuccess(data);
}
};
$.ajax(c.ajaxObject);
}
},
getAjaxUrl = function(table, c) {
var url = (c.ajaxUrl) ? c.ajaxUrl
// allow using "{page+1}" in the url string to switch to a non-zero based index
.replace(/\{page([\-+]\d+)?\}/, function(s,n){ return c.page + (n ? parseInt(n, 10) : 0); })
.replace(/\{size\}/g, c.size) : '',
sl = table.config.sortList,
fl = c.currentFilters || [],
sortCol = url.match(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/),
filterCol = url.match(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/),
arry = [];
if (sortCol) {
sortCol = sortCol[1];
$.each(sl, function(i,v){
arry.push(sortCol + '[' + v[0] + ']=' + v[1]);
});
// if the arry is empty, just add the col parameter... "&{sortList:col}" becomes "&col"
url = url.replace(/\{\s*sort(?:List)?\s*:\s*(\w*)\s*\}/g, arry.length ? arry.join('&') : sortCol );
arry = [];
}
if (filterCol) {
filterCol = filterCol[1];
$.each(fl, function(i,v){
if (v) {
arry.push(filterCol + '[' + i + ']=' + encodeURIComponent(v));
}
});
// if the arry is empty, just add the fcol parameter... "&{filterList:fcol}" becomes "&fcol"
url = url.replace(/\{\s*filter(?:List)?\s*:\s*(\w*)\s*\}/g, arry.length ? arry.join('&') : filterCol );
}
if ( typeof(c.customAjaxUrl) === "function" ) {
url = c.customAjaxUrl(table, url);
}
return url;
},
renderTable = function(table, rows, c) {
c.isDisabled = false; // needed because sorting will change the page and re-enable the pager
var i, j, o, $tb,
l = rows.length,
s = ( c.page * c.size ),
e = ( s + c.size );
if ( l < 1 ) { return; } // empty table, abort!
if (c.initialized) { $(table).trigger('pagerChange', c); }
if ( !c.removeRows ) {
hideRows(table, c);
} else {
if ( e > rows.length ) {
e = rows.length;
}
$.tablesorter.clearTableBody(table);
$tb = $.tablesorter.processTbody(table, table.config.$tbodies.eq(0), true);
for ( i = s; i < e; i++ ) {
o = rows[i];
l = o.length;
for ( j = 0; j < l; j++ ) {
$tb.appendChild(o[j]);
}
}
$.tablesorter.processTbody(table, $tb, false);
}
if ( c.page >= c.totalPages ) {
moveToLastPage(table, c);
}
updatePageDisplay(table, c);
if ( !c.isDisabled ) { fixHeight(table, c); }
$(table).trigger('applyWidgets');
},
showAllRows = function(table, c){
if ( c.ajax ) {
pagerArrows(c, true);
} else {
c.isDisabled = true;
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.page = 0;
c.size = c.totalRows;
c.totalPages = 1;
$(table).find('tr.pagerSavedHeightSpacer').remove();
renderTable(table, table.config.rowsCopy, c);
}
// disable size selector
c.$size.add(c.$goto).each(function(){
$(this).addClass(c.cssDisabled)[0].disabled = true;
});
},
moveToPage = function(table, c, flag) {
if ( c.isDisabled ) { return; }
var p = Math.min( c.totalPages, c.filteredPages );
if ( c.page < 0 ) { c.page = 0; }
if ( c.page > ( p - 1 ) && p !== 0 ) { c.page = p - 1; }
if (c.ajax) {
getAjax(table, c);
} else if (!c.ajax) {
renderTable(table, table.config.rowsCopy, c);
}
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerUpdateTriggered', true);
if (c.initialized && flag !== false) {
$(table).trigger('pageMoved', c);
}
},
setPageSize = function(table, size, c) {
c.size = size;
c.$size.val(size);
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.totalPages = Math.ceil( c.totalRows / c.size );
moveToPage(table, c);
},
moveToFirstPage = function(table, c) {
c.page = 0;
moveToPage(table, c);
},
moveToLastPage = function(table, c) {
c.page = ( Math.min( c.totalPages, c.filteredPages ) - 1 );
moveToPage(table, c);
},
moveToNextPage = function(table, c) {
c.page++;
if ( c.page >= ( Math.min( c.totalPages, c.filteredPages ) - 1 ) ) {
c.page = ( Math.min( c.totalPages, c.filteredPages ) - 1 );
}
moveToPage(table, c);
},
moveToPrevPage = function(table, c) {
c.page--;
if ( c.page <= 0 ) {
c.page = 0;
}
moveToPage(table, c);
},
destroyPager = function(table, c){
showAllRows(table, c);
c.$container.hide(); // hide pager
table.config.appender = null; // remove pager appender function
$(table).unbind('destroy.pager sortEnd.pager filterEnd.pager enable.pager disable.pager');
},
enablePager = function(table, c, triggered){
var p = c.$size.removeClass(c.cssDisabled).removeAttr('disabled');
c.$goto.removeClass(c.cssDisabled).removeAttr('disabled');
c.isDisabled = false;
c.page = $.data(table, 'pagerLastPage') || c.page || 0;
c.size = $.data(table, 'pagerLastSize') || parseInt(p.find('option[selected]').val(), 10) || c.size;
p.val(c.size); // set page size
c.totalPages = Math.ceil( Math.min( c.totalPages, c.filteredPages ) / c.size);
if ( triggered ) {
$(table).trigger('update');
setPageSize(table, c.size, c);
hideRowsSetup(table, c);
fixHeight(table, c);
}
};
$this.appender = function(table, rows) {
var c = table.config.pager;
if ( !c.ajax ) {
table.config.rowsCopy = rows;
c.totalRows = rows.length;
c.size = $.data(table, 'pagerLastSize') || c.size;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table, rows, c);
}
};
$this.construct = function(settings) {
return this.each(function() {
// check if tablesorter has initialized
if (!(this.config && this.hasInitialized)) { return; }
var t, ctrls, fxn,
config = this.config,
c = config.pager = $.extend( {}, $.tablesorterPager.defaults, settings ),
table = this,
tc = table.config,
$t = $(table),
// added in case the pager is reinitialized after being destroyed.
pager = c.$container = $(c.container).addClass('tablesorter-pager').show();
c.oldAjaxSuccess = c.oldAjaxSuccess || c.ajaxObject.success;
config.appender = $this.appender;
$t
.unbind('filterStart.pager filterEnd.pager sortEnd.pager disable.pager enable.pager destroy.pager update.pager pageSize.pager')
.bind('filterStart.pager', function(e, filters) {
$.data(table, 'pagerUpdateTriggered', false);
c.currentFilters = filters;
})
// update pager after filter widget completes
.bind('filterEnd.pager sortEnd.pager', function(e) {
//Prevent infinite event loops from occuring by setting this in all moveToPage calls and catching it here.
if ($.data(table, 'pagerUpdateTriggered')) {
$.data(table, 'pagerUpdateTriggered', false);
return;
}
//only run the server side sorting if it has been enabled
if (e.type === "filterEnd" || (e.type === "sortEnd" && tc.serverSideSorting)) {
moveToPage(table, c, false);
}
updatePageDisplay(table, c, false);
fixHeight(table, c);
})
.bind('disable.pager', function(e){
e.stopPropagation();
showAllRows(table, c);
})
.bind('enable.pager', function(e){
e.stopPropagation();
enablePager(table, c, true);
})
.bind('destroy.pager', function(e){
e.stopPropagation();
destroyPager(table, c);
})
.bind('update.pager', function(e){
e.stopPropagation();
hideRows(table, c);
})
.bind('pageSize.pager', function(e,v){
e.stopPropagation();
setPageSize(table, parseInt(v, 10) || 10, c);
hideRows(table, c);
updatePageDisplay(table, c, false);
if (c.$size.length) { c.$size.val(c.size); } // twice?
})
.bind('pageSet.pager', function(e,v){
e.stopPropagation();
c.page = (parseInt(v, 10) || 1) - 1;
if (c.$goto.length) { c.$goto.val(c.size); } // twice?
moveToPage(table, c);
updatePageDisplay(table, c, false);
});
// clicked controls
ctrls = [ c.cssFirst, c.cssPrev, c.cssNext, c.cssLast ];
fxn = [ moveToFirstPage, moveToPrevPage, moveToNextPage, moveToLastPage ];
pager.find(ctrls.join(','))
.unbind('click.pager')
.bind('click.pager', function(e){
var i, $t = $(this), l = ctrls.length;
if ( !$t.hasClass(c.cssDisabled) ) {
for (i = 0; i < l; i++) {
if ($t.is(ctrls[i])) {
fxn[i](table, c);
break;
}
}
}
return false;
});
// goto selector
c.$goto = pager.find(c.cssGoto);
if ( c.$goto.length ) {
c.$goto
.unbind('change')
.bind('change', function(){
c.page = $(this).val() - 1;
moveToPage(table, c);
});
updatePageDisplay(table, c, false);
}
// page size selector
c.$size = pager.find(c.cssPageSize);
if ( c.$size.length ) {
c.$size.unbind('change.pager').bind('change.pager', function() {
c.$size.val( $(this).val() ); // in case there are more than one pagers
if ( !$(this).hasClass(c.cssDisabled) ) {
setPageSize(table, parseInt( $(this).val(), 10 ), c);
changeHeight(table, c);
}
return false;
});
}
// clear initialized flag
c.initialized = false;
// before initialization event
$t.trigger('pagerBeforeInitialized', c);
enablePager(table, c, false);
if ( typeof(c.ajaxUrl) === 'string' ) {
// ajax pager; interact with database
c.ajax = true;
//When filtering with ajax, allow only custom filtering function, disable default filtering since it will be done server side.
tc.widgetOptions.filter_serversideFiltering = true;
tc.serverSideSorting = true;
moveToPage(table, c);
} else {
c.ajax = false;
// Regular pager; all rows stored in memory
$(this).trigger("appendCache", true);
hideRowsSetup(table, c);
}
changeHeight(table, c);
// pager initialized
if (!c.ajax) {
c.initialized = true;
$(table).trigger('pagerInitialized', c);
}
});
};
}()
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery);
| churchill-lab/qtl-viewer | qtlviewer/static/jquery.tablesorter/addons/pager/jquery.tablesorter.pager.js | JavaScript | gpl-3.0 | 21,755 |
/**
* The <b>MarketAnalysis</b> is a gui application using a database for data storage.
*
* The main purpose of this application is to provide indication on rewarding investments.
* Additionally once the investment strategy is selected allows the monitoring of the performance.
*
*/
package marketanalysis;
| r-k-/MarketAnalysis | src/marketanalysis/package-info.java | Java | gpl-3.0 | 316 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
bl_info = {
"name": "Rigacar (Generates Car Rig)",
"author": "David Gayerie",
"version": (7, 0),
"blender": (2, 83, 0),
"location": "View3D > Add > Armature",
"description": "Adds a deformation rig for vehicules, generates animation rig and bake wheels animation.",
"wiki_url": "http://digicreatures.net/articles/rigacar.html",
"tracker_url": "https://github.com/digicreatures/rigacar/issues",
"category": "Rigging"}
if "bpy" in locals():
import importlib
if "bake_operators" in locals():
importlib.reload(bake_operators)
if "car_rig" in locals():
importlib.reload(car_rig)
if "widgets" in locals():
importlib.reload(widgets)
else:
import bpy
from . import bake_operators
from . import car_rig
def enumerate_ground_sensors(bones):
bone = bones.get('GroundSensor.Axle.Ft')
if bone is not None:
yield bone
for bone in bones:
if bone.name.startswith('GroundSensor.Ft'):
yield bone
bone = bones.get('GroundSensor.Axle.Bk')
if bone is not None:
yield bone
for bone in bones:
if bone.name.startswith('GroundSensor.Bk'):
yield bone
class RIGACAR_PT_mixin:
def __init__(self):
self.layout.use_property_split = True
self.layout.use_property_decorate = False
@classmethod
def is_car_rig(cls, context):
return context.object is not None and context.object.data is not None and 'Car Rig' in context.object.data
@classmethod
def is_car_rig_generated(cls, context):
return cls.is_car_rig(context) and context.object.data['Car Rig']
def display_generate_section(self, context):
self.layout.operator(car_rig.POSE_OT_carAnimationRigGenerate.bl_idname, text='Generate')
def display_bake_section(self, context):
self.layout.operator(bake_operators.ANIM_OT_carSteeringBake.bl_idname)
self.layout.operator(bake_operators.ANIM_OT_carWheelsRotationBake.bl_idname)
self.layout.operator(bake_operators.ANIM_OT_carClearSteeringWheelsRotation.bl_idname)
def display_rig_props_section(self, context):
layout = self.layout.column()
layout.prop(context.object, '["wheels_on_y_axis"]', text="Wheels on Y axis")
layout.prop(context.object, '["suspension_factor"]', text="Pitch factor")
layout.prop(context.object, '["suspension_rolling_factor"]', text="Roll factor")
def display_ground_sensors_section(self, context):
for ground_sensor in enumerate_ground_sensors(context.object.pose.bones):
ground_projection_constraint = ground_sensor.constraints.get('Ground projection')
self.layout.label(text=ground_sensor.name, icon='BONE_DATA')
if ground_projection_constraint is not None:
self.layout.prop(ground_projection_constraint, 'target', text='Ground')
if ground_projection_constraint.target is not None:
self.layout.prop(ground_projection_constraint, 'shrinkwrap_type')
if ground_projection_constraint.shrinkwrap_type == 'PROJECT':
self.layout.prop(ground_projection_constraint, 'project_limit')
self.layout.prop(ground_projection_constraint, 'influence')
ground_projection_limit_constraint = ground_sensor.constraints.get('Ground projection limitation')
if ground_projection_limit_constraint is not None:
self.layout.prop(ground_projection_limit_constraint, 'min_z', text='Min local Z')
self.layout.prop(ground_projection_limit_constraint, 'max_z', text='Max local Z')
self.layout.separator()
class RIGACAR_PT_rigProperties(bpy.types.Panel, RIGACAR_PT_mixin):
bl_label = "Rigacar"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig(context)
def draw(self, context):
if RIGACAR_PT_mixin.is_car_rig_generated(context):
self.display_rig_props_section(context)
self.layout.separator()
self.display_bake_section(context)
else:
self.display_generate_section(context)
class RIGACAR_PT_groundSensorsProperties(bpy.types.Panel, RIGACAR_PT_mixin):
bl_label = "Ground Sensors"
bl_parent_id = "RIGACAR_PT_rigProperties"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_ground_sensors_section(context)
class RIGACAR_PT_animationRigView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Animation Rig"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig(context)
def draw(self, context):
if RIGACAR_PT_mixin.is_car_rig_generated(context):
self.display_rig_props_section(context)
else:
self.display_generate_section(context)
class RIGACAR_PT_wheelsAnimationView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Wheels animation"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_bake_section(context)
class RIGACAR_PT_groundSensorsView(bpy.types.Panel, RIGACAR_PT_mixin):
bl_category = "Rigacar"
bl_label = "Ground Sensors"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return RIGACAR_PT_mixin.is_car_rig_generated(context)
def draw(self, context):
self.display_ground_sensors_section(context)
def menu_entries(menu, context):
menu.layout.operator(car_rig.OBJECT_OT_armatureCarDeformationRig.bl_idname, text="Car (deformation rig)", icon='AUTO')
classes = (
RIGACAR_PT_rigProperties,
RIGACAR_PT_groundSensorsProperties,
RIGACAR_PT_animationRigView,
RIGACAR_PT_wheelsAnimationView,
RIGACAR_PT_groundSensorsView,
)
def register():
bpy.types.VIEW3D_MT_armature_add.append(menu_entries)
for c in classes:
bpy.utils.register_class(c)
car_rig.register()
bake_operators.register()
def unregister():
bake_operators.unregister()
car_rig.unregister()
for c in classes:
bpy.utils.unregister_class(c)
bpy.types.VIEW3D_MT_armature_add.remove(menu_entries)
if __name__ == "__main__":
register()
| digicreatures/rigacar | __init__.py | Python | gpl-3.0 | 7,661 |
/*
* Copyright (C) 2017 Team Gateship-One
* (Hendrik Borghorst & Frederik Luetkes)
*
* The AUTHORS.md file contains a detailed contributors list:
* <https://github.com/gateship-one/malp/blob/master/AUTHORS.md>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.gateshipone.malp.application.background;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.VolumeProviderCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.NotificationCompat;
import org.gateshipone.malp.R;
import org.gateshipone.malp.application.activities.MainActivity;
import org.gateshipone.malp.application.artworkdatabase.ArtworkManager;
import org.gateshipone.malp.application.utils.CoverBitmapLoader;
import org.gateshipone.malp.application.utils.FormatHelper;
import org.gateshipone.malp.mpdservice.handlers.serverhandler.MPDCommandHandler;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDAlbum;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDCurrentStatus;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDTrack;
public class NotificationManager implements CoverBitmapLoader.CoverBitmapListener, ArtworkManager.onNewAlbumImageListener {
private static final String TAG = NotificationManager.class.getSimpleName();
private static final int NOTIFICATION_ID = 0;
private BackgroundService mService;
/**
* Intent IDs used for controlling action.
*/
private final static int INTENT_OPENGUI = 0;
private final static int INTENT_PREVIOUS = 1;
private final static int INTENT_PLAYPAUSE = 2;
private final static int INTENT_STOP = 3;
private final static int INTENT_NEXT = 4;
private final static int INTENT_QUIT = 5;
// Notification objects
private final android.app.NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder = null;
// Notification itself
private Notification mNotification;
// Save last track and last image
private Bitmap mLastBitmap = null;
/**
* Last state of the MPD server
*/
private MPDCurrentStatus mLastStatus = null;
/**
* Last played track of the MPD server. Used to check if track changed and a new cover is necessary.
*/
private MPDTrack mLastTrack = null;
/**
* State of the notification and the media session.
*/
private boolean mSessionActive;
/**
* Loader to asynchronously load cover images.
*/
private CoverBitmapLoader mCoverLoader;
/**
* Mediasession to set the lockscreen picture as well
*/
private MediaSessionCompat mMediaSession;
/**
* {@link VolumeProviderCompat} to react to volume changes over the hardware keys by the user.
* Only active as long as the notification is active.
*/
private MALPVolumeControlProvider mVolumeControlProvider;
public NotificationManager(BackgroundService service) {
mService = service;
mNotificationManager = (android.app.NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
mLastStatus = new MPDCurrentStatus();
mLastTrack = new MPDTrack("");
/**
* Create loader to asynchronously load cover images. This class is the callback (s. receiveBitmap)
*/
mCoverLoader = new CoverBitmapLoader(mService, this);
ArtworkManager.getInstance(service).registerOnNewAlbumImageListener(this);
}
/**
* Shows the notification
*/
public void showNotification() {
if (mMediaSession == null) {
mMediaSession = new MediaSessionCompat(mService, mService.getString(R.string.app_name));
mMediaSession.setCallback(new MALPMediaSessionCallback());
mVolumeControlProvider = new MALPVolumeControlProvider();
mMediaSession.setPlaybackToRemote(mVolumeControlProvider);
mMediaSession.setActive(true);
}
mService.startForeground(NOTIFICATION_ID, mNotification);
updateNotification(mLastTrack, mLastStatus.getPlaybackState());
mSessionActive = true;
}
/**
* Hides the notification (if shown) and resets state variables.
*/
public void hideNotification() {
if (mMediaSession != null) {
mMediaSession.setActive(false);
mMediaSession.release();
mMediaSession = null;
}
mNotificationManager.cancel(NOTIFICATION_ID);
if (mNotification != null) {
mService.stopForeground(true);
mNotification = null;
mNotificationBuilder = null;
}
mSessionActive = false;
}
/*
* Creates a android system notification with two different remoteViews. One
* for the normal layout and one for the big one. Sets the different
* attributes of the remoteViews and starts a thread for Cover generation.
*/
public synchronized void updateNotification(MPDTrack track, MPDCurrentStatus.MPD_PLAYBACK_STATE state) {
if (track != null) {
mNotificationBuilder = new NotificationCompat.Builder(mService);
// Open application intent
Intent contentIntent = new Intent(mService, MainActivity.class);
contentIntent.putExtra(MainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW, MainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW_NOWPLAYINGVIEW);
contentIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent contentPendingIntent = PendingIntent.getActivity(mService, INTENT_OPENGUI, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder.setContentIntent(contentPendingIntent);
// Set pendingintents
// Previous song action
Intent prevIntent = new Intent(BackgroundService.ACTION_PREVIOUS);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mService, INTENT_PREVIOUS, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();
// Pause/Play action
PendingIntent playPauseIntent;
int playPauseIcon;
if (state == MPDCurrentStatus.MPD_PLAYBACK_STATE.MPD_PLAYING) {
Intent pauseIntent = new Intent(BackgroundService.ACTION_PAUSE);
playPauseIntent = PendingIntent.getBroadcast(mService, INTENT_PLAYPAUSE, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
playPauseIcon = R.drawable.ic_pause_48dp;
} else {
Intent playIntent = new Intent(BackgroundService.ACTION_PLAY);
playPauseIntent = PendingIntent.getBroadcast(mService, INTENT_PLAYPAUSE, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
playPauseIcon = R.drawable.ic_play_arrow_48dp;
}
NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon, "PlayPause", playPauseIntent).build();
// Stop action
Intent stopIntent = new Intent(BackgroundService.ACTION_STOP);
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(mService, INTENT_STOP, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action stopActon = new NotificationCompat.Action.Builder(R.drawable.ic_stop_black_48dp, "Stop", stopPendingIntent).build();
// Next song action
Intent nextIntent = new Intent(BackgroundService.ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mService, INTENT_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();
// Quit action
Intent quitIntent = new Intent(BackgroundService.ACTION_QUIT_BACKGROUND_SERVICE);
PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mService, INTENT_QUIT, quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder.setDeleteIntent(quitPendingIntent);
mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
mNotificationBuilder.setSmallIcon(R.drawable.ic_notification_24dp);
mNotificationBuilder.addAction(prevAction);
mNotificationBuilder.addAction(playPauseAction);
mNotificationBuilder.addAction(stopActon);
mNotificationBuilder.addAction(nextAction);
NotificationCompat.MediaStyle notificationStyle = new NotificationCompat.MediaStyle();
notificationStyle.setShowActionsInCompactView(1, 2);
mNotificationBuilder.setStyle(notificationStyle);
String title;
if (track.getTrackTitle().isEmpty()) {
title = FormatHelper.getFilenameFromPath(track.getPath());
} else {
title = track.getTrackTitle();
}
mNotificationBuilder.setContentTitle(title);
String secondRow;
if (!track.getTrackArtist().isEmpty() && !track.getTrackAlbum().isEmpty()) {
secondRow = track.getTrackArtist() + mService.getString(R.string.track_item_separator) + track.getTrackAlbum();
} else if (track.getTrackArtist().isEmpty() && !track.getTrackAlbum().isEmpty()) {
secondRow = track.getTrackAlbum();
} else if (track.getTrackAlbum().isEmpty() && !track.getTrackArtist().isEmpty()) {
secondRow = track.getTrackArtist();
} else {
secondRow = track.getPath();
}
// Set the media session metadata
updateMetadata(track, state);
mNotificationBuilder.setContentText(secondRow);
// Remove unnecessary time info
mNotificationBuilder.setWhen(0);
// Cover but only if changed
if (mNotification == null || !track.getTrackAlbum().equals(mLastTrack.getTrackAlbum())) {
mLastTrack = track;
mLastBitmap = null;
mCoverLoader.getImage(mLastTrack, true);
}
// Only set image if an saved one is available
if (mLastBitmap != null) {
mNotificationBuilder.setLargeIcon(mLastBitmap);
} else {
/**
* Create a dummy placeholder image for versions greater android 7 because it
* does not automatically show the application icon anymore in mediastyle notifications.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Drawable icon = mService.getDrawable(R.drawable.notification_placeholder_256dp);
Bitmap iconBitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(iconBitmap);
DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, 1);
canvas.setDrawFilter(filter);
icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
icon.setFilterBitmap(true);
icon.draw(canvas);
mNotificationBuilder.setLargeIcon(iconBitmap);
} else {
/**
* For older android versions set the null icon which will result in a dummy icon
* generated from the application icon.
*/
mNotificationBuilder.setLargeIcon(null);
}
}
// Build the notification
mNotification = mNotificationBuilder.build();
// Send the notification away
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
}
/**
* Updates the Metadata from Androids MediaSession. This sets track/album and stuff
* for a lockscreen image for example.
*
* @param track Current track.
* @param playbackState State of the PlaybackService.
*/
private void updateMetadata(MPDTrack track, MPDCurrentStatus.MPD_PLAYBACK_STATE playbackState) {
if (track != null) {
if (playbackState == MPDCurrentStatus.MPD_PLAYBACK_STATE.MPD_PLAYING) {
mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f)
.setActions(PlaybackStateCompat.ACTION_SKIP_TO_NEXT + PlaybackStateCompat.ACTION_PAUSE +
PlaybackStateCompat.ACTION_PLAY + PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS +
PlaybackStateCompat.ACTION_STOP + PlaybackStateCompat.ACTION_SEEK_TO).build());
} else {
mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().
setState(PlaybackStateCompat.STATE_PAUSED, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_SKIP_TO_NEXT +
PlaybackStateCompat.ACTION_PAUSE + PlaybackStateCompat.ACTION_PLAY +
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS + PlaybackStateCompat.ACTION_STOP +
PlaybackStateCompat.ACTION_SEEK_TO).build());
}
// Try to get old metadata to save image retrieval.
MediaMetadataCompat oldData = mMediaSession.getController().getMetadata();
MediaMetadataCompat.Builder metaDataBuilder;
if (oldData == null) {
metaDataBuilder = new MediaMetadataCompat.Builder();
} else {
metaDataBuilder = new MediaMetadataCompat.Builder(mMediaSession.getController().getMetadata());
}
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, track.getTrackTitle());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, track.getTrackAlbum());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, track.getTrackArtist());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, track.getTrackArtist());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, track.getTrackTitle());
metaDataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, track.getTrackNumber());
metaDataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, track.getLength());
mMediaSession.setMetadata(metaDataBuilder.build());
}
}
/**
* Notifies about a change in MPDs status. If not shown this may be used later.
*
* @param status New MPD status
*/
public void setMPDStatus(MPDCurrentStatus status) {
if (mSessionActive) {
updateNotification(mLastTrack, status.getPlaybackState());
// Notify the mediasession about the new volume
mVolumeControlProvider.setCurrentVolume(status.getVolume());
}
// Save for later usage
mLastStatus = status;
}
/**
* Notifies about a change in MPDs track. If not shown this may be used later.
*
* @param track New MPD track
*/
public void setMPDFile(MPDTrack track) {
if (mSessionActive) {
updateNotification(track, mLastStatus.getPlaybackState());
}
// Save for later usage
mLastTrack = track;
}
/*
* Receives the generated album picture from the main status helper for the
* notification controls. Sets it and notifies the system that the
* notification has changed
*/
@Override
public synchronized void receiveBitmap(Bitmap bm, final CoverBitmapLoader.IMAGE_TYPE type) {
// Check if notification exists and set picture
mLastBitmap = bm;
if (type == CoverBitmapLoader.IMAGE_TYPE.ALBUM_IMAGE && mNotification != null && bm != null) {
mNotificationBuilder.setLargeIcon(bm);
mNotification = mNotificationBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
/* Set lockscreen picture and stuff */
if (mMediaSession != null) {
MediaMetadataCompat.Builder metaDataBuilder;
metaDataBuilder = new MediaMetadataCompat.Builder(mMediaSession.getController().getMetadata());
metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bm);
mMediaSession.setMetadata(metaDataBuilder.build());
}
}
}
@Override
public void newAlbumImage(MPDAlbum album) {
if (mLastTrack.getTrackAlbum().equals(album.getName())) {
mCoverLoader.getImage(mLastTrack, true);
}
}
/**
* Callback class for MediaControls controlled by android system like BT remotes, etc and
* Volume keys on some android versions.
*/
private class MALPMediaSessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
super.onPlay();
MPDCommandHandler.togglePause();
}
@Override
public void onPause() {
super.onPause();
MPDCommandHandler.togglePause();
}
@Override
public void onSkipToNext() {
super.onSkipToNext();
MPDCommandHandler.nextSong();
}
@Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
MPDCommandHandler.previousSong();
}
@Override
public void onStop() {
super.onStop();
MPDCommandHandler.stop();
}
@Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
MPDCommandHandler.seekSeconds((int) pos);
}
}
/**
* Handles volume changes from mediasession callbacks. Will send user requested changes
* in volume back to the MPD server.
*/
private class MALPVolumeControlProvider extends VolumeProviderCompat {
public MALPVolumeControlProvider() {
super(VOLUME_CONTROL_ABSOLUTE, 100, mLastStatus.getVolume());
}
@Override
public void onSetVolumeTo(int volume) {
MPDCommandHandler.setVolume(volume);
setCurrentVolume(volume);
}
@Override
public void onAdjustVolume(int direction) {
if (direction == 1) {
MPDCommandHandler.increaseVolume();
} else if (direction == -1) {
MPDCommandHandler.decreaseVolume();
}
}
}
}
| Sohalt/malp | app/src/main/java/org/gateshipone/malp/application/background/NotificationManager.java | Java | gpl-3.0 | 20,104 |
package com.idega.builder.presentation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.FinderException;
import com.idega.builder.business.BuilderConstants;
import com.idega.builder.business.ICObjectComparator;
import com.idega.core.accesscontrol.business.StandardRoles;
import com.idega.core.component.data.ICObject;
import com.idega.core.component.data.ICObjectBMPBean;
import com.idega.core.component.data.ICObjectHome;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.Span;
import com.idega.presentation.text.Heading3;
import com.idega.presentation.text.ListItem;
import com.idega.presentation.text.Lists;
import com.idega.presentation.text.Text;
public class AddModuleBlock extends Block {
private Map<String, List<ICObject>> addedTabs = new HashMap<String, List<ICObject>>();
private String localizedText = "Sorry, there are no components available.";
private boolean isBuilderUser(IWContext iwc) {
if (iwc.hasRole(StandardRoles.ROLE_KEY_BUILDER)) {
return true;
}
if (iwc.hasRole(StandardRoles.ROLE_KEY_EDITOR)) {
return true;
}
return iwc.hasRole(StandardRoles.ROLE_KEY_AUTHOR);
}
@Override
public String getBundleIdentifier() {
return BuilderConstants.IW_BUNDLE_IDENTIFIER;
}
@Override
public void main(IWContext iwc) throws Exception {
IWResourceBundle iwrb = getResourceBundle(iwc);
boolean isBuilderUser = isBuilderUser(iwc);
localizedText = iwrb.getLocalizedString("no_components_available", localizedText);
Collection<ICObject> allComoponents = getAllComponents();
Layer container = new Layer();
container.setStyleClass("addModuleContainer");
add(container);
// Header
/*Layer header = new Layer();
String regionName = iwc.getParameter(BuilderConstants.REGION_NAME);
StringBuffer label = new StringBuffer(iwrb.getLocalizedString(BuilderConstants.ADD_MODULE_TO_REGION_LOCALIZATION_KEY,
BuilderConstants.ADD_MODULE_TO_REGION_LOCALIZATION_VALUE));
if (regionName != null && !(CoreConstants.EMPTY.equals(regionName))) {
label.append(CoreConstants.SPACE).append(iwrb.getLocalizedString("to", "to")).append(CoreConstants.SPACE).append(iwrb.getLocalizedString("region", "region"));
label.append(CoreConstants.SPACE).append(regionName);
}
header.add(new Heading1(label.toString()));
header.setStyleClass("addModuleToBuilderPage");
container.add(header);*/
Lists titles = new Lists();
titles.setStyleClass("mootabs_title");
List<ICObject> widgets = getConcreteComponents(iwc, allComoponents, true, false, false);
if (widgets != null && widgets.size() > 0) {
addComponentsTitles(titles, widgets, "widgetsTab", iwrb.getLocalizedString("widget_modules", "Widgets"));
}
List<ICObject> blocks = getConcreteComponents(iwc, allComoponents, false, true, false);
if (blocks != null && blocks.size() > 0) {
addComponentsTitles(titles, blocks, "blocksTab", iwrb.getLocalizedString("blocks_header", "Blocks"));
}
List<ICObject> builderComponents = null;
if (isBuilderUser) {
builderComponents = getConcreteComponents(iwc, allComoponents, false, false, true);
if (builderComponents != null && builderComponents.size() > 0) {
addComponentsTitles(titles, builderComponents, "builderTab", iwrb.getLocalizedString("builder_modules", "Builder"));
}
}
if (addedTabs.size() == 0) {
container.add(new Heading3(localizedText));
return;
}
container.add(titles);
String key = null;
for (Iterator<String> keys = addedTabs.keySet().iterator(); keys.hasNext();) {
key = keys.next();
Layer componentsListContainer = new Layer();
componentsListContainer.setStyleClass("mootabs_panel");
componentsListContainer.setId(key);
addListToWindow(iwc, addedTabs.get(key), componentsListContainer);
container.add(componentsListContainer);
}
Layer script = new Layer();
script.add(new StringBuffer("<script type=\"text/javascript\">createTabsWithMootabs('").append(container.getId()).append("'); closeAllLoadingMessages();</script>").toString());
container.add(script);
}
private void addComponentsTitles(Lists titles, List<ICObject> components, String tabText, String text) {
ListItem tab = new ListItem();
tab.setMarkupAttribute("title", tabText);
tab.addText(text);
titles.add(tab);
addedTabs.put(tabText, components);
}
private void addListToWindow(IWContext iwc, List<ICObject> objects, Layer container) {
if (objects == null || objects.size() == 0) {
container.add(localizedText);
return;
}
Lists items = new Lists();
String itemStyleClass = "modulesListItemStyle";
ListItem item = new ListItem();
String actionDefinition = "onclick";
ICObject object = null;
for (int i = 0; i < objects.size(); i++) {
object = objects.get(i);
String iconURI = object.getIconURI();
//IWBundle iwb = object.getBundle(iwc.getIWMainApplication());
//IWResourceBundle iwrb = iwb.getResourceBundle(iwc);
item = new ListItem();
item.setStyleClass(itemStyleClass);
item.attributes.put(actionDefinition, new StringBuffer("addSelectedModule(").append(object.getID()).append(", '").append(object.getClassName()).append("');").toString());
items.add(item);
if (iconURI != null) {
Image image = new Image(iconURI);
image.setAlt(object.getName());
item.add(image);
}
Span span = new Span();
span.setStyleClass("objectName");
//span.add(new Text(iwrb.getLocalizedString("iw.component." + object.getClassName(), object.getName())));
span.add(new Text(object.getName()));
item.add(span);
span = new Span();
span.setStyleClass("objectDescription");
//span.add(new Text(iwrb.getLocalizedString("iw.component.description." + object.getName(), "Descripition for item " + object.getName())));
span.add(new Text("Descripition for item " + object.getName()));
item.add(span);
}
container.add(items);
}
private List<ICObject> getConcreteComponents(IWContext iwc, Collection<ICObject> allComponents, boolean findWidgets, boolean findBlocks, boolean findBuilder) {
List<ICObject> components = new ArrayList<ICObject>();
List<String> namesList = new ArrayList<String>();
if (allComponents == null) {
return components;
}
ICObject object = null;
// Find "widget" type modules
if (findWidgets) {
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (object.isWidget()) {
addComponent(components, object, namesList);
}
}
return getSortedComponents(components);
}
// Find "block" type modules
if (findBlocks) {
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (object.isBlock()) {
if (!components.contains(object)) {
addComponent(components, object, namesList);
}
}
}
return getSortedComponents(components);
}
// Find all other Builder/Development modules
List<String> componentTypes = Arrays.asList(new String[] {ICObjectBMPBean.COMPONENT_TYPE_ELEMENT, ICObjectBMPBean.COMPONENT_TYPE_BLOCK,
ICObjectBMPBean.COMPONENT_TYPE_JSFUICOMPONENT});
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (!object.isBlock() && !object.isWidget()) {
if (componentTypes.contains(object.getObjectType())) {
addComponent(components, object, namesList);
}
}
}
return getSortedComponents(components);
}
private List<ICObject> getSortedComponents(List<ICObject> components) {
if (components == null) {
return null;
}
ICObjectComparator comparator = new ICObjectComparator();
Collections.sort(components, comparator);
return components;
}
private void addComponent(List<ICObject> components, ICObject component, List<String> namesList) {
if (component == null || components == null || namesList == null) {
return;
}
if (namesList.contains(component.getClassName())) {
return;
}
namesList.add(component.getClassName());
components.add(component);
}
private Collection<ICObject> getAllComponents() {
ICObjectHome icoHome = null;
try {
icoHome = (ICObjectHome) IDOLookup.getHome(ICObject.class);
} catch (IDOLookupException e) {
e.printStackTrace();
}
if (icoHome == null) {
return null;
}
try {
return icoHome.findAll();
} catch (FinderException e) {
e.printStackTrace();
}
return null;
}
}
| idega/com.idega.builder | src/java/com/idega/builder/presentation/AddModuleBlock.java | Java | gpl-3.0 | 8,828 |
using System.Net.Sockets;
namespace ServerCore
{
public interface IProtocolFactory
{
IProtocol CreateProtocol(Socket a_ClientSocket, ILogger a_Logger, IDataSource a_DataSource);
}
}
| mycargus/bearded-code | dotNet/ImageClientAndServer/ImageServer/ServerCore/IProtocolFactory.cs | C# | gpl-3.0 | 215 |
/*
* ScrInputStream.java
* Copyright 2012 Patrick Meade
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.rpgsheet.xcom.io;
import com.rpgsheet.xcom.slick.Palette;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.newdawn.slick.Color;
import org.newdawn.slick.Image;
import org.newdawn.slick.ImageBuffer;
public class ScrInputStream
{
public ScrInputStream(InputStream inputStream)
{
this.dataInputStream = new DataInputStream(inputStream);
}
public Image readImage(Palette palette) throws IOException
{
ImageBuffer imageBuffer = new ImageBuffer(320, 200);
for(int y=0; y<200; y++) {
for(int x=0; x<320; x++) {
int color = dataInputStream.readUnsignedByte();
Color c = palette.getColor(color & (palette.getNumColors()-1));
imageBuffer.setRGBA(x, y, c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
}
}
return imageBuffer.getImage(Image.FILTER_NEAREST);
}
private DataInputStream dataInputStream;
}
| blinkdog/xcom | src/main/java/com/rpgsheet/xcom/io/ScrInputStream.java | Java | gpl-3.0 | 1,727 |
#!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import jsonschema
import yaml
from snapcraft.internal import common
class SnapcraftSchemaError(Exception):
@property
def message(self):
return self._message
def __init__(self, message):
self._message = message
class Validator:
def __init__(self, snapcraft_yaml=None):
"""Create a validation instance for snapcraft_yaml."""
self._snapcraft = snapcraft_yaml if snapcraft_yaml else {}
self._load_schema()
@property
def schema(self):
"""Return all schema properties."""
return self._schema['properties'].copy()
@property
def part_schema(self):
"""Return part-specific schema properties."""
sub = self.schema['parts']['patternProperties']
properties = sub['^(?!plugins$)[a-z0-9][a-z0-9+-\/]*$']['properties']
return properties
def _load_schema(self):
schema_file = os.path.abspath(os.path.join(
common.get_schemadir(), 'snapcraft.yaml'))
try:
with open(schema_file) as fp:
self._schema = yaml.load(fp)
except FileNotFoundError:
raise SnapcraftSchemaError(
'snapcraft validation file is missing from installation path')
def validate(self):
format_check = jsonschema.FormatChecker()
try:
jsonschema.validate(
self._snapcraft, self._schema, format_checker=format_check)
except jsonschema.ValidationError as e:
messages = [e.message]
path = []
while e.absolute_path:
element = e.absolute_path.popleft()
# assume numbers are indices and use 'xxx[123]' notation.
if isinstance(element, int):
path[-1] = '{}[{}]'.format(path[-1], element)
else:
path.append(str(element))
if path:
messages.insert(0, "The '{}' property does not match the "
"required schema:".format('/'.join(path)))
if e.cause:
messages.append('({})'.format(e.cause))
raise SnapcraftSchemaError(' '.join(messages))
| jonathon-love/snapcraft | snapcraft/_schema.py | Python | gpl-3.0 | 2,896 |
angular.module('senseItWeb', null, null).controller('ProfileCtrl', function ($scope, OpenIdService, $state, fileReader) {
'use strict';
var _ = $scope._
, password_min = 6;
$scope.noyes = [
{value: '0', label: 'no'},
{value: '1', label: 'yes'}
];
if (!$scope.status.logged && $state.params.goBack) {
OpenIdService.registerWatcher($scope, function () {
if ($scope.status.logged) {
$state.go($state.previous);
}
});
}
$scope.form = new SiwFormManager(function () {
if ($scope.status.profile.metadata === null) {
$scope.status.profile.metadata = {};
}
if ($scope.status.profile.visibility === null) {
$scope.status.profile.visibility = {};
}
return $scope.status.profile;
}, ['username', 'email', 'notify1', 'notify2', 'notify3', 'notify4', 'notify5', 'metadata', 'visibility'], function () {
$scope.status.newUser = false;
$scope.openIdService.saveProfile().then(function (data) {
$scope.formError = data.responses.username || null;
if ($scope.formError) {
$scope.form.open('username');
}
});
}, function () {
$scope.formError = null;
}
);
$scope.visibilityDisplay = function () {
var options = [
['metadata', 'Profile information'],
['projectsJoined', 'Joined projects'],
['projectsCreated', 'Projects created by me']
].filter(function (option) {
return $scope.status.profile.visibility &&
$scope.status.profile.visibility[option[0]];
});
if (options.length > 0) {
return options.map(function (option) {
return '<b>' + option[1] + '</b>';
}).join(', ');
} else {
return 'none';
}
};
$scope.imageForm = new SiwFormManager(function () {
return $scope.status.profile;
}, [], function () {
$scope.openIdService.saveProfileImage($scope.imageForm.files);
});
$scope.filelistener = {
previewFile: null,
set: function (key, file) {
$scope.imageForm.setFile(key, file);
this.updatePreview();
},
clear: function (key) {
$scope.imageForm.clearFile(key);
this.updatePreview();
},
deleteFile: function (key) {
$scope.imageForm.deleteFile(key);
this.updatePreview();
},
updatePreview: function () {
if ($scope.imageForm.files['image']) {
fileReader.readAsDataUrl($scope.imageForm.files['image'], $scope).then(function (result) {
$scope.filelistener.previewFile = result;
});
} else {
$scope.filelistener.previewFile = null;
}
}
};
$scope.filelistener.updatePreview();
$scope.logout = function () {
$scope.openIdService.logout();
};
$scope.providerLogin = function (provider, action) {
OpenIdService.providerLogin(provider, action);
};
$scope.deleteConnection = function (providerId) {
$scope.openIdService.deleteConnection(providerId);
};
$scope.formError = null;
$scope.formErrorText = function () {
switch ($scope.formError) {
case 'username_empty':
return 'Username cannot be empty';
case 'username_not_available':
return 'Username not available (already taken)';
default:
return '';
}
};
$scope.loginMode = {
mode: 'login',
set: function (mode) {
this.mode = mode;
},
is: function (mode) {
return this.mode === mode;
}
};
$scope.login = {
editing: {username: '', password: ''},
error: {
username: false,
password: false
},
clearPassword: function () {
var p = this.editing.password;
this.editing.password = "";
return p;
},
submit: function () {
var ok = true;
this.editing.username = this.editing.username.trim();
if (this.editing.username.length === 0) {
this.error.username = _('Username cannot be empty.');
ok = false;
}
if (this.editing.password.length === 0) {
this.error.password = _('Password cannot be empty.');
ok = false;
}
if (ok) {
var error = this.error;
error.username = null;
OpenIdService.login(this.editing.username, this.clearPassword(), function (data) {
error.password = data === 'false' ? _('Username & password do not match.') : null;
});
}
}
};
$scope.register = {
recaptcha: {siteKey: $scope.cfg.recaptcha.siteKey},
editing: {username: '', password: '', repeatPassword: '', email: ''},
error: {username: false, password: false, repeatPassword: false, email: false, recaptcha: false},
clearPassword: function () {
var p = this.editing.password;
this.editing.password = this.editing.repeatPassword = "";
return p;
},
reset: function () {
this.editing = {username: '', password: '', repeatPassword: '', email: ''};
this.error = {username: false, password: false, repeatPassword: false, email: false, recaptcha: false};
},
submit: function () {
var ok = true;
this.editing.username = this.editing.username.trim();
this.editing.email = this.editing.email.trim();
this.editing.recaptcha = angular.element("#g-recaptcha-response").val();
this.error = {username: false, password: false, repeatPassword: false, email: false, recaptcha: false};
if (this.editing.username.length === 0) {
this.error.username = _('Username cannot be empty.');
ok = false;
}
if (this.editing.email.length === 0) {
this.error.email = _('Email cannot be empty.');
ok = false;
}
if (this.editing.password.length < password_min) {
this.error.password = _('Password must have at least {{n}} characters.', { 'n': password_min });
ok = false;
}
if (this.editing.password !== this.editing.repeatPassword) {
this.error.repeatPassword = _('Passwords do not match.');
ok = false;
}
if (this.editing.recaptcha === '') {
this.error.recaptcha = _('Are you a human being or a robot?');
ok = false;
}
if (ok) {
var error = this.error = {username: false, password: false, repeatPassword: false, email: false};
OpenIdService.register(this.editing.username, this.clearPassword(), this.editing.email, this.editing.recaptcha).then(function (data) {
switch (data.responses.registration) {
case 'username_exists':
error.username = _('Username not available.');
break;
case 'email_exists':
error.email = _('Email already associated with a different account.');
break;
case 'bad_recaptcha':
error.recaptcha = _('Captcha failed. Try again.');
grecaptcha.reset();
break;
}
});
}
}
};
$scope.reminder = {
recaptcha: {siteKey: $scope.cfg.recaptcha.siteKey},
editing: {email: ''},
error: {email: false},
reset: function () {
this.editing = {email: ''};
this.error = {email: false};
},
submit: function () {
var ok = true;
this.editing.email = this.editing.email.trim();
this.editing.recaptcha = angular.element("#g-recaptcha-response").val();
if (this.editing.email.length === 0) {
this.error.email = _('Email cannot be empty.');
ok = false;
}
if (this.editing.recaptcha === '') {
this.error.recaptcha = _('Are you a human being or a robot?');
ok = false;
}
if (ok) {
var error = this.error = {email: false};
OpenIdService.reminder(this.editing.email, this.editing.recaptcha).then(function (data) {
grecaptcha.reset();
switch (data.responses.reminder) {
case 'email_not_exists':
error.email = _('No account found with that email or username.');
break;
case 'bad_recaptcha':
error.recaptcha = _('Captcha failed. Try again.');
break;
case 'reminder_sent':
error.email = _('A password reminder has been sent.');
break;
}
});
}
}
};
$scope.password = {
set: function () {
return $scope.status.profile.passwordSet;
},
editing: false,
error: {
oldPassword: false,
newPassword: false,
repeatPassword: false
},
edit: function () {
this.editing = {oldPassword: '', newPassword: '', repeatPassword: ''};
},
close: function () {
this.editing = false;
},
cancel: function () {
this.close();
},
save: function () {
var ok = true;
if (this.editing.newPassword.length < password_min) {
this.error.password = _('Password must have at least {{n}} characters.', { 'n': password_min });
ok = false;
}
if (this.editing.newPassword !== this.editing.repeatPassword) {
this.error.repeatPassword = _('Passwords do not match.');
ok = false;
}
if (ok) {
var self = this;
var error = self.error;
error.repeatPassword = false;
OpenIdService.setPassword(this.editing.oldPassword, this.editing.newPassword).then(function (data) {
switch (data.responses.oldpassword) {
case 'bad_password':
error.oldPassword = 'Old password is not valid.';
break;
default:
error.oldPassword = false;
break;
}
switch (data.responses.newpassword) {
case 'too_short':
error.newPassword = 'New password is too short.';
break;
case 'same_as_username':
error.newPassword = 'New password cannot be equal to your username.';
break;
default:
error.newPassword = false;
break;
}
if (!error.repeatPassword && !error.newPassword && !error.oldPassword) {
self.close();
}
});
}
}
};
});
| IET-OU/nquire-web-source | static/src/js/app/controllers/profile/profile-controller.js | JavaScript | gpl-3.0 | 10,138 |
<?php
// Heading
$_['heading_title'] = 'Áp dụng mã giảm giá';
// Text
$_['text_coupon'] = 'Coupon(%s):';
$_['text_success'] = 'Thành công: Mã giảm giả của bạn đã được áp dụng!';
// Entry
$_['entry_coupon'] = 'Nhập mã giảm giá ở đây:';
// Error
$_['error_coupon'] = 'Lỗi: Mã giảm giá không tồn tại, quá hạn hay đã được sử dụng!';
?> | rongandat/juss | catalog/language/vietnamese/total/coupon.php | PHP | gpl-3.0 | 401 |
/*
* A JavaScript implementation of the SHA256 hash function.
*
* FILE: sha256.js
* VERSION: 0.8
* AUTHOR: Christoph Bichlmeier <informatik@zombiearena.de>
*
* NOTE: This version is not tested thoroughly!
*
* Copyright (c) 2003, Christoph Bichlmeier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* ======================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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.
*/
/* SHA256 logical functions */
function rotateRight(n,x) {
return ((x >>> n) | (x << (32 - n)));
}
function choice(x,y,z) {
return ((x & y) ^ (~x & z));
}
function majority(x,y,z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
function sha256_Sigma0(x) {
return (rotateRight(2, x) ^ rotateRight(13, x) ^ rotateRight(22, x));
}
function sha256_Sigma1(x) {
return (rotateRight(6, x) ^ rotateRight(11, x) ^ rotateRight(25, x));
}
function sha256_sigma0(x) {
return (rotateRight(7, x) ^ rotateRight(18, x) ^ (x >>> 3));
}
function sha256_sigma1(x) {
return (rotateRight(17, x) ^ rotateRight(19, x) ^ (x >>> 10));
}
function sha256_expand(W, j) {
return (W[j&0x0f] += sha256_sigma1(W[(j+14)&0x0f]) + W[(j+9)&0x0f] +
sha256_sigma0(W[(j+1)&0x0f]));
}
/* Hash constant words K: */
var K256 = new Array(
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
);
/* global arrays */
var ihash, count, buffer;
var sha256_hex_digits = "0123456789abcdef";
/* Add 32-bit integers with 16-bit operations (bug in some JS-interpreters:
overflow) */
function safe_add(x, y)
{
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/* Initialise the SHA256 computation */
function sha256_init() {
ihash = new Array(8);
count = new Array(2);
buffer = new Array(64);
count[0] = count[1] = 0;
ihash[0] = 0x6a09e667;
ihash[1] = 0xbb67ae85;
ihash[2] = 0x3c6ef372;
ihash[3] = 0xa54ff53a;
ihash[4] = 0x510e527f;
ihash[5] = 0x9b05688c;
ihash[6] = 0x1f83d9ab;
ihash[7] = 0x5be0cd19;
}
/* Transform a 512-bit message block */
function sha256_transform() {
var a, b, c, d, e, f, g, h, T1, T2;
var W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for(var i=0; i<16; i++)
W[i] = ((buffer[(i<<2)+3]) | (buffer[(i<<2)+2] << 8) | (buffer[(i<<2)+1]
<< 16) | (buffer[i<<2] << 24));
for(var j=0; j<64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if(j < 16) T1 += W[j];
else T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
}
/* Read the next chunk of data and update the SHA256 computation */
function sha256_update(data, inputLen) {
var i, index, curpos = 0;
/* Compute number of bytes mod 64 */
index = ((count[0] >> 3) & 0x3f);
var remainder = (inputLen & 0x3f);
/* Update number of bits */
if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++;
count[1] += (inputLen >> 29);
/* Transform as many times as possible */
for(i=0; i+63<inputLen; i+=64) {
for(var j=index; j<64; j++)
buffer[j] = data.charCodeAt(curpos++);
sha256_transform();
index = 0;
}
/* Buffer remaining input */
for(var j=0; j<remainder; j++)
buffer[j] = data.charCodeAt(curpos++);
}
/* Finish the computation by operations such as padding */
function sha256_final() {
var index = ((count[0] >> 3) & 0x3f);
buffer[index++] = 0x80;
if(index <= 56) {
for(var i=index; i<56; i++)
buffer[i] = 0;
} else {
for(var i=index; i<64; i++)
buffer[i] = 0;
sha256_transform();
for(var i=0; i<56; i++)
buffer[i] = 0;
}
buffer[56] = (count[1] >>> 24) & 0xff;
buffer[57] = (count[1] >>> 16) & 0xff;
buffer[58] = (count[1] >>> 8) & 0xff;
buffer[59] = count[1] & 0xff;
buffer[60] = (count[0] >>> 24) & 0xff;
buffer[61] = (count[0] >>> 16) & 0xff;
buffer[62] = (count[0] >>> 8) & 0xff;
buffer[63] = count[0] & 0xff;
sha256_transform();
}
/* Split the internal hash values into an array of bytes */
function sha256_encode_bytes() {
var j=0;
var output = new Array(32);
for(var i=0; i<8; i++) {
output[j++] = ((ihash[i] >>> 24) & 0xff);
output[j++] = ((ihash[i] >>> 16) & 0xff);
output[j++] = ((ihash[i] >>> 8) & 0xff);
output[j++] = (ihash[i] & 0xff);
}
return output;
}
/* Get the internal hash as a hex string */
function sha256_encode_hex() {
var output = new String();
for(var i=0; i<8; i++) {
for(var j=28; j>=0; j-=4)
output += sha256_hex_digits.charAt((ihash[i] >>> j) & 0x0f);
}
return output;
}
/* Main function: returns a hex string representing the SHA256 value of the
given data */
function sha256_digest(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
}
/* test if the JS-interpreter is working properly */
function sha256_self_test()
{
return sha256_digest("message digest") ==
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650";
}
| smit-happens/WhiteboardProject | Whiteboard/WebContent/sha256.js | JavaScript | gpl-3.0 | 7,554 |
package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.exifinterface.media.ExifInterface;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import org.signal.core.util.ThreadUtil;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.mms.GlideApp;
import org.thoughtcrime.securesms.mms.MediaConstraints;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
public class BitmapUtil {
private static final String TAG = BitmapUtil.class.getSimpleName();
private static final int MAX_COMPRESSION_QUALITY = 90;
private static final int MIN_COMPRESSION_QUALITY = 45;
private static final int MAX_COMPRESSION_ATTEMPTS = 5;
private static final int MIN_COMPRESSION_QUALITY_DECREASE = 5;
private static final int MAX_IMAGE_HALF_SCALES = 3;
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@Deprecated
@WorkerThread
public static <T> ScaleResult createScaledBytes(@NonNull Context context, @NonNull T model, @NonNull MediaConstraints constraints)
throws BitmapDecodingException
{
return createScaledBytes(context, model,
constraints.getImageMaxWidth(context),
constraints.getImageMaxHeight(context),
constraints.getImageMaxSize(context));
}
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@WorkerThread
public static <T> ScaleResult createScaledBytes(@NonNull Context context,
@NonNull T model,
final int maxImageWidth,
final int maxImageHeight,
final int maxImageSize)
throws BitmapDecodingException
{
return createScaledBytes(context, model, maxImageWidth, maxImageHeight, maxImageSize, CompressFormat.JPEG);
}
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@WorkerThread
public static <T> ScaleResult createScaledBytes(Context context,
T model,
int maxImageWidth,
int maxImageHeight,
int maxImageSize,
@NonNull CompressFormat format)
throws BitmapDecodingException
{
return createScaledBytes(context, model, maxImageWidth, maxImageHeight, maxImageSize, format, 1, 0);
}
@WorkerThread
private static <T> ScaleResult createScaledBytes(@NonNull Context context,
@NonNull T model,
final int maxImageWidth,
final int maxImageHeight,
final int maxImageSize,
@NonNull CompressFormat format,
final int sizeAttempt,
int totalAttempts)
throws BitmapDecodingException
{
try {
int quality = MAX_COMPRESSION_QUALITY;
int attempts = 0;
byte[] bytes;
Bitmap scaledBitmap = GlideApp.with(context.getApplicationContext())
.asBitmap()
.load(model)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.centerInside()
.submit(maxImageWidth, maxImageHeight)
.get();
if (scaledBitmap == null) {
throw new BitmapDecodingException("Unable to decode image");
}
Log.i(TAG, String.format(Locale.US,"Initial scaled bitmap has size of %d bytes.", scaledBitmap.getByteCount()));
Log.i(TAG, String.format(Locale.US, "Max dimensions %d x %d, %d bytes", maxImageWidth, maxImageHeight, maxImageSize));
try {
do {
totalAttempts++;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
scaledBitmap.compress(format, quality, baos);
bytes = baos.toByteArray();
Log.d(TAG, "iteration with quality " + quality + " size " + bytes.length + " bytes.");
if (quality == MIN_COMPRESSION_QUALITY) break;
int nextQuality = (int)Math.floor(quality * Math.sqrt((double)maxImageSize / bytes.length));
if (quality - nextQuality < MIN_COMPRESSION_QUALITY_DECREASE) {
nextQuality = quality - MIN_COMPRESSION_QUALITY_DECREASE;
}
quality = Math.max(nextQuality, MIN_COMPRESSION_QUALITY);
}
while (bytes.length > maxImageSize && attempts++ < MAX_COMPRESSION_ATTEMPTS);
if (bytes.length > maxImageSize) {
if (sizeAttempt <= MAX_IMAGE_HALF_SCALES) {
scaledBitmap.recycle();
scaledBitmap = null;
Log.i(TAG, "Halving dimensions and retrying.");
return createScaledBytes(context, model, maxImageWidth / 2, maxImageHeight / 2, maxImageSize, format, sizeAttempt + 1, totalAttempts);
} else {
throw new BitmapDecodingException("Unable to scale image below " + bytes.length + " bytes.");
}
}
if (bytes.length <= 0) {
throw new BitmapDecodingException("Decoding failed. Bitmap has a length of " + bytes.length + " bytes.");
}
Log.i(TAG, String.format(Locale.US, "createScaledBytes(%s) -> quality %d, %d attempt(s) over %d sizes.", model.getClass().getName(), quality, totalAttempts, sizeAttempt));
return new ScaleResult(bytes, scaledBitmap.getWidth(), scaledBitmap.getHeight());
} finally {
if (scaledBitmap != null) scaledBitmap.recycle();
}
} catch (InterruptedException | ExecutionException e) {
throw new BitmapDecodingException(e);
}
}
@WorkerThread
public static <T> Bitmap createScaledBitmap(Context context, T model, int maxWidth, int maxHeight)
throws BitmapDecodingException
{
try {
return GlideApp.with(context.getApplicationContext())
.asBitmap()
.load(model)
.centerInside()
.submit(maxWidth, maxHeight)
.get();
} catch (InterruptedException | ExecutionException e) {
throw new BitmapDecodingException(e);
}
}
@WorkerThread
public static Bitmap createScaledBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
if (bitmap.getWidth() <= maxWidth && bitmap.getHeight() <= maxHeight) {
return bitmap;
}
if (maxWidth <= 0 || maxHeight <= 0) {
return bitmap;
}
int newWidth = maxWidth;
int newHeight = maxHeight;
float widthRatio = bitmap.getWidth() / (float) maxWidth;
float heightRatio = bitmap.getHeight() / (float) maxHeight;
if (widthRatio > heightRatio) {
newHeight = (int) (bitmap.getHeight() / widthRatio);
} else {
newWidth = (int) (bitmap.getWidth() / heightRatio);
}
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
public static @NonNull CompressFormat getCompressFormatForContentType(@Nullable String contentType) {
if (contentType == null) return CompressFormat.JPEG;
switch (contentType) {
case MediaUtil.IMAGE_JPEG: return CompressFormat.JPEG;
case MediaUtil.IMAGE_PNG: return CompressFormat.PNG;
case MediaUtil.IMAGE_WEBP: return CompressFormat.WEBP;
default: return CompressFormat.JPEG;
}
}
private static BitmapFactory.Options getImageDimensions(InputStream inputStream)
throws BitmapDecodingException
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BufferedInputStream fis = new BufferedInputStream(inputStream);
BitmapFactory.decodeStream(fis, null, options);
try {
fis.close();
} catch (IOException ioe) {
Log.w(TAG, "failed to close the InputStream after reading image dimensions");
}
if (options.outWidth == -1 || options.outHeight == -1) {
throw new BitmapDecodingException("Failed to decode image dimensions: " + options.outWidth + ", " + options.outHeight);
}
return options;
}
@Nullable
public static Pair<Integer, Integer> getExifDimensions(InputStream inputStream) throws IOException {
ExifInterface exif = new ExifInterface(inputStream);
int width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
int height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
if (width == 0 || height == 0) {
return null;
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90 ||
orientation == ExifInterface.ORIENTATION_ROTATE_270 ||
orientation == ExifInterface.ORIENTATION_TRANSVERSE ||
orientation == ExifInterface.ORIENTATION_TRANSPOSE)
{
return new Pair<>(height, width);
}
return new Pair<>(width, height);
}
public static Pair<Integer, Integer> getDimensions(InputStream inputStream) throws BitmapDecodingException {
BitmapFactory.Options options = getImageDimensions(inputStream);
return new Pair<>(options.outWidth, options.outHeight);
}
public static InputStream toCompressedJpeg(Bitmap bitmap) {
ByteArrayOutputStream thumbnailBytes = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 85, thumbnailBytes);
return new ByteArrayInputStream(thumbnailBytes.toByteArray());
}
public static @Nullable byte[] toByteArray(@Nullable Bitmap bitmap) {
if (bitmap == null) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
public static @Nullable byte[] toWebPByteArray(@Nullable Bitmap bitmap) {
if (bitmap == null) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (Build.VERSION.SDK_INT >= 30) {
bitmap.compress(CompressFormat.WEBP_LOSSLESS, 100, stream);
} else {
bitmap.compress(CompressFormat.WEBP, 100, stream);
}
return stream.toByteArray();
}
public static @Nullable Bitmap fromByteArray(@Nullable byte[] bytes) {
if (bytes == null) return null;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public static byte[] createFromNV21(@NonNull final byte[] data,
final int width,
final int height,
int rotation,
final Rect croppingRect,
final boolean flipHorizontal)
throws IOException
{
byte[] rotated = rotateNV21(data, width, height, rotation, flipHorizontal);
final int rotatedWidth = rotation % 180 > 0 ? height : width;
final int rotatedHeight = rotation % 180 > 0 ? width : height;
YuvImage previewImage = new YuvImage(rotated, ImageFormat.NV21,
rotatedWidth, rotatedHeight, null);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
previewImage.compressToJpeg(croppingRect, 80, outputStream);
byte[] bytes = outputStream.toByteArray();
outputStream.close();
return bytes;
}
/*
* NV21 a.k.a. YUV420sp
* YUV 4:2:0 planar image, with 8 bit Y samples, followed by interleaved V/U plane with 8bit 2x2
* subsampled chroma samples.
*
* http://www.fourcc.org/yuv.php#NV21
*/
public static byte[] rotateNV21(@NonNull final byte[] yuv,
final int width,
final int height,
final int rotation,
final boolean flipHorizontal)
throws IOException
{
if (rotation == 0) return yuv;
if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
} else if ((width * height * 3) / 2 != yuv.length) {
throw new IOException("provided width and height don't jive with the data length (" +
yuv.length + "). Width: " + width + " height: " + height +
" = data length: " + (width * height * 3) / 2);
}
final byte[] output = new byte[yuv.length];
final int frameSize = width * height;
final boolean swap = rotation % 180 != 0;
final boolean xflip = flipHorizontal ? rotation % 270 == 0 : rotation % 270 != 0;
final boolean yflip = rotation >= 180;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
final int yIn = j * width + i;
final int uIn = frameSize + (j >> 1) * width + (i & ~1);
final int vIn = uIn + 1;
final int wOut = swap ? height : width;
final int hOut = swap ? width : height;
final int iSwapped = swap ? j : i;
final int jSwapped = swap ? i : j;
final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
final int yOut = jOut * wOut + iOut;
final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
final int vOut = uOut + 1;
output[yOut] = (byte)(0xff & yuv[yIn]);
output[uOut] = (byte)(0xff & yuv[uIn]);
output[vOut] = (byte)(0xff & yuv[vIn]);
}
}
return output;
}
public static Bitmap createFromDrawable(final Drawable drawable, final int width, final int height) {
final AtomicBoolean created = new AtomicBoolean(false);
final Bitmap[] result = new Bitmap[1];
Runnable runnable = new Runnable() {
@Override
public void run() {
if (drawable instanceof BitmapDrawable) {
result[0] = ((BitmapDrawable) drawable).getBitmap();
} else {
int canvasWidth = drawable.getIntrinsicWidth();
if (canvasWidth <= 0) canvasWidth = width;
int canvasHeight = drawable.getIntrinsicHeight();
if (canvasHeight <= 0) canvasHeight = height;
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
} catch (Exception e) {
Log.w(TAG, e);
bitmap = null;
}
result[0] = bitmap;
}
synchronized (result) {
created.set(true);
result.notifyAll();
}
}
};
ThreadUtil.runOnMain(runnable);
synchronized (result) {
while (!created.get()) Util.wait(result, 0);
return result[0];
}
}
public static int getMaxTextureSize() {
final int MAX_ALLOWED_TEXTURE_SIZE = 2048;
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(display, version);
int[] totalConfigurations = new int[1];
egl.eglGetConfigs(display, null, 0, totalConfigurations);
EGLConfig[] configurationsList = new EGLConfig[totalConfigurations[0]];
egl.eglGetConfigs(display, configurationsList, totalConfigurations[0], totalConfigurations);
int[] textureSize = new int[1];
int maximumTextureSize = 0;
for (int i = 0; i < totalConfigurations[0]; i++) {
egl.eglGetConfigAttrib(display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_WIDTH, textureSize);
if (maximumTextureSize < textureSize[0])
maximumTextureSize = textureSize[0];
}
egl.eglTerminate(display);
return Math.min(maximumTextureSize, MAX_ALLOWED_TEXTURE_SIZE);
}
public static class ScaleResult {
private final byte[] bitmap;
private final int width;
private final int height;
public ScaleResult(byte[] bitmap, int width, int height) {
this.bitmap = bitmap;
this.width = width;
this.height = height;
}
public byte[] getBitmap() {
return bitmap;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
}
| stinsonga/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/BitmapUtil.java | Java | gpl-3.0 | 18,105 |
using System;
namespace Yoeca.Sql
{
/// <summary>
/// Attribute to identify a property as a primary key of a table.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class SqlPrimaryKeyAttribute : Attribute
{
}
} | basvanderlaken/yoeca-sql | Yoeca.Sql/Attributes/SqlPrimaryKeyAttribute.cs | C# | gpl-3.0 | 267 |
/*
Copyright (C) 2012-2014 de4dot@gmail.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using dnlib.IO;
using dnlib.PE;
using dnlib.W32Resources;
namespace dnlib.DotNet.Writer {
/// <summary>
/// Writes Win32 resources
/// </summary>
public sealed class Win32ResourcesChunk : IChunk {
readonly Win32Resources win32Resources;
FileOffset offset;
RVA rva;
uint length;
readonly Dictionary<ResourceDirectory, uint> dirDict = new Dictionary<ResourceDirectory, uint>();
readonly List<ResourceDirectory> dirList = new List<ResourceDirectory>();
readonly Dictionary<ResourceData, uint> dataHeaderDict = new Dictionary<ResourceData, uint>();
readonly List<ResourceData> dataHeaderList = new List<ResourceData>();
readonly Dictionary<string, uint> stringsDict = new Dictionary<string, uint>(StringComparer.Ordinal);
readonly List<string> stringsList = new List<string>();
readonly Dictionary<IBinaryReader, uint> dataDict = new Dictionary<IBinaryReader, uint>();
readonly List<IBinaryReader> dataList = new List<IBinaryReader>();
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="win32Resources">Win32 resources</param>
public Win32ResourcesChunk(Win32Resources win32Resources) {
this.win32Resources = win32Resources;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> and <see cref="RVA"/> of a
/// <see cref="ResourceDirectoryEntry"/>. <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dirEntry">A <see cref="ResourceDirectoryEntry"/></param>
/// <param name="fileOffset">Updated with the file offset</param>
/// <param name="rva">Updated with the RVA</param>
/// <returns><c>true</c> if <paramref name="dirEntry"/> is valid and
/// <paramref name="fileOffset"/> and <paramref name="rva"/> have been updated. <c>false</c>
/// if <paramref name="dirEntry"/> is not part of the Win32 resources.</returns>
public bool GetFileOffsetAndRvaOf(ResourceDirectoryEntry dirEntry, out FileOffset fileOffset, out RVA rva) {
var dir = dirEntry as ResourceDirectory;
if (dir != null)
return GetFileOffsetAndRvaOf(dir, out fileOffset, out rva);
var dataHeader = dirEntry as ResourceData;
if (dataHeader != null)
return GetFileOffsetAndRvaOf(dataHeader, out fileOffset, out rva);
fileOffset = 0;
rva = 0;
return false;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> of a <see cref="ResourceDirectoryEntry"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dirEntry">A <see cref="ResourceDirectoryEntry"/></param>
/// <returns>The file offset or 0 if <paramref name="dirEntry"/> is invalid</returns>
public FileOffset GetFileOffset(ResourceDirectoryEntry dirEntry) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dirEntry, out fileOffset, out rva);
return fileOffset;
}
/// <summary>
/// Returns the <see cref="RVA"/> of a <see cref="ResourceDirectoryEntry"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dirEntry">A <see cref="ResourceDirectoryEntry"/></param>
/// <returns>The RVA or 0 if <paramref name="dirEntry"/> is invalid</returns>
public RVA GetRVA(ResourceDirectoryEntry dirEntry) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dirEntry, out fileOffset, out rva);
return rva;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> and <see cref="RVA"/> of a
/// <see cref="ResourceDirectory"/>. <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dir">A <see cref="ResourceDirectory"/></param>
/// <param name="fileOffset">Updated with the file offset</param>
/// <param name="rva">Updated with the RVA</param>
/// <returns><c>true</c> if <paramref name="dir"/> is valid and
/// <paramref name="fileOffset"/> and <paramref name="rva"/> have been updated. <c>false</c>
/// if <paramref name="dir"/> is not part of the Win32 resources.</returns>
public bool GetFileOffsetAndRvaOf(ResourceDirectory dir, out FileOffset fileOffset, out RVA rva) {
uint offs;
if (dir == null || !dirDict.TryGetValue(dir, out offs)) {
fileOffset = 0;
rva = 0;
return false;
}
fileOffset = offset + offs;
rva = this.rva + offs;
return true;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> of a <see cref="ResourceDirectory"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dir">A <see cref="ResourceDirectory"/></param>
/// <returns>The file offset or 0 if <paramref name="dir"/> is invalid</returns>
public FileOffset GetFileOffset(ResourceDirectory dir) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dir, out fileOffset, out rva);
return fileOffset;
}
/// <summary>
/// Returns the <see cref="RVA"/> of a <see cref="ResourceDirectory"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dir">A <see cref="ResourceDirectory"/></param>
/// <returns>The RVA or 0 if <paramref name="dir"/> is invalid</returns>
public RVA GetRVA(ResourceDirectory dir) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dir, out fileOffset, out rva);
return rva;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> and <see cref="RVA"/> of a
/// <see cref="ResourceData"/>. <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dataHeader">A <see cref="ResourceData"/></param>
/// <param name="fileOffset">Updated with the file offset</param>
/// <param name="rva">Updated with the RVA</param>
/// <returns><c>true</c> if <paramref name="dataHeader"/> is valid and
/// <paramref name="fileOffset"/> and <paramref name="rva"/> have been updated. <c>false</c>
/// if <paramref name="dataHeader"/> is not part of the Win32 resources.</returns>
public bool GetFileOffsetAndRvaOf(ResourceData dataHeader, out FileOffset fileOffset, out RVA rva) {
uint offs;
if (dataHeader == null || !dataHeaderDict.TryGetValue(dataHeader, out offs)) {
fileOffset = 0;
rva = 0;
return false;
}
fileOffset = offset + offs;
rva = this.rva + offs;
return true;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> of a <see cref="ResourceData"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dataHeader">A <see cref="ResourceData"/></param>
/// <returns>The file offset or 0 if <paramref name="dataHeader"/> is invalid</returns>
public FileOffset GetFileOffset(ResourceData dataHeader) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dataHeader, out fileOffset, out rva);
return fileOffset;
}
/// <summary>
/// Returns the <see cref="RVA"/> of a <see cref="ResourceData"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="dataHeader">A <see cref="ResourceData"/></param>
/// <returns>The RVA or 0 if <paramref name="dataHeader"/> is invalid</returns>
public RVA GetRVA(ResourceData dataHeader) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(dataHeader, out fileOffset, out rva);
return rva;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> and <see cref="RVA"/> of the raw data
/// owned by a <see cref="ResourceData"/>. <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="data">A <see cref="ResourceData"/>'s <see cref="IBinaryReader"/></param>
/// <param name="fileOffset">Updated with the file offset</param>
/// <param name="rva">Updated with the RVA</param>
/// <returns><c>true</c> if <paramref name="data"/> is valid and
/// <paramref name="fileOffset"/> and <paramref name="rva"/> have been updated. <c>false</c>
/// if <paramref name="data"/> is not part of the Win32 resources.</returns>
public bool GetFileOffsetAndRvaOf(IBinaryReader data, out FileOffset fileOffset, out RVA rva) {
uint offs;
if (data == null || !dataDict.TryGetValue(data, out offs)) {
fileOffset = 0;
rva = 0;
return false;
}
fileOffset = offset + offs;
rva = this.rva + offs;
return true;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> of the raw data owned by a
/// <see cref="ResourceData"/>. <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="data">A <see cref="ResourceData"/>'s <see cref="IBinaryReader"/></param>
/// <returns>The file offset or 0 if <paramref name="data"/> is invalid</returns>
public FileOffset GetFileOffset(IBinaryReader data) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(data, out fileOffset, out rva);
return fileOffset;
}
/// <summary>
/// Returns the <see cref="RVA"/> of the raw data owned by a <see cref="ResourceData"/>.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="data">A <see cref="ResourceData"/>'s <see cref="IBinaryReader"/></param>
/// <returns>The RVA or 0 if <paramref name="data"/> is invalid</returns>
public RVA GetRVA(IBinaryReader data) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(data, out fileOffset, out rva);
return rva;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> and <see cref="RVA"/> of a
/// <see cref="ResourceDirectoryEntry"/>'s name. <see cref="SetOffset"/> must have been
/// called.
/// </summary>
/// <param name="name">The name of a <see cref="ResourceDirectoryEntry"/></param>
/// <param name="fileOffset">Updated with the file offset</param>
/// <param name="rva">Updated with the RVA</param>
/// <returns><c>true</c> if <paramref name="name"/> is valid and
/// <paramref name="fileOffset"/> and <paramref name="rva"/> have been updated. <c>false</c>
/// if <paramref name="name"/> is not part of the Win32 resources.</returns>
public bool GetFileOffsetAndRvaOf(string name, out FileOffset fileOffset, out RVA rva) {
uint offs;
if (name == null || !stringsDict.TryGetValue(name, out offs)) {
fileOffset = 0;
rva = 0;
return false;
}
fileOffset = offset + offs;
rva = this.rva + offs;
return true;
}
/// <summary>
/// Returns the <see cref="FileOffset"/> of a <see cref="ResourceDirectoryEntry"/>'s name.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="name">The name of a <see cref="ResourceDirectoryEntry"/></param>
/// <returns>The file offset or 0 if <paramref name="name"/> is invalid</returns>
public FileOffset GetFileOffset(string name) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(name, out fileOffset, out rva);
return fileOffset;
}
/// <summary>
/// Returns the <see cref="RVA"/> of a <see cref="ResourceDirectoryEntry"/>'s name.
/// <see cref="SetOffset"/> must have been called.
/// </summary>
/// <param name="name">The name of a <see cref="ResourceDirectoryEntry"/></param>
/// <returns>The RVA or 0 if <paramref name="name"/> is invalid</returns>
public RVA GetRVA(string name) {
FileOffset fileOffset;
RVA rva;
GetFileOffsetAndRvaOf(name, out fileOffset, out rva);
return rva;
}
const uint RESOURCE_DIR_ALIGNMENT = 4;
const uint RESOURCE_DATA_HEADER_ALIGNMENT = 4;
const uint RESOURCE_STRING_ALIGNMENT = 2;
const uint RESOURCE_DATA_ALIGNMENT = 4;
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
if (win32Resources == null)
return;
FindDirectoryEntries();
// Place everything in the following order:
// 1. All resource directories. The root is always first.
// 2. All resource data headers.
// 3. All the strings.
// 4. All resource data.
uint rsrcOffset = 0;
uint maxAlignment = 1;
maxAlignment = Math.Max(maxAlignment, RESOURCE_DIR_ALIGNMENT);
maxAlignment = Math.Max(maxAlignment, RESOURCE_DATA_HEADER_ALIGNMENT);
maxAlignment = Math.Max(maxAlignment, RESOURCE_STRING_ALIGNMENT);
maxAlignment = Math.Max(maxAlignment, RESOURCE_DATA_ALIGNMENT);
if (((uint)offset & (maxAlignment - 1)) != 0)
throw new ModuleWriterException(string.Format("Win32 resources section isn't {0}-byte aligned", maxAlignment));
if (maxAlignment > ModuleWriterBase.DEFAULT_WIN32_RESOURCES_ALIGNMENT)
throw new ModuleWriterException("maxAlignment > DEFAULT_WIN32_RESOURCES_ALIGNMENT");
foreach (var dir in dirList) {
rsrcOffset = Utils.AlignUp(rsrcOffset, RESOURCE_DIR_ALIGNMENT);
dirDict[dir] = rsrcOffset;
if (dir != dirList[0])
AddString(dir.Name);
rsrcOffset += 16 + (uint)(dir.Directories.Count + dir.Data.Count) * 8;
}
foreach (var data in dataHeaderList) {
rsrcOffset = Utils.AlignUp(rsrcOffset, RESOURCE_DATA_HEADER_ALIGNMENT);
dataHeaderDict[data] = rsrcOffset;
AddString(data.Name);
AddData(data.Data);
rsrcOffset += 16;
}
foreach (var s in stringsList) {
rsrcOffset = Utils.AlignUp(rsrcOffset, RESOURCE_STRING_ALIGNMENT);
stringsDict[s] = rsrcOffset;
rsrcOffset += 2 + (uint)(s.Length * 2);
}
foreach (var data in dataList) {
rsrcOffset = Utils.AlignUp(rsrcOffset, RESOURCE_DATA_ALIGNMENT);
dataDict[data] = rsrcOffset;
rsrcOffset += (uint)data.Length;
}
length = rsrcOffset;
}
void AddData(IBinaryReader data) {
if (dataDict.ContainsKey(data))
return;
dataList.Add(data);
dataDict.Add(data, 0);
}
void AddString(ResourceName name) {
if (!name.HasName || stringsDict.ContainsKey(name.Name))
return;
stringsList.Add(name.Name);
stringsDict.Add(name.Name, 0);
}
void FindDirectoryEntries() {
FindDirectoryEntries(win32Resources.Root);
}
void FindDirectoryEntries(ResourceDirectory dir) {
if (dirDict.ContainsKey(dir))
return;
dirList.Add(dir);
dirDict[dir] = 0;
foreach (var dir2 in dir.Directories)
FindDirectoryEntries(dir2);
foreach (var data in dir.Data) {
if (dataHeaderDict.ContainsKey(data))
continue;
dataHeaderList.Add(data);
dataHeaderDict[data] = 0;
}
}
/// <inheritdoc/>
public uint GetFileLength() {
return Utils.AlignUp(length, ModuleWriterBase.DEFAULT_WIN32_RESOURCES_ALIGNMENT);
}
/// <inheritdoc/>
public uint GetVirtualSize() {
return GetFileLength();
}
/// <inheritdoc/>
public void WriteTo(BinaryWriter writer) {
uint offset = 0;
// The order here must be the same as in SetOffset()
foreach (var dir in dirList) {
uint padding = Utils.AlignUp(offset, RESOURCE_DIR_ALIGNMENT) - offset;
writer.WriteZeros((int)padding);
offset += padding;
if (dirDict[dir] != offset)
throw new ModuleWriterException("Invalid Win32 resource directory offset");
offset += WriteTo(writer, dir);
}
foreach (var dataHeader in dataHeaderList) {
uint padding = Utils.AlignUp(offset, RESOURCE_DATA_HEADER_ALIGNMENT) - offset;
writer.WriteZeros((int)padding);
offset += padding;
if (dataHeaderDict[dataHeader] != offset)
throw new ModuleWriterException("Invalid Win32 resource data header offset");
offset += WriteTo(writer, dataHeader);
}
foreach (var s in stringsList) {
uint padding = Utils.AlignUp(offset, RESOURCE_STRING_ALIGNMENT) - offset;
writer.WriteZeros((int)padding);
offset += padding;
if (stringsDict[s] != offset)
throw new ModuleWriterException("Invalid Win32 resource string offset");
var bytes = Encoding.Unicode.GetBytes(s);
if (bytes.Length / 2 > ushort.MaxValue)
throw new ModuleWriterException("Win32 resource entry name is too long");
writer.Write((ushort)(bytes.Length / 2));
writer.Write(bytes);
offset += 2 + (uint)bytes.Length;
}
byte[] dataBuffer = new byte[0x2000];
foreach (var data in dataList) {
uint padding = Utils.AlignUp(offset, RESOURCE_DATA_ALIGNMENT) - offset;
writer.WriteZeros((int)padding);
offset += padding;
if (dataDict[data] != offset)
throw new ModuleWriterException("Invalid Win32 resource data offset");
data.Position = 0;
offset += data.WriteTo(writer, dataBuffer);
}
writer.WriteZeros((int)(Utils.AlignUp(length, ModuleWriterBase.DEFAULT_WIN32_RESOURCES_ALIGNMENT) - length));
}
uint WriteTo(BinaryWriter writer, ResourceDirectory dir) {
writer.Write(dir.Characteristics);
writer.Write(dir.TimeDateStamp);
writer.Write(dir.MajorVersion);
writer.Write(dir.MinorVersion);
List<ResourceDirectoryEntry> named;
List<ResourceDirectoryEntry> ids;
GetNamedAndIds(dir, out named, out ids);
if (named.Count > ushort.MaxValue || ids.Count > ushort.MaxValue)
throw new ModuleWriterException("Too many named/id Win32 resource entries");
writer.Write((ushort)named.Count);
writer.Write((ushort)ids.Count);
// These must be sorted in ascending order. Names are case insensitive.
named.Sort((a, b) => a.Name.Name.ToUpperInvariant().CompareTo(b.Name.Name.ToUpperInvariant()));
ids.Sort((a, b) => a.Name.Id.CompareTo(b.Name.Id));
foreach (var d in named) {
writer.Write(0x80000000 | stringsDict[d.Name.Name]);
writer.Write(GetDirectoryEntryOffset(d));
}
foreach (var d in ids) {
writer.Write(d.Name.Id);
writer.Write(GetDirectoryEntryOffset(d));
}
return 16 + (uint)(named.Count + ids.Count) * 8;
}
uint GetDirectoryEntryOffset(ResourceDirectoryEntry e) {
if (e is ResourceData)
return dataHeaderDict[(ResourceData)e];
return 0x80000000 | dirDict[(ResourceDirectory)e];
}
static void GetNamedAndIds(ResourceDirectory dir, out List<ResourceDirectoryEntry> named, out List<ResourceDirectoryEntry> ids) {
named = new List<ResourceDirectoryEntry>();
ids = new List<ResourceDirectoryEntry>();
foreach (var d in dir.Directories) {
if (d.Name.HasId)
ids.Add(d);
else
named.Add(d);
}
foreach (var d in dir.Data) {
if (d.Name.HasId)
ids.Add(d);
else
named.Add(d);
}
}
uint WriteTo(BinaryWriter writer, ResourceData dataHeader) {
writer.Write((uint)rva + dataDict[dataHeader.Data]);
writer.Write((uint)dataHeader.Data.Length);
writer.Write(dataHeader.CodePage);
writer.Write(dataHeader.Reserved);
return 16;
}
}
}
| telerik/justdecompile-plugins | De4dot.JustDecompile/De4dot/sources/dnlib/src/DotNet/Writer/Win32ResourcesChunk.cs | C# | gpl-3.0 | 19,496 |
<?php
/**
* @package XG Project
* @copyright Copyright (c) 2008 - 2014
* @license http://opensource.org/licenses/gpl-3.0.html GPL-3.0
* @since Version 2.10.0
*/
define('INSIDE' , TRUE);
define('INSTALL' , FALSE);
define('IN_ADMIN', TRUE);
define('XGP_ROOT', './../');
include(XGP_ROOT . 'global.php');
include('AdminFunctions/Autorization.php');
if ($Observation != 1) die();
$parse = $lang;
$query = doquery("SELECT * FROM {{table}} WHERE `planet_type` = '3'", "planets");
$i = 0;
while ($u = mysql_fetch_array($query))
{
$parse['moon'] .= "<tr>"
. "<th>" . $u[0] . "</th>"
. "<th>" . $u[1] . "</th>"
. "<th>" . $u[2] . "</th>"
. "<th>" . $u[4] . "</th>"
. "<th>" . $u[5] . "</th>"
. "<th>" . $u[6] . "</th>"
. "</tr>";
$i++;
}
if ($i == "1")
$parse['moon'] .= "<tr><th class=b colspan=6>".$lang['mt_only_one_moon']."</th></tr>";
else
$parse['moon'] .= "<tr><th class=b colspan=6>". $lang['mt_there_are'] . $i . $lang['mt_moons'] ."</th></tr>";
display(parsetemplate(gettemplate('adm/MoonListBody'), $parse), FALSE, '', TRUE, FALSE);
?> | XG-Project/XG-Project-v2 | adm/MoonListPage.php | PHP | gpl-3.0 | 1,130 |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.neatmonster.nocheatplus.components.registry.event;
/**
* Allow to unregister listeners, should also disable internally created handles
* if they are this listener. Rather an internal interface.
*
* @author asofold
*
*/
public interface IUnregisterGenericInstanceRegistryListener {
public <T> void unregisterGenericInstanceRegistryListener(Class<T> registeredFor, IGenericInstanceRegistryListener<T> listener);
}
| NoCheatPlus/NoCheatPlus | NCPCore/src/main/java/fr/neatmonster/nocheatplus/components/registry/event/IUnregisterGenericInstanceRegistryListener.java | Java | gpl-3.0 | 1,108 |
package p09_CollectionHierarchy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<String> collection = Arrays.stream(reader.readLine().split("\\s+"))
.collect(Collectors.toList());
AddRemoveCollection<String> addRemoveCollection = new AddRemoveCollectionImpl<>();
AddCollection<String> addCollection = new AddCollectionImpl<>();
MyList<String> myList = new MyListImpl<>();
int count = Integer.parseInt(reader.readLine());
StringBuilder addToAddCollection = new StringBuilder();
StringBuilder addToAddRemoveCollection = new StringBuilder();
StringBuilder addToMyList = new StringBuilder();
StringBuilder removeFromAddRemoveCollection = new StringBuilder();
StringBuilder removeFromMyList = new StringBuilder();
for (String element : collection) {
addToAddCollection.append(addCollection.add(element)).append(" ");
addToAddRemoveCollection.append(addRemoveCollection.add(element)).append(" ");
addToMyList.append(myList.add(element)).append(" ");
}
for (int i = 0; i < count; i++) {
removeFromAddRemoveCollection.append(addRemoveCollection.remove()).append(" ");
removeFromMyList.append(myList.remove()).append(" ");
}
System.out.println(addToAddCollection);
System.out.println(addToAddRemoveCollection);
System.out.println(addToMyList);
System.out.println(removeFromAddRemoveCollection);
System.out.println(removeFromMyList);
}
}
| kostovhg/SoftUni | Java Fundamentals-Sep17/Java_OOP_Advanced/t01_InterfacesAndAbstraction_E/src/p09_CollectionHierarchy/Main.java | Java | gpl-3.0 | 1,874 |
// Copyright 2009-2014 Josh Close and Contributors
// This file is a part of CsvHelper and is licensed under the MS-PL
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html
// http://csvhelper.com
using System;
using System.Collections.Generic;
using System.Linq;
namespace CsvHelper.Configuration
{
/// <summary>
/// Collection that holds CsvClassMaps for record types.
/// </summary>
public class CsvClassMapCollection
{
private readonly Dictionary<Type, CsvClassMap> data = new Dictionary<Type, CsvClassMap>();
/// <summary>
/// Gets the <see cref="CsvClassMap"/> for the specified record type.
/// </summary>
/// <value>
/// The <see cref="CsvClassMap"/>.
/// </value>
/// <param name="type">The record type.</param>
/// <returns>The <see cref="CsvClassMap"/> for the specified record type.</returns>
public virtual CsvClassMap this[Type type]
{
get
{
CsvClassMap map;
data.TryGetValue( type, out map );
return map;
}
}
/// <summary>
/// Adds the specified map for it's record type. If a map
/// already exists for the record type, the specified
/// map will replace it.
/// </summary>
/// <param name="map">The map.</param>
internal virtual void Add( CsvClassMap map )
{
var type = GetGenericCsvClassMapType( map.GetType() ).GetGenericArguments().First();
if( data.ContainsKey( type ) )
{
data[type] = map;
}
else
{
data.Add( type, map );
}
}
/// <summary>
/// Removes the class map.
/// </summary>
/// <param name="classMapType">The class map type.</param>
internal virtual void Remove( Type classMapType )
{
if( !typeof( CsvClassMap ).IsAssignableFrom( classMapType ) )
{
throw new ArgumentException( "The class map type must inherit from CsvClassMap." );
}
var type = GetGenericCsvClassMapType( classMapType ).GetGenericArguments().First();
data.Remove( type );
}
/// <summary>
/// Removes all maps.
/// </summary>
internal virtual void Clear()
{
data.Clear();
}
/// <summary>
/// Goes up the inheritance tree to find the type instance of CsvClassMap{}.
/// </summary>
/// <param name="type">The type to traverse.</param>
/// <returns>The type that is CsvClassMap{}.</returns>
protected virtual Type GetGenericCsvClassMapType( Type type )
{
if( type.IsGenericType && type.GetGenericTypeDefinition() == typeof( CsvClassMap<> ) )
{
return type;
}
return GetGenericCsvClassMapType( type.BaseType );
}
}
}
| worldexplorer/SquareOne | CsvHelper261-master/src/CsvHelper/Configuration/CsvClassMapCollection.cs | C# | gpl-3.0 | 2,628 |
/*
* AutoSIM - Internet of Things Simulator
* Copyright (C) 2014, Aditya Yadav <aditya@automatski.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.automatski.autosim.environments.utils;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonUtils {
private static GsonBuilder builder = null;
static {
builder = new GsonBuilder();
builder.setPrettyPrinting().serializeNulls();
}
public static String objectToJson(Object obj) throws Exception {
Gson gson = builder.create();
return gson.toJson(obj);
}
public static Object jsonToObject(String path, Class clas) throws Exception {
Gson gson = builder.create();
String json = new String(Files.readAllBytes(Paths.get(path)));//"./albums.json")));
return gson.fromJson(json, clas);
}
}
| adityayadav76/internet_of_things_simulator | AutoSIM-Environments/src/com/automatski/autosim/environments/utils/GsonUtils.java | Java | gpl-3.0 | 1,519 |
/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "FootpathRemoveAction.h"
#include "../Cheats.h"
#include "../OpenRCT2.h"
#include "../core/MemoryStream.h"
#include "../interface/Window.h"
#include "../localisation/StringIds.h"
#include "../management/Finance.h"
#include "../world/Footpath.h"
#include "../world/Location.hpp"
#include "../world/Park.h"
#include "../world/Wall.h"
#include "BannerRemoveAction.h"
FootpathRemoveAction::FootpathRemoveAction(const CoordsXYZ& location)
: _loc(location)
{
}
void FootpathRemoveAction::AcceptParameters(GameActionParameterVisitor& visitor)
{
visitor.Visit(_loc);
}
uint16_t FootpathRemoveAction::GetActionFlags() const
{
return GameAction::GetActionFlags();
}
void FootpathRemoveAction::Serialise(DataSerialiser& stream)
{
GameAction::Serialise(stream);
stream << DS_TAG(_loc);
}
GameActions::Result::Ptr FootpathRemoveAction::Query() const
{
GameActions::Result::Ptr res = std::make_unique<GameActions::Result>();
res->Cost = 0;
res->Expenditure = ExpenditureType::Landscaping;
res->Position = { _loc.x + 16, _loc.y + 16, _loc.z };
if (!LocationValid(_loc))
{
return MakeResult(GameActions::Status::NotOwned, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_LAND_NOT_OWNED_BY_PARK);
}
if (!((gScreenFlags & SCREEN_FLAGS_SCENARIO_EDITOR) || gCheatsSandboxMode) && !map_is_location_owned(_loc))
{
return MakeResult(GameActions::Status::NotOwned, STR_CANT_REMOVE_FOOTPATH_FROM_HERE, STR_LAND_NOT_OWNED_BY_PARK);
}
TileElement* footpathElement = GetFootpathElement();
if (footpathElement == nullptr)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE);
}
res->Cost = GetRefundPrice(footpathElement);
return res;
}
GameActions::Result::Ptr FootpathRemoveAction::Execute() const
{
GameActions::Result::Ptr res = std::make_unique<GameActions::Result>();
res->Cost = 0;
res->Expenditure = ExpenditureType::Landscaping;
res->Position = { _loc.x + 16, _loc.y + 16, _loc.z };
if (!(GetFlags() & GAME_COMMAND_FLAG_GHOST))
{
footpath_interrupt_peeps(_loc);
footpath_remove_litter(_loc);
}
TileElement* footpathElement = GetFootpathElement();
if (footpathElement != nullptr)
{
footpath_queue_chain_reset();
auto bannerRes = RemoveBannersAtElement(_loc, footpathElement);
if (bannerRes->Error == GameActions::Status::Ok)
{
res->Cost += bannerRes->Cost;
}
footpath_remove_edges_at(_loc, footpathElement);
map_invalidate_tile_full(_loc);
tile_element_remove(footpathElement);
footpath_update_queue_chains();
// Remove the spawn point (if there is one in the current tile)
gPeepSpawns.erase(
std::remove_if(
gPeepSpawns.begin(), gPeepSpawns.end(),
[this](const CoordsXYZ& spawn) {
{
return spawn.ToTileStart() == _loc.ToTileStart();
}
}),
gPeepSpawns.end());
}
else
{
return MakeResult(GameActions::Status::InvalidParameters, STR_CANT_REMOVE_FOOTPATH_FROM_HERE);
}
res->Cost += GetRefundPrice(footpathElement);
return res;
}
TileElement* FootpathRemoveAction::GetFootpathElement() const
{
bool getGhostPath = GetFlags() & GAME_COMMAND_FLAG_GHOST;
TileElement* tileElement = map_get_footpath_element(_loc);
TileElement* footpathElement = nullptr;
if (tileElement != nullptr)
{
if (getGhostPath && !tileElement->IsGhost())
{
while (!(tileElement++)->IsLastForTile())
{
if (tileElement->GetType() != TILE_ELEMENT_TYPE_PATH && !tileElement->IsGhost())
{
continue;
}
footpathElement = tileElement;
break;
}
}
else
{
footpathElement = tileElement;
}
}
return footpathElement;
}
money32 FootpathRemoveAction::GetRefundPrice(TileElement* footpathElement) const
{
money32 cost = -MONEY(10, 00);
return cost;
}
/**
*
* rct2: 0x006BA23E
*/
GameActions::Result::Ptr FootpathRemoveAction::RemoveBannersAtElement(const CoordsXY& loc, TileElement* tileElement) const
{
auto result = MakeResult();
while (!(tileElement++)->IsLastForTile())
{
if (tileElement->GetType() == TILE_ELEMENT_TYPE_PATH)
return result;
if (tileElement->GetType() != TILE_ELEMENT_TYPE_BANNER)
continue;
auto bannerRemoveAction = BannerRemoveAction({ loc, tileElement->GetBaseZ(), tileElement->AsBanner()->GetPosition() });
bool isGhost = tileElement->IsGhost();
auto bannerFlags = GetFlags() | (isGhost ? static_cast<uint32_t>(GAME_COMMAND_FLAG_GHOST) : 0);
bannerRemoveAction.SetFlags(bannerFlags);
auto res = GameActions::ExecuteNested(&bannerRemoveAction);
// Ghost removal is free
if (res->Error == GameActions::Status::Ok && !isGhost)
{
result->Cost += res->Cost;
}
tileElement--;
}
return result;
}
| LRFLEW/OpenRCT2 | src/openrct2/actions/FootpathRemoveAction.cpp | C++ | gpl-3.0 | 5,661 |
<?php
/* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005 Eric Seigne <eric.seigne@ryxeo.com>
* Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
* Copyright (C) 2014 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2014-2016 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2014-2015 Philippe Grand <philippe.grand@atoo-net.com>
* Copyright (C) 2014 Ion agorria <ion@agorria.com>
* Copyright (C) 2015 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
* Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/product/price.php
* \ingroup product
* \brief Page to show product prices
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_expression.class.php';
require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
$prodcustprice = new Productcustomerprice($db);
}
$langs->load("products");
$langs->load("bills");
$langs->load("companies");
$mesg=''; $error=0; $errors=array();
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'alpha');
$cancel = GETPOST('cancel', 'alpha');
$eid = GETPOST('eid', 'int');
$search_soc = GETPOST('search_soc');
// Security check
$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));
$fieldtype = (! empty($ref) ? 'ref' : 'rowid');
if ($user->societe_id) $socid = $user->societe_id;
$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
if ($id > 0 || ! empty($ref))
{
$object = new Product($db);
$object->fetch($id, $ref);
}
// Clean param
if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) $conf->global->PRODUIT_MULTIPRICES_LIMIT = 5;
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
$hookmanager->initHooks(array('productpricecard','globalcard'));
/*
* Actions
*/
if ($cancel) $action='';
$parameters=array('id'=>$id, 'ref'=>$ref);
$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers
{
$search_soc = '';
}
if ($action == 'setlabelsellingprice' && $user->admin)
{
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
$keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel');
dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice','alpha'), 'chaine', 0, '', $conf->entity);
$action = '';
}
if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer))
{
$tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)'
// We must define tva_tx, npr and local taxes
$vatratecode = '';
$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
// If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes
if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
{
// We look into database using code
$vatratecode=$reg[1];
// Get record from code
$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'";
$sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
$sql.= " AND t.code ='".$vatratecode."'";
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$npr = $obj->recuperableonly;
$localtax1 = $obj->localtax1;
$localtax2 = $obj->localtax2;
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
}
}
$object->default_vat_code = $vatratecode;
$object->tva_tx = $tva_tx;
$object->tva_npr = $npr;
$object->localtax1_tx = $localtax1;
$object->localtax2_tx = $localtax2;
$object->localtax1_type = $localtax1_type;
$object->localtax2_type = $localtax2_type;
$db->begin();
$resql = $object->update($object->id, $user);
if (! $resql)
{
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
if ($error)
{
//$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2);
$localtaxarray=array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them.
$object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode);
}
if (! $error)
{
$db->commit();
}
else
{
$db->rollback();
}
$action='';
}
if (($action == 'update_price') && !$cancel && $object->getRights()->creer)
{
$error = 0;
$pricestoupdate = array();
$psq = GETPOST('psqflag');
$psq = empty($newpsq) ? 0 : $newpsq;
$maxpricesupplier = $object->min_recommended_price();
if (!empty($conf->dynamicprices->enabled)) {
$object->fk_price_expression = empty($eid) ? 0 : $eid; //0 discards expression
if ($object->fk_price_expression != 0) {
//Check the expression validity by parsing it
$priceparser = new PriceParser($db);
if ($priceparser->parseProduct($object) < 0) {
$error ++;
setEventMessages($priceparser->translatedError(), null, 'errors');
}
}
}
// Multiprices
if (! $error && ! empty($conf->global->PRODUIT_MULTIPRICES)) {
$newprice = GETPOST('price', 'array');
$newprice_min = GETPOST('price_min', 'array');
$newpricebase = GETPOST('multiprices_base_type', 'array');
$newvattx = GETPOST('tva_tx', 'array');
$newvatnpr = GETPOST('tva_npr', 'array');
$newlocaltax1_tx = GETPOST('localtax1_tx', 'array');
$newlocaltax1_type = GETPOST('localtax1_type', 'array');
$newlocaltax2_tx = GETPOST('localtax2_tx', 'array');
$newlocaltax2_type = GETPOST('localtax2_type', 'array');
//Shall we generate prices using price rules?
$object->price_autogen = GETPOST('usePriceRules') == 'on';
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i ++)
{
if (!isset($newprice[$i])) {
continue;
}
$tva_tx_txt = $newvattx[$i];
$vatratecode = '';
$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
$localtax1 = $newlocaltax1_tx[$i];
$localtax1_type = $newlocaltax1_type[$i];
$localtax2 = $newlocaltax2_tx[$i];
$localtax2_type = $newlocaltax2_type[$i];
if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
{
// We look into database using code
$vatratecode=$reg[1];
// Get record from code
$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'";
$sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
$sql.= " AND t.code ='".$vatratecode."'";
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$npr = $obj->recuperableonly;
$localtax1 = $obj->localtax1;
$localtax2 = $obj->localtax2;
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
}
}
$pricestoupdate[$i] = array(
'price' => $newprice[$i],
'price_min' => $newprice_min[$i],
'price_base_type' => $newpricebase[$i],
'default_vat_code' => $vatratecode,
'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future
'npr' => $npr, // default_vat_code should be used in priority in a future
'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future
);
//If autogeneration is enabled, then we only set the first level
if ($object->price_autogen) {
break;
}
}
}
elseif (! $error)
{
$tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)'
$vatratecode = '';
// We must define tva_tx, npr and local taxes
$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
// If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes
if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
{
// We look into database using code
$vatratecode=$reg[1];
// Get record from code
$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'";
$sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
$sql.= " AND t.code ='".$vatratecode."'";
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$npr = $obj->recuperableonly;
$localtax1 = $obj->localtax1;
$localtax2 = $obj->localtax2;
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
// If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule
if (in_array($mysoc->country_code, array('ES')))
{
$localtax1 = get_localtax($tva_tx,1);
$localtax2 = get_localtax($tva_tx,2);
}
}
}
$pricestoupdate[0] = array(
'price' => $_POST["price"],
'price_min' => $_POST["price_min"],
'price_base_type' => $_POST["price_base_type"],
'default_vat_code' => $vatratecode,
'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future
'npr' => $npr, // default_vat_code should be used in priority in a future
'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future
);
}
if (!$error) {
$db->begin();
foreach ($pricestoupdate as $key => $val) {
$newprice = $val['price'];
if ($val['price'] < $val['price_min'] && !empty($object->fk_price_expression)) {
$newprice = $val['price_min']; //Set price same as min, the user will not see the
}
$newprice = price2num($newprice, 'MU');
$newprice_min = price2num($val['price_min'], 'MU');
if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $newprice_min < $maxpricesupplier) {
setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, - 1, - 1, 'auto')), null, 'errors');
$error ++;
break;
}
$res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']);
if ($res < 0) {
$error ++;
setEventMessages($object->error, $object->errors, 'errors');
break;
}
}
}
if (!$error && $object->update($object->id, $user) < 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
if (empty($error)) {
$action = '';
setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
$db->commit();
} else {
$action = 'edit_price';
$db->rollback();
}
}
if ($action == 'delete' && $user->rights->produit->supprimer)
{
$result = $object->log_price_delete($user, $_GET ["lineid"]);
if ($result < 0) {
setEventMessages($object->error, $object->errors, 'errors');
}
}
/**
* ***************************************************
* Price by quantity
* ***************************************************
*/
if ($action == 'activate_price_by_qty') { // Activating product price by quantity add a new price, specified as by quantity
$level = GETPOST('level');
$object->updatePrice(0, $object->price_base_type, $user, $object->tva_tx, 0, $level, $object->tva_npr, 1);
}
if ($action == 'edit_price_by_qty')
{ // Edition d'un prix par quantité
$rowid = GETPOST('rowid');
}
if ($action == 'update_price_by_qty')
{ // Ajout / Mise à jour d'un prix par quantité
// Récupération des variables
$rowid = GETPOST('rowid');
$priceid = GETPOST('priceid');
$newprice = price2num(GETPOST("price"), 'MU');
// $newminprice=price2num(GETPOST("price_min"),'MU'); // TODO : Add min price management
$quantity = GETPOST('quantity');
$remise_percent = price2num(GETPOST('remise_percent'));
$remise = 0; // TODO : allow discount by amount when available on documents
if (empty($quantity)) {
$error ++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Qty")), null, 'errors');
}
if (empty($newprice)) {
$error ++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Price")), null, 'errors');
}
if (! $error) {
// Calcul du prix HT et du prix unitaire
if ($object->price_base_type == 'TTC') {
$price = price2num($newprice) / (1 + ($object->tva_tx / 100));
}
$price = price2num($newprice, 'MU');
$unitPrice = price2num($price / $quantity, 'MU');
// Ajout / mise à jour
if ($rowid > 0) {
$sql = "UPDATE " . MAIN_DB_PREFIX . "product_price_by_qty SET";
$sql .= " price='" . $price . "',";
$sql .= " unitprice=" . $unitPrice . ",";
$sql .= " quantity=" . $quantity . ",";
$sql .= " remise_percent=" . $remise_percent . ",";
$sql .= " remise=" . $remise;
$sql .= " WHERE rowid = " . GETPOST('rowid');
$result = $db->query($sql);
} else {
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_price_by_qty (fk_product_price,price,unitprice,quantity,remise_percent,remise) values (";
$sql .= $priceid . ',' . $price . ',' . $unitPrice . ',' . $quantity . ',' . $remise_percent . ',' . $remise . ')';
$result = $db->query($sql);
}
}
}
if ($action == 'delete_price_by_qty')
{
$rowid = GETPOST('rowid');
$sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_price_by_qty";
$sql .= " WHERE rowid = " . GETPOST('rowid');
$result = $db->query($sql);
}
if ($action == 'delete_all_price_by_qty')
{
$priceid = GETPOST('priceid');
$sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_price_by_qty";
$sql .= " WHERE fk_product_price = " . $priceid;
$result = $db->query($sql);
}
/**
* ***************************************************
* Price by customer
* ****************************************************
*/
if ($action == 'add_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) {
$maxpricesupplier = $object->min_recommended_price();
$update_child_soc = GETPOST('updatechildprice');
// add price by customer
$prodcustprice->fk_soc = GETPOST('socid', 'int');
$prodcustprice->fk_product = $object->id;
$prodcustprice->price = price2num(GETPOST("price"), 'MU');
$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
$tva_tx_txt = GETPOST("tva_tx");
$vatratecode = '';
// We must define tva_tx, npr and local taxes
$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
// If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes
if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
{
// We look into database using code
$vatratecode=$reg[1];
// Get record from code
$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'";
$sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
$sql.= " AND t.code ='".$vatratecode."'";
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$npr = $obj->recuperableonly;
$localtax1 = $obj->localtax1;
$localtax2 = $obj->localtax2;
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
}
}
$prodcustprice->default_vat_code = $vatratecode;
$prodcustprice->tva_tx = $tva_tx;
$prodcustprice->recuperableonly = $npr;
$prodcustprice->localtax1_tx = $localtax1;
$prodcustprice->localtax2_tx = $localtax2;
$prodcustprice->localtax1_type = $localtax1_type;
$prodcustprice->localtax2_type = $localtax2_type;
if (! ($prodcustprice->fk_soc > 0))
{
$langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
$error++;
$action='add_customer_price';
}
if (! empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier)
{
$langs->load("errors");
setEventMessages($langs->trans("MinimumPriceLimit",price($maxpricesupplier,0,'',1,-1,-1,'auto')), null, 'errors');
$error++;
$action='add_customer_price';
}
if (! $error)
{
$result = $prodcustprice->create($user, 0, $update_child_soc);
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
} else {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
}
$action = '';
}
}
if ($action == 'delete_customer_price' && ($user->rights->produit->supprimer || $user->rights->service->supprimer))
{
// Delete price by customer
$prodcustprice->id = GETPOST('lineid');
$result = $prodcustprice->delete($user);
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
} else {
setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
}
$action = '';
}
if ($action == 'update_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer))
{
$maxpricesupplier = $object->min_recommended_price();
$update_child_soc = GETPOST('updatechildprice');
$prodcustprice->fetch(GETPOST('lineid', 'int'));
// update price by customer
$prodcustprice->price = price2num(GETPOST("price"), 'MU');
$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
$tva_tx_txt = GETPOST("tva_tx");
$vatratecode='';
// We must define tva_tx, npr and local taxes
$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
// If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes
if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
{
// We look into database using code
$vatratecode=$reg[1];
// Get record from code
$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$mysoc->country_code."'";
$sql.= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
$sql.= " AND t.code ='".$vatratecode."'";
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$npr = $obj->recuperableonly;
$localtax1 = $obj->localtax1;
$localtax2 = $obj->localtax2;
$localtax1_type = $obj->localtax1_type;
$localtax2_type = $obj->localtax2_type;
}
}
$prodcustprice->default_vat_code = $vatratecode;
$prodcustprice->tva_tx = $tva_tx;
$prodcustprice->recuperableonly = $npr;
$prodcustprice->localtax1_tx = $localtax1;
$prodcustprice->localtax2_tx = $localtax2;
$prodcustprice->localtax1_type = $localtax1_type;
$prodcustprice->localtax2_type = $localtax2_type;
if ($prodcustprice->price_min < $maxpricesupplier && !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE))
{
setEventMessages($langs->trans("MinimumPriceLimit",price($maxpricesupplier,0,'',1,-1,-1,'auto')), null, 'errors');
$error++;
$action='update_customer_price';
}
if ( ! $error)
{
$result = $prodcustprice->update($user, 0, $update_child_soc);
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
} else {
setEventMessages($langs->trans('Save'), null, 'mesgs');
}
$action = '';
}
}
}
/*
* View
*/
$form = new Form($db);
if (! empty($id) || ! empty($ref))
{
// fetch updated prices
$object->fetch($id, $ref);
}
$title = $langs->trans('ProductServiceCard');
$helpurl = '';
$shortlabel = dol_trunc($object->label,16);
if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT))
{
$title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('SellingPrices');
$helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos';
}
if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE))
{
$title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('SellingPrices');
$helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios';
}
llxHeader('', $title, $helpurl);
$head = product_prepare_head($object);
$titre = $langs->trans("CardProduct" . $object->type);
$picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
dol_fiche_head($head, 'price', $titre, 0, $picto);
$linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php">'.$langs->trans("BackToList").'</a>';
dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref');
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield" width="100%">';
// MultiPrix
if (! empty($conf->global->PRODUIT_MULTIPRICES))
{
// Price and min price are variable (depends on level of company).
if (! empty($socid))
{
$soc = new Societe($db);
$soc->id = $socid;
$soc->fetch($socid);
// Selling price
print '<tr><td class="titlefield">';
print $langs->trans("SellingPrice");
print '</td>';
print '<td colspan="2">';
if ($object->multiprices_base_type[$soc->price_level] == 'TTC') {
print price($object->multiprices_ttc[$soc->price_level]);
} else {
print price($object->multiprices[$soc->price_level]);
}
if ($object->multiprices_base_type[$soc->price_level]) {
print ' ' . $langs->trans($object->multiprices_base_type[$soc->price_level]);
} else {
print ' ' . $langs->trans($object->price_base_type);
}
print '</td></tr>';
// Price min
print '<tr><td>' . $langs->trans("MinPrice") . '</td><td colspan="2">';
if ($object->multiprices_base_type[$soc->price_level] == 'TTC')
{
print price($object->multiprices_min_ttc[$soc->price_level]) . ' ' . $langs->trans($object->multiprices_base_type[$soc->price_level]);
} else {
print price($object->multiprices_min[$soc->price_level]) . ' ' . $langs->trans(empty($object->multiprices_base_type[$soc->price_level])?'HT':$object->multiprices_base_type[$soc->price_level]);
}
print '</td></tr>';
if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
{
// TVA
print '<tr><td>' . $langs->trans("VATRate") . '</td><td colspan="2">' . vatrate($object->multiprices_tva_tx[$soc->price_level], true) . '</td></tr>';
}
else
{
// TVA
print '<tr><td>' . $langs->trans("VATRate") . '</td><td>';
if ($object->default_vat_code)
{
print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
}
else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);
print '</td></tr>';
}
}
else
{
if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility
{
// We show only vat for level 1
print '<tr><td class="titlefield">' . $langs->trans("VATRate") . '</td>';
print '<td colspan="2">' . vatrate($object->multiprices_tva_tx[1], true) . '</td>';
print '</tr>';
}
else
{
// TVA
print '<tr><td class="titlefield">' . $langs->trans("VATRate") . '</td><td>';
if ($object->default_vat_code)
{
print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
}
else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);
print '</td></tr>';
}
print '</table>';
print '<br>';
print '<table class="noborder tableforfield" width="100%">';
print '<tr class="liste_titre"><td>';
print $langs->trans("PriceLevel");
if ($user->admin) print ' <a href="'.$_SERVER["PHP_SELF"].'?action=editlabelsellingprice&pricelevel='.$i.'&id='.$object->id.'">'.img_edit($langs->trans('EditSellingPriceLabel'),0).'</a>';
print '</td>';
print '<td style="text-align: right">'.$langs->trans("SellingPrice").'</td>';
print '<td style="text-align: right">'.$langs->trans("MinPrice").'</td>';
print '</tr>';
$var=True;
for($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++)
{
$var = ! $var;
print '<tr '.$bc[$var].'>';
// Label of price
print '<td>';
$keyforlabel='PRODUIT_MULTIPRICES_LABEL'.$i;
if (preg_match('/editlabelsellingprice/', $action))
{
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="setlabelsellingprice">';
print '<input type="hidden" name="pricelevel" value="'.$i.'">';
print $langs->trans("SellingPrice") . ' ' . $i.' - ';
print '<input size="10" class="maxwidthonsmartphone" type="text" name="labelsellingprice" value="'.$conf->global->$keyforlabel.'">';
print ' <input type="submit" class="button" value="'.$langs->trans("Modify").'">';
print '</form>';
}
else
{
print $langs->trans("SellingPrice") . ' ' . $i;
if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel);
}
print '</td>';
if ($object->multiprices_base_type [$i] == 'TTC') {
print '<td style="text-align: right">' . price($object->multiprices_ttc[$i]);
} else {
print '<td style="text-align: right">' . price($object->multiprices[$i]);
}
if ($object->multiprices_base_type[$i]) {
print ' '.$langs->trans($object->multiprices_base_type [$i]).'</td>';
} else {
print ' '.$langs->trans($object->price_base_type).'</td>';
}
// Prix min
print '<td style="text-align: right">';
if (empty($object->multiprices_base_type[$i])) $object->multiprices_base_type[$i]="HT";
if ($object->multiprices_base_type[$i] == 'TTC')
{
print price($object->multiprices_min_ttc[$i]) . ' ' . $langs->trans($object->multiprices_base_type[$i]);
}
else
{
print price($object->multiprices_min[$i]) . ' ' . $langs->trans($object->multiprices_base_type[$i]);
}
print '</td></tr>';
// Price by quantity
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) // TODO Fix the form included into a tr instead of a td
{
print '<tr><td>' . $langs->trans("PriceByQuantity") . ' ' . $i;
print '</td><td>';
if ($object->prices_by_qty[$i] == 1) {
print '<table width="50%" class="border" summary="List of quantities">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("PriceByQuantityRange") . ' ' . $i . '</td>';
print '<td align="right">' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("UnitPrice") . '</td>';
print '<td align="right">' . $langs->trans("Discount") . '</td>';
print '<td> </td>';
print '</tr>';
foreach ($object->prices_by_qty_list[$i] as $ii => $prices)
{
if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer)) {
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="action" value="update_price_by_qty">';
print '<input type="hidden" name="priceid" value="' . $object->prices_by_qty_id[$i] . '">';
print '<input type="hidden" value="' . $prices['rowid'] . '" name="rowid">';
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td><input size="5" type="text" value="' . $prices['quantity'] . '" name="quantity"></td>';
print '<td align="right" colspan="2"><input size="10" type="text" value="' . price2num($prices['price'], 'MU') . '" name="price"> ' . $object->price_base_type . '</td>';
// print '<td align="right"> </td>';
print '<td align="right"><input size="5" type="text" value="' . $prices['remise_percent'] . '" name="remise_percent"> %</td>';
print '<td align="center"><input type="submit" value="' . $langs->trans("Modify") . '" class="button"></td>';
print '</tr>';
print '</form>';
} else {
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td>' . $prices['quantity'] . '</td>';
print '<td align="right">' . price($prices['price']) . '</td>';
print '<td align="right">' . price($prices['unitprice']) . '</td>';
print '<td align="right">' . price($prices['remise_percent']) . ' %</td>';
print '<td align="center">';
if (($user->rights->produit->creer || $user->rights->service->creer)) {
print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit_price_by_qty&rowid=' . $prices["rowid"] . '">';
print img_edit() . '</a>';
print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=delete_price_by_qty&rowid=' . $prices["rowid"] . '">';
print img_delete() . '</a>';
} else {
print ' ';
}
print '</td>';
print '</tr>';
}
}
if ($action != 'edit_price_by_qty' && ($user->rights->produit->creer || $user->rights->service->creer)) {
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="action" value="update_price_by_qty">';
print '<input type="hidden" name="priceid" value="' . $object->prices_by_qty_id[$i] . '">';
print '<input type="hidden" value="0" name="rowid">';
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td><input size="5" type="text" value="1" name="quantity"></td>';
print '<td align="right" colspan="2"><input size="10" type="text" value="0" name="price"> ' . $object->price_base_type . '</td>';
// print '<td align="right"> </td>';
print '<td align="right"><input size="5" type="text" value="0" name="remise_percent"> %</td>';
print '<td align="center"><input type="submit" value="' . $langs->trans("Add") . '" class="button"></td>';
print '</tr>';
print '</form>';
}
print '</table>';
} else {
print $langs->trans("No");
print ' <a href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=activate_price_by_qty&level=' . $i . '">(' . $langs->trans("Activate") . ')</a>';
}
print '</td></tr>';
}
}
}
}
else
{
// TVA
print '<tr><td class="titlefield">' . $langs->trans("VATRate") . '</td><td>';
if ($object->default_vat_code)
{
print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
}
else print vatrate($object->tva_tx, true, $object->tva_npr, true);
print '</td></tr>';
// Price
print '<tr><td>' . $langs->trans("SellingPrice") . '</td><td>';
if ($object->price_base_type == 'TTC') {
print price($object->price_ttc) . ' ' . $langs->trans($object->price_base_type);
} else {
print price($object->price) . ' ' . $langs->trans($object->price_base_type);
}
print '</td></tr>';
// Price minimum
print '<tr><td>' . $langs->trans("MinPrice") . '</td><td>';
if ($object->price_base_type == 'TTC') {
print price($object->price_min_ttc) . ' ' . $langs->trans($object->price_base_type);
} else {
print price($object->price_min) . ' ' . $langs->trans($object->price_base_type);
}
print '</td></tr>';
// Price by quantity
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) // TODO Fix the form inside tr instead of td
{
print '<tr><td>' . $langs->trans("PriceByQuantity");
if ($object->prices_by_qty [0] == 0) {
print ' <a href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=activate_price_by_qty&level=1">' . $langs->trans("Activate");
}
print '</td><td>';
if ($object->prices_by_qty [0] == 1) {
print '<table width="50%" class="border" summary="List of quantities">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("PriceByQuantityRange") . '</td>';
print '<td align="right">' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("UnitPrice") . '</td>';
print '<td align="right">' . $langs->trans("Discount") . '</td>';
print '<td> </td>';
print '</tr>';
foreach ($object->prices_by_qty_list [0] as $ii => $prices)
{
if ($action == 'edit_price_by_qty' && $rowid == $prices['rowid'] && ($user->rights->produit->creer || $user->rights->service->creer))
{
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="action" value="update_price_by_qty">';
print '<input type="hidden" name="priceid" value="' . $object->prices_by_qty_id[0] . '">';
print '<input type="hidden" value="' . $prices['rowid'] . '" name="rowid">';
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td><input size="5" type="text" value="' . $prices['quantity'] . '" name="quantity"></td>';
print '<td align="right" colspan="2"><input size="10" type="text" value="' . price2num($prices['price'], 'MU') . '" name="price"> ' . $object->price_base_type . '</td>';
// print '<td align="right"> </td>';
print '<td align="right"><input size="5" type="text" value="' . $prices['remise_percent'] . '" name="remise_percent"> %</td>';
print '<td align="center"><input type="submit" value="' . $langs->trans("Modify") . '" class="button"></td>';
print '</tr>';
print '</form>';
} else {
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td>' . $prices['quantity'] . '</td>';
print '<td align="right">' . price($prices['price']) . '</td>';
print '<td align="right">' . price($prices['unitprice']) . '</td>';
print '<td align="right">' . price($prices['remise_percent']) . ' %</td>';
print '<td align="center">';
if (($user->rights->produit->creer || $user->rights->service->creer)) {
print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit_price_by_qty&rowid=' . $prices["rowid"] . '">';
print img_edit() . '</a>';
print '<a href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=delete_price_by_qty&rowid=' . $prices["rowid"] . '">';
print img_delete() . '</a>';
} else {
print ' ';
}
print '</td>';
print '</tr>';
}
}
if ($action != 'edit_price_by_qty') {
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">'; // FIXME a form into a table is not allowed
print '<input type="hidden" name="action" value="update_price_by_qty">';
print '<input type="hidden" name="priceid" value="' . $object->prices_by_qty_id [0] . '">';
print '<input type="hidden" value="0" name="rowid">';
print '<tr class="' . ($ii % 2 == 0 ? 'pair' : 'impair') . '">';
print '<td><input size="5" type="text" value="1" name="quantity"></td>';
print '<td align="right" colspan="2"><input size="10" type="text" value="0" name="price"> ' . $object->price_base_type . '</td>';
// print '<td align="right"> </td>';
print '<td align="right"><input size="5" type="text" value="0" name="remise_percent"> %</td>';
print '<td align="center"><input type="submit" value="' . $langs->trans("Add") . '" class="button"></td>';
print '</tr>';
print '</form>';
}
print '</table>';
} else {
print $langs->trans("No");
}
print '</td></tr>';
}
}
print "</table>\n";
print '</div>';
print '<div style="clear:both"></div>';
dol_fiche_end();
/* ************************************************************************** */
/* */
/* Barre d'action */
/* */
/* ************************************************************************** */
if (! $action || $action == 'delete' || $action == 'showlog_customer_price' || $action == 'showlog_default_price' || $action == 'add_customer_price')
{
print "\n" . '<div class="tabsAction">' . "\n";
if (empty($conf->global->PRODUIT_MULTIPRICES))
{
if ($user->rights->produit->creer || $user->rights->service->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=edit_price&id=' . $object->id . '">' . $langs->trans("UpdateDefaultPrice") . '</a></div>';
}
}
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
{
if ($user->rights->produit->creer || $user->rights->service->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?action=add_customer_price&id=' . $object->id . '">' . $langs->trans("AddCustomerPrice") . '</a></div>';
}
}
if (! empty($conf->global->PRODUIT_MULTIPRICES))
{
if ($user->rights->produit->creer || $user->rights->service->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=edit_vat&id=' . $object->id . '">' . $langs->trans("UpdateVAT") . '</a></div>';
}
if ($user->rights->produit->creer || $user->rights->service->creer) {
print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?action=edit_price&id=' . $object->id . '">' . $langs->trans("UpdateLevelPrices") . '</a></div>';
}
}
print "\n</div>\n";
}
/*
* Edit price area
*/
if ($action == 'edit_vat' && ($user->rights->produit->creer || $user->rights->service->creer))
{
print load_fiche_titre($langs->trans("UpdateVAT"), '');
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
print '<input type="hidden" name="action" value="update_vat">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
dol_fiche_head('');
print '<table class="border" width="100%">';
// VAT
print '<tr><td>' . $langs->trans("VATRate") . '</td><td>';
print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1);
print '</td></tr>';
print '</table>';
dol_fiche_end();
print '<div class="center">';
print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</div>';
print '<br></form><br>';
}
if ($action == 'edit_price' && $object->getRights()->creer)
{
print load_fiche_titre($langs->trans("NewPrice"), '');
if (empty($conf->global->PRODUIT_MULTIPRICES))
{
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
print '<input type="hidden" name="action" value="update_price">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
dol_fiche_head('');
print '<table class="border" width="100%">';
// VAT
print '<tr><td>' . $langs->trans("VATRate") . '</td><td colspan="2">';
print $form->load_tva("tva_tx", $object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1);
print '</td></tr>';
// Price base
print '<tr><td width="20%">';
print $langs->trans('PriceBase');
print '</td>';
print '<td colspan="2">';
print $form->selectPriceBaseType($object->price_base_type, "price_base_type");
print '</td>';
print '</tr>';
// Only show price mode and expression selector if module is enabled
if (! empty($conf->dynamicprices->enabled)) {
// Price mode selector
print '<tr><td>'.$langs->trans("PriceMode").'</td><td colspan="2">';
$price_expression = new PriceExpression($db);
$price_expression_list = array(0 => $langs->trans("PriceNumeric")); //Put the numeric mode as first option
foreach ($price_expression->list_price_expression() as $entry) {
$price_expression_list[$entry->id] = $entry->title;
}
$price_expression_preselection = GETPOST('eid') ? GETPOST('eid') : ($object->fk_price_expression ? $object->fk_price_expression : '0');
print $form->selectarray('eid', $price_expression_list, $price_expression_preselection);
print ' <div id="expression_editor" class="button">'.$langs->trans("PriceExpressionEditor").'</div>';
print '</td></tr>';
// This code hides the numeric price input if is not selected, loads the editor page if editor button is pressed
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#expression_editor").click(function() {
window.location = "<?php echo DOL_URL_ROOT ?>/product/dynamic_price/editor.php?id=<?php echo $id ?>&tab=price&eid=" + $("#eid").val();
});
jQuery("#eid").change(on_change);
on_change();
});
function on_change() {
if ($("#eid").val() == 0) {
jQuery("#price_numeric").show();
} else {
jQuery("#price_numeric").hide();
}
}
</script>
<?php
}
// Price
$product = new Product($db);
$product->fetch($id, $ref, '', 1); //Ignore the math expression when getting the price
print '<tr id="price_numeric"><td width="20%">';
$text = $langs->trans('SellingPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td><td colspan="2">';
if ($object->price_base_type == 'TTC') {
print '<input name="price" size="10" value="' . price($product->price_ttc) . '">';
} else {
print '<input name="price" size="10" value="' . price($product->price) . '">';
}
print '</td></tr>';
// Price minimum
print '<tr><td>';
$text = $langs->trans('MinPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td><td';
if (empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
print ' colspan="2"';
}
print '>';
if ($object->price_base_type == 'TTC') {
print '<input name="price_min" size="10" value="' . price($object->price_min_ttc) . '">';
} else {
print '<input name="price_min" size="10" value="' . price($object->price_min) . '">';
}
print '</td>';
if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE))
{
print '<td align="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier,0,'',1,-1,-1,'auto')).' '.img_warning().'</td>';
}
print '</tr>';
print '</table>';
dol_fiche_end();
print '<div class="center">';
print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</div>';
print '<br></form>';
}
else
{
?>
<script>
var showHidePriceRules = function () {
var otherPrices = $('div.fiche form table tbody tr:not(:first)');
var minPrice1 = $('div.fiche form input[name="price_min[1]"]');
if (jQuery('input#usePriceRules').prop('checked')) {
otherPrices.hide();
minPrice1.hide();
} else {
otherPrices.show();
minPrice1.show();
}
};
jQuery(document).ready(function () {
showHidePriceRules();
jQuery('input#usePriceRules').click(showHidePriceRules);
});
</script>
<?php
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<input type="hidden" name="action" value="update_price">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
dol_fiche_head('');
if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) {
print $langs->trans('UseMultipriceRules'). ' <input type="checkbox" id="usePriceRules" name="usePriceRules" '.($object->price_autogen ? 'checked' : '').'><br><br>';
}
print '<table class="noborder">';
print '<thead><tr class="liste_titre">';
print '<td>'.$langs->trans("PriceLevel").'</td>';
if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) print '<td style="text-align: center">'.$langs->trans("VATRate").'</td>';
else print '<td></td>';
print '<td class="center">'.$langs->trans("SellingPrice").'</td>';
print '<td class="center">'.$langs->trans("MinPrice").'</td>';
if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
print '<td></td>';
}
print '</tr></thead>';
print '<tbody>';
$var = false;
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i ++)
{
$var = !$var;
print '<tr '.$bc[$var].'>';
print '<td>';
print $form->textwithpicto($langs->trans('SellingPrice') . ' ' . $i, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td>';
// VAT
if (empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) {
print '<td>';
print '<input type="hidden" name="tva_tx[' . $i . ']" value="' . ($object->default_vat_code ? $object->tva_tx.' ('.$object->default_vat_code.')' : $object->tva_tx) . '">';
print '<input type="hidden" name="tva_npr[' . $i . ']" value="' . $object->tva_npr . '">';
print '<input type="hidden" name="localtax1_tx[' . $i . ']" value="' . $object->localtax1_tx . '">';
print '<input type="hidden" name="localtax1_type[' . $i . ']" value="' . $object->localtax1_type . '">';
print '<input type="hidden" name="localtax2_tx[' . $i . ']" value="' . $object->localtax2_tx . '">';
print '<input type="hidden" name="localtax2_type[' . $i . ']" value="' . $object->localtax2_type . '">';
print '</td>';
} else {
// This option is kept for backward compatibility but has no sense
print '<td style="text-align: center">';
print $form->load_tva("tva_tx[" . $i.']', $object->multiprices_tva_tx[$i], $mysoc, '', $object->id, false, $object->type, false, 1);
print '</td>';
}
// Selling price
print '<td style="text-align: center">';
if ($object->multiprices_base_type [$i] == 'TTC') {
print '<input name="price[' . $i . ']" size="10" value="' . price($object->multiprices_ttc [$i]) . '">';
} else {
print '<input name="price[' . $i . ']" size="10" value="' . price($object->multiprices [$i]) . '">';
}
print ' '.$form->selectPriceBaseType($object->multiprices_base_type [$i], "multiprices_base_type[" . $i."]");
print '</td>';
// Min price
print '<td style="text-align: center">';
if ($object->multiprices_base_type [$i] == 'TTC') {
print '<input name="price_min[' . $i . ']" size="10" value="' . price($object->multiprices_min_ttc [$i]) . '">';
} else {
print '<input name="price_min[' . $i . ']" size="10" value="' . price($object->multiprices_min [$i]) . '">';
}
if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE))
{
print '<td align="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier,0,'',1,-1,-1,'auto')).' '.img_warning().'</td>';
}
print '</td>';
print '</tr>';
}
print '</tbody>';
print '</table>';
dol_fiche_end();
print '<div style="text-align: center">';
print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
print '</form>';
}
}
// List of price changes -log historic (ordered by descending date)
if ((empty($conf->global->PRODUIT_CUSTOMER_PRICES) || $action=='showlog_default_price') && ! in_array($action, array('edit_price','edit_vat')))
{
$sql = "SELECT p.rowid, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.recuperableonly,";
$sql .= " p.price_level, p.price_min, p.price_min_ttc,p.price_by_qty,";
$sql .= " p.date_price as dp, p.fk_price_expression, u.rowid as user_id, u.login";
$sql .= " FROM " . MAIN_DB_PREFIX . "product_price as p,";
$sql .= " " . MAIN_DB_PREFIX . "user as u";
$sql .= " WHERE fk_product = " . $object->id;
$sql .= " AND p.entity IN (" . getEntity('productprice', 1) . ")";
$sql .= " AND p.fk_user_author = u.rowid";
if (! empty($socid) && ! empty($conf->global->PRODUIT_MULTIPRICES)) $sql .= " AND p.price_level = " . $soc->price_level;
$sql .= " ORDER BY p.date_price DESC, p.rowid DESC, p.price_level ASC";
// $sql .= $db->plimit();
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
if (! $num)
{
$db->free($result);
// Il doit au moins y avoir la ligne de prix initial.
// On l'ajoute donc pour remettre a niveau (pb vieilles versions)
$object->updatePrice($object->price, $object->price_base_type, $user, $newprice_min);
$result = $db->query($sql);
$num = $db->num_rows($result);
}
if ($num > 0)
{
// Default prices or
// Log of previous customer prices
$backbutton='<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '">' . $langs->trans("Back") . '</a>';
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) print_barre_liste($langs->trans("DefaultPrice"),'','','','','',$backbutton, 0, 0, 'title_accountancy.png');
else print_barre_liste($langs->trans("PriceByCustomerLog"),'','','','','','', 0, 0, 'title_accountancy.png');
print '<div class="div-table-responsive">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("AppliedPricesFrom") . '</td>';
if (! empty($conf->global->PRODUIT_MULTIPRICES)) {
print '<td align="center">' . $langs->trans("PriceLevel") . '</td>';
}
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
print '<td align="center">' . $langs->trans("Type") . '</td>';
}
print '<td align="center">' . $langs->trans("PriceBase") . '</td>';
print $conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL;
if (empty($conf->global->PRODUIT_MULTIPRICES)) print '<td align="right">' . $langs->trans("VATRate") . '</td>';
print '<td align="right">' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("TTC") . '</td>';
if (! empty($conf->dynamicprices->enabled)) {
print '<td align="right">' . $langs->trans("PriceExpressionSelected") . '</td>';
}
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '</td>';
print '<td align="right">' . $langs->trans("ChangedBy") . '</td>';
if ($user->rights->produit->supprimer)
print '<td align="right"> </td>';
print '</tr>';
$notfirstlineforlevel=array();
$var = True;
$i = 0;
while ($i < $num)
{
$objp = $db->fetch_object($result);
$var = ! $var;
print '<tr '. $bc[$var].'>';
// Date
print "<td>" . dol_print_date($db->jdate($objp->dp), "dayhour") . "</td>";
// Price level
if (! empty($conf->global->PRODUIT_MULTIPRICES)) {
print '<td align="center">' . $objp->price_level . "</td>";
}
// Price by quantity
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
{
$type = ($objp->price_by_qty == 1) ? 'PriceByQuantity' : 'Standard';
print '<td align="center">' . $langs->trans($type) . "</td>";
}
print '<td align="center">' . $langs->trans($objp->price_base_type) . "</td>";
if (empty($conf->global->PRODUIT_MULTIPRICES)) print '<td align="right">' . vatrate($objp->tva_tx, true, $objp->recuperableonly) . "</td>";
// Price
if (! empty($objp->fk_price_expression) && ! empty($conf->dynamicprices->enabled))
{
$price_expression = new PriceExpression($db);
$res = $price_expression->fetch($objp->fk_price_expression);
$title = $price_expression->title;
print '<td align="right"></td>';
print '<td align="right"></td>';
print '<td align="right">' . $title . "</td>";
}
else
{
print '<td align="right">' . ($objp->price_base_type != 'TTC' ? price($objp->price) : ''). "</td>";
print '<td align="right">' . ($objp->price_base_type == 'TTC' ? price($objp->price_ttc) : '') . "</td>";
if (! empty($conf->dynamicprices->enabled)) { //Only if module is enabled
print '<td align="right"></td>';
}
}
print '<td align="right">' . ($objp->price_base_type != 'TTC' ? price($objp->price_min) : '') . '</td>';
print '<td align="right">' . ($objp->price_base_type == 'TTC' ? price($objp->price_min_ttc) : '') . '</td>';
// User
print '<td align="right"><a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $objp->user_id . '">' . img_object($langs->trans("ShowUser"), 'user') . ' ' . $objp->login . '</a></td>';
// Action
if ($user->rights->produit->supprimer)
{
$candelete=0;
if (! empty($conf->global->PRODUIT_MULTIPRICES))
{
if (empty($notfirstlineforlevel[$objp->price_level])) $notfirstlineforlevel[$objp->price_level]=1;
else $candelete=1;
}
elseif ($i > 0) $candelete=1;
print '<td align="right">';
if ($candelete)
{
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=delete&id=' . $object->id . '&lineid=' . $objp->rowid . '">';
print img_delete();
print '</a>';
} else
print ' '; // Can not delete last price (it's current price)
print '</td>';
}
print "</tr>\n";
$i++;
}
$db->free($result);
print "</table>";
print '</div>';
print "<br>";
}
} else {
dol_print_error($db);
}
}
// Add area to show/add/edit a price for a dedicated customer
if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
{
$prodcustprice = new Productcustomerprice($db);
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
$page = GETPOST("page", 'int');
if ($page == - 1) {
$page = 0;
}
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
if (! $sortorder)
$sortorder = "ASC";
if (! $sortfield)
$sortfield = "soc.nom";
// Build filter to diplay only concerned lines
$filter = array('t.fk_product' => $object->id);
if (! empty($search_soc)) {
$filter['soc.nom'] = $search_soc;
}
if ($action == 'add_customer_price')
{
// Form to add a new customer price
$maxpricesupplier = $object->min_recommended_price();
print load_fiche_titre($langs->trans('PriceByCustomer'));
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
print '<input type="hidden" name="action" value="add_customer_price_confirm">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
dol_fiche_head();
print '<table class="border" width="100%">';
print '<tr>';
print '<td class="fieldrequired">' . $langs->trans('ThirdParty') . '</td>';
print '<td>';
print $form->select_company('', 'socid', 's.client in (1,2,3) AND s.rowid NOT IN (SELECT fk_soc FROM ' . MAIN_DB_PREFIX . 'product_customer_price WHERE fk_product='.$object->id.')', 'SelectThirdParty', 0, 0, array(), 0, 'minwidth300');
print '</td>';
print '</tr>';
// VAT
print '<tr><td class="fieldrequired">' . $langs->trans("VATRate") . '</td><td>';
print $form->load_tva("tva_tx", $object->tva_tx, $mysoc, '', $object->id, $object->tva_npr, $object->type, false, 1);
print '</td></tr>';
// Price base
print '<tr><td class="fieldrequired">';
print $langs->trans('PriceBase');
print '</td>';
print '<td>';
print $form->selectPriceBaseType($object->price_base_type, "price_base_type");
print '</td>';
print '</tr>';
// Price
print '<tr><td class="fieldrequired">';
$text = $langs->trans('SellingPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td><td>';
if ($object->price_base_type == 'TTC') {
print '<input name="price" size="10" value="' . price($object->price_ttc) . '">';
} else {
print '<input name="price" size="10" value="' . price($object->price) . '">';
}
print '</td></tr>';
// Price minimum
print '<tr><td>';
$text = $langs->trans('MinPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
if ($object->price_base_type == 'TTC') {
print '<td><input name="price_min" size="10" value="' . price($object->price_min_ttc) . '">';
} else {
print '<td><input name="price_min" size="10" value="' . price($object->price_min) . '">';
}
if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE))
{
print '<td align="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier,0,'',1,-1,-1,'auto')).' '.img_warning().'</td>';
}
print '</td></tr>';
// Update all child soc
print '<tr><td width="15%">';
print $langs->trans('ForceUpdateChildPriceSoc');
print '</td>';
print '<td>';
print '<input type="checkbox" name="updatechildprice" value="1">';
print '</td>';
print '</tr>';
print '</table>';
dol_fiche_end();
print '<div class="center">';
print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</div>';
print '</form>';
}
elseif ($action == 'edit_customer_price')
{
// Edit mode
$maxpricesupplier = $object->min_recommended_price();
print load_fiche_titre($langs->trans('PriceByCustomer'));
$result = $prodcustprice->fetch(GETPOST('lineid', 'int'));
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
}
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="token" value="' . $_SESSION ['newtoken'] . '">';
print '<input type="hidden" name="action" value="update_customer_price_confirm">';
print '<input type="hidden" name="lineid" value="' . $prodcustprice->id . '">';
print '<table class="border" width="100%">';
print '<tr>';
print '<td>' . $langs->trans('ThirdParty') . '</td>';
$staticsoc = new Societe($db);
$staticsoc->fetch($prodcustprice->fk_soc);
print "<td colspan='2'>" . $staticsoc->getNomUrl(1) . "</td>";
print '</tr>';
// VAT
print '<tr><td>' . $langs->trans("VATRate") . '</td><td colspan="2">';
print $form->load_tva("tva_tx", $prodcustprice->tva_tx, $mysoc, '', $object->id, $prodcustprice->recuperableonly, $object->type, false, 1);
print '</td></tr>';
// Price base
print '<tr><td width="15%">';
print $langs->trans('PriceBase');
print '</td>';
print '<td>';
print $form->selectPriceBaseType($prodcustprice->price_base_type, "price_base_type");
print '</td>';
print '</tr>';
// Price
print '<tr><td width="20%">';
$text = $langs->trans('SellingPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td><td>';
if ($prodcustprice->price_base_type == 'TTC') {
print '<input name="price" size="10" value="' . price($prodcustprice->price_ttc) . '">';
} else {
print '<input name="price" size="10" value="' . price($prodcustprice->price) . '">';
}
print '</td></tr>';
// Price minimum
print '<tr><td>';
$text = $langs->trans('MinPrice');
print $form->textwithpicto($text, $langs->trans("PrecisionUnitIsLimitedToXDecimals", $conf->global->MAIN_MAX_DECIMALS_UNIT), 1, 1);
print '</td><td>';
if ($prodcustprice->price_base_type == 'TTC') {
print '<input name="price_min" size="10" value="' . price($prodcustprice->price_min_ttc) . '">';
} else {
print '<input name="price_min" size="10" value="' . price($prodcustprice->price_min) . '">';
}
print '</td>';
if ( !empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE))
{
print '<td align="left">'.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier,0,'',1,-1,-1,'auto')).' '.img_warning().'</td>';
}
print '</tr>';
// Update all child soc
print '<tr><td width="15%">';
print $langs->trans('ForceUpdateChildPriceSoc');
print '</td>';
print '<td>';
print '<input type="checkbox" name="updatechildprice" value="1">';
print '</td>';
print '</tr>';
print '</table>';
print '<br><div class="center">';
print '<input type="submit" class="button" value="' . $langs->trans("Save") . '">';
print ' ';
print '<input type="submit" class="button" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</div>';
print '<br></form>';
}
elseif ($action == 'showlog_customer_price')
{
$filter = array('t.fk_product' => $object->id,'t.fk_soc' => GETPOST('socid', 'int'));
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$nbtotalofrecords = $prodcustprice->fetch_all_log($sortorder, $sortfield, $conf->liste_limit, $offset, $filter);
}
$result = $prodcustprice->fetch_all_log($sortorder, $sortfield, $conf->liste_limit, $offset, $filter);
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
}
$option = '&socid=' . GETPOST('socid', 'int') . '&id=' . $object->id;
$staticsoc = new Societe($db);
$staticsoc->fetch(GETPOST('socid', 'int'));
$title=$langs->trans('PriceByCustomerLog');
$title.=' - '.$staticsoc->getNomUrl(1);
$backbutton='<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '">' . $langs->trans("Back") . '</a>';
print_barre_liste($title, $page, $_SERVEUR['PHP_SELF'], $option, $sortfield, $sortorder, $backbutton, count($prodcustprice->lines), $nbtotalofrecords, 'title_accountancy.png');
if (count($prodcustprice->lines) > 0)
{
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("ThirdParty") . '</td>';
print '<td>' . $langs->trans("AppliedPricesFrom") . '</td>';
print '<td align="center">' . $langs->trans("PriceBase") . '</td>';
print '<td align="right">' . $langs->trans("VATRate") . '</td>';
print '<td align="right">' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("TTC") . '</td>';
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '</td>';
print '<td align="right">' . $langs->trans("ChangedBy") . '</td>';
print '<td> </td>';
print '</tr>';
$var = True;
foreach ($prodcustprice->lines as $line)
{
$var = ! $var;
print "<tr ".$bc[$var].">";
// Date
$staticsoc = new Societe($db);
$staticsoc->fetch($line->fk_soc);
print "<td>" . $staticsoc->getNomUrl(1) . "</td>";
print "<td>" . dol_print_date($line->datec, "dayhour") . "</td>";
print '<td align="center">' . $langs->trans($line->price_base_type) . "</td>";
print '<td align="right">' . vatrate($line->tva_tx, true, $line->recuperableonly) . "</td>";
print '<td align="right">' . price($line->price) . "</td>";
print '<td align="right">' . price($line->price_ttc) . "</td>";
print '<td align="right">' . price($line->price_min) . '</td>';
print '<td align="right">' . price($line->price_min_ttc) . '</td>';
// User
$userstatic = new User($db);
$userstatic->fetch($line->fk_user);
print '<td align="right">';
print $userstatic->getLoginUrl(1);
print '</td>';
}
print "</table>";
} else {
print $langs->trans('None');
}
}
else if ($action != 'showlog_default_price' && $action != 'edit_price')
{
// List of all prices by customers
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
$nbtotalofrecords = $prodcustprice->fetch_all($sortorder, $sortfield, 0, 0, $filter);
}
$result = $prodcustprice->fetch_all($sortorder, $sortfield, $conf->liste_limit, $offset, $filter);
if ($result < 0) {
setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
}
$option = '&search_soc=' . $search_soc . '&id=' . $object->id;
print_barre_liste($langs->trans('PriceByCustomer'), $page, $_SERVEUR ['PHP_SELF'], $option, $sortfield, $sortorder, '', count($prodcustprice->lines), $nbtotalofrecords, 'title_accountancy.png');
print '<form action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td>' . $langs->trans("ThirdParty") . '</td>';
print '<td>' . $langs->trans("AppliedPricesFrom") . '</td>';
print '<td align="center">' . $langs->trans("PriceBase") . '</td>';
print '<td align="right">' . $langs->trans("VATRate") . '</td>';
print '<td align="right">' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("TTC") . '</td>';
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("HT") . '</td>';
print '<td align="right">' . $langs->trans("MinPrice") . ' ' . $langs->trans("TTC") . '</td>';
print '<td align="right">' . $langs->trans("ChangedBy") . '</td>';
print '<td> </td>';
print '</tr>';
if (count($prodcustprice->lines) > 0 || $search_soc)
{
print '<tr class="liste_titre">';
print '<td><input type="text" class="flat" name="search_soc" value="' . $search_soc . '" size="20"></td>';
print '<td colspan="8"> </td>';
// Print the search button
print '<td class="liste_titre" align="right">';
$searchpitco=$form->showFilterAndCheckAddButtons(0);
print $searchpitco;
print '</td>';
print '</tr>';
}
$var = False;
// Line for default price
print "<tr ".$bc[$var].">";
print "<td>" . $langs->trans("Default") . "</td>";
print "<td>" . "</td>";
print '<td align="center">' . $langs->trans($object->price_base_type) . "</td>";
print '<td align="right">' . vatrate($object->tva_tx, true, $object->recuperableonly) . "</td>";
print '<td align="right">' . price($object->price) . "</td>";
print '<td align="right">' . price($object->price_ttc) . "</td>";
print '<td align="right">' . price($object->price_min) . '</td>';
print '<td align="right">' . price($object->price_min_ttc) . '</td>';
print '<td align="right">';
print '</td>';
if ($user->rights->produit->supprimer || $user->rights->service->supprimer)
{
print '<td align="right">';
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=showlog_default_price&id=' . $object->id . '">';
print img_info($langs->trans('PriceByCustomerLog'));
print '</a>';
print ' ';
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=edit_price&id=' . $object->id . '">';
print img_edit('default', 0, 'style="vertical-align: middle;"');
print '</a>';
print ' ';
print '</td>';
}
print "</tr>\n";
if (count($prodcustprice->lines) > 0)
{
$var = false;
foreach ($prodcustprice->lines as $line)
{
$var = ! $var;
print "<tr ".$bc[$var].">";
// Date
$staticsoc = new Societe($db);
$staticsoc->fetch($line->fk_soc);
print "<td>" . $staticsoc->getNomUrl(1) . "</td>";
print "<td>" . dol_print_date($line->datec, "dayhour") . "</td>";
print '<td align="center">' . $langs->trans($line->price_base_type) . "</td>";
print '<td align="right">' . vatrate($line->tva_tx, true, $line->recuperableonly) . "</td>";
print '<td align="right">' . price($line->price) . "</td>";
print '<td align="right">' . price($line->price_ttc) . "</td>";
print '<td align="right">' . price($line->price_min) . '</td>';
print '<td align="right">' . price($line->price_min_ttc) . '</td>';
// User
$userstatic = new User($db);
$userstatic->fetch($line->fk_user);
print '<td align="right">';
print $userstatic->getLoginUrl(1);
print '</td>';
// Todo Edit or delete button
// Action
if ($user->rights->produit->supprimer || $user->rights->service->supprimer)
{
print '<td align="right">';
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=showlog_customer_price&id=' . $object->id . '&socid=' . $line->fk_soc . '">';
print img_info($langs->trans('PriceByCustomerLog'));
print '</a>';
print ' ';
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=edit_customer_price&id=' . $object->id . '&lineid=' . $line->id . '">';
print img_edit('default', 0, 'style="vertical-align: middle;"');
print '</a>';
print ' ';
print '<a href="' . $_SERVER["PHP_SELF"] . '?action=delete_customer_price&id=' . $object->id . '&lineid=' . $line->id . '">';
print img_delete('default', 'style="vertical-align: middle;"');
print '</a>';
print '</td>';
}
print "</tr>\n";
}
}
/*else
{
$colspan=9;
if ($user->rights->produit->supprimer || $user->rights->service->supprimer) $colspan+=1;
print "<tr ".$bc[false].">";
print '<td colspan="'.$colspan.'">'.$langs->trans('None').'</td>';
print "</tr>";
}*/
print "</table>";
print "</form>";
}
}
llxFooter();
$db->close();
| philippe-opendsi/dolibarr | htdocs/product/price.php | PHP | gpl-3.0 | 75,432 |
/*
* investovator, Stock Market Gaming framework
* Copyright (C) 2013 investovator
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.investovator.core.commons.events;
import java.io.Serializable;
/**
* @author Amila Surendra
* @version $Revision
*/
public class GameEvent implements Serializable {
}
| investovator/investovator-core | src/main/java/org/investovator/core/commons/events/GameEvent.java | Java | gpl-3.0 | 925 |
/*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package services
import (
"fmt"
"sync"
"github.com/cgrates/cgrates/engine"
v1 "github.com/cgrates/cgrates/apier/v1"
"github.com/cgrates/cgrates/config"
"github.com/cgrates/cgrates/servmanager"
"github.com/cgrates/cgrates/sessions"
"github.com/cgrates/cgrates/utils"
"github.com/cgrates/rpcclient"
)
// NewSessionService returns the Session Service
func NewSessionService(cfg *config.CGRConfig, dm *DataDBService,
server *utils.Server, internalChan chan rpcclient.ClientConnector,
exitChan chan bool, connMgr *engine.ConnManager) servmanager.Service {
return &SessionService{
connChan: internalChan,
cfg: cfg,
dm: dm,
server: server,
exitChan: exitChan,
connMgr: connMgr,
}
}
// SessionService implements Service interface
type SessionService struct {
sync.RWMutex
cfg *config.CGRConfig
dm *DataDBService
server *utils.Server
exitChan chan bool
sm *sessions.SessionS
rpc *v1.SMGenericV1
rpcv1 *v1.SessionSv1
connChan chan rpcclient.ClientConnector
// in order to stop the bircp server if necesary
bircpEnabled bool
connMgr *engine.ConnManager
}
// Start should handle the sercive start
func (smg *SessionService) Start() (err error) {
if smg.IsRunning() {
return fmt.Errorf("service aleady running")
}
var datadb *engine.DataManager
if smg.dm.IsRunning() {
dbchan := smg.dm.GetDMChan()
datadb = <-dbchan
dbchan <- datadb
}
smg.Lock()
defer smg.Unlock()
smg.sm = sessions.NewSessionS(smg.cfg, datadb, smg.connMgr)
//start sync session in a separate gorutine
go func(sm *sessions.SessionS) {
if err = sm.ListenAndServe(smg.exitChan); err != nil {
utils.Logger.Err(fmt.Sprintf("<%s> error: %s!", utils.SessionS, err))
}
}(smg.sm)
// Pass internal connection via BiRPCClient
smg.connChan <- smg.sm
// Register RPC handler
smg.rpc = v1.NewSMGenericV1(smg.sm)
smg.rpcv1 = v1.NewSessionSv1(smg.sm) // methods with multiple options
if !smg.cfg.DispatcherSCfg().Enabled {
smg.server.RpcRegister(smg.rpc)
smg.server.RpcRegister(smg.rpcv1)
}
// Register BiRpc handlers
if smg.cfg.SessionSCfg().ListenBijson != "" {
smg.bircpEnabled = true
for method, handler := range smg.rpc.Handlers() {
smg.server.BiRPCRegisterName(method, handler)
}
for method, handler := range smg.rpcv1.Handlers() {
smg.server.BiRPCRegisterName(method, handler)
}
// run this in it's own gorutine
go func() {
if err := smg.server.ServeBiJSON(smg.cfg.SessionSCfg().ListenBijson, smg.sm.OnBiJSONConnect, smg.sm.OnBiJSONDisconnect); err != nil {
utils.Logger.Err(fmt.Sprintf("<%s> serve BiRPC error: %s!", utils.SessionS, err))
smg.Lock()
smg.bircpEnabled = false
smg.Unlock()
}
}()
}
return
}
// GetIntenternalChan returns the internal connection chanel
func (smg *SessionService) GetIntenternalChan() (conn chan rpcclient.ClientConnector) {
return smg.connChan
}
// Reload handles the change of config
func (smg *SessionService) Reload() (err error) {
return
}
// Shutdown stops the service
func (smg *SessionService) Shutdown() (err error) {
smg.Lock()
defer smg.Unlock()
if err = smg.sm.Shutdown(); err != nil {
return
}
if smg.bircpEnabled {
smg.server.StopBiRPC()
smg.bircpEnabled = false
}
smg.sm = nil
smg.rpc = nil
smg.rpcv1 = nil
<-smg.connChan
return
}
// IsRunning returns if the service is running
func (smg *SessionService) IsRunning() bool {
smg.RLock()
defer smg.RUnlock()
return smg != nil && smg.sm != nil
}
// ServiceName returns the service name
func (smg *SessionService) ServiceName() string {
return utils.SessionS
}
// ShouldRun returns if the service should be running
func (smg *SessionService) ShouldRun() bool {
return smg.cfg.SessionSCfg().Enabled
}
| rinor/cgrates | services/sessions.go | GO | gpl-3.0 | 4,470 |
package coordinateSystem;
public class Point {
private double x;
private double y;
public Point() {
this.setX(0);
this.setY(0);
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
| LokeshSreekanta/TurtleGraphicsDesignPatterns | src/coordinateSystem/Point.java | Java | gpl-3.0 | 318 |
<?php
// Exit if accessed directly
if ( !defined('ABSPATH')) exit;
/**
* Blog Template
*
Template Name: Blog Excerpt (summary)
*
* @file blog-excerpt.php
* @package Responsive
* @author Emil Uzelac
* @copyright 2003 - 2013 ThemeID
* @license license.txt
* @version Release: 1.1.0
* @filesource wp-content/themes/responsive/blog-excerpt.php
* @link http://codex.wordpress.org/Templates
* @since available since Release 1.0
*/
get_header();
?>
<div id="content-blog" class="grid col-620">
<?php get_template_part( 'loop-header' ); ?>
<?php
global $wp_query, $paged;
if( get_query_var( 'paged' ) ) {
$paged = get_query_var( 'paged' );
}
elseif( get_query_var( 'page' ) ) {
$paged = get_query_var( 'page' );
}
else {
$paged = 1;
}
$blog_query = new WP_Query( array( 'post_type' => 'post', 'paged' => $paged ) );
$temp_query = $wp_query;
$wp_query = null;
$wp_query = $blog_query;
if ( $blog_query->have_posts() ) :
while ( $blog_query->have_posts() ) : $blog_query->the_post();
?>
<?php responsive_entry_before(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php responsive_entry_top(); ?>
<?php get_template_part( 'post-meta' ); ?>
<div class="post-entry">
<?php if ( has_post_thumbnail()) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<?php the_excerpt(); ?>
<?php wp_link_pages(array('before' => '<div class="pagination">' . __('Pages:', 'responsive'), 'after' => '</div>')); ?>
</div><!-- end of .post-entry -->
<?php get_template_part( 'post-data' ); ?>
<?php responsive_entry_bottom(); ?>
</div><!-- end of #post-<?php the_ID(); ?> -->
<?php responsive_entry_after(); ?>
<?php
endwhile;
if ( $wp_query->max_num_pages > 1 ) :
?>
<div class="navigation">
<div class="previous"><?php next_posts_link( __( '‹ Older posts', 'responsive' ), $wp_query->max_num_pages ); ?></div>
<div class="next"><?php previous_posts_link( __( 'Newer posts ›', 'responsive' ), $wp_query->max_num_pages ); ?></div>
</div><!-- end of .navigation -->
<?php
endif;
else :
get_template_part( 'loop-no-posts' );
endif;
$wp_query = $temp_query;
wp_reset_postdata();
?>
</div><!-- end of #content-blog -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | teamblueridge/tbr-responsive | blog-excerpt.php | PHP | gpl-3.0 | 2,786 |
/**
* MegaMek - Copyright (C) 2004,2005 Ben Mazur (bmazur@sev.org)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
/*
* Created on Sep 12, 2004
*
*/
package megamek.common.weapons.battlearmor;
import megamek.common.EquipmentType;
import megamek.common.TechConstants;
import megamek.common.weapons.LaserWeapon;
/**
* @author Andrew Hunter
*/
public class ISBAERSmallLaser extends LaserWeapon {
/**
*
*/
private static final long serialVersionUID = -4997798107691083605L;
/**
*
*/
public ISBAERSmallLaser() {
super();
techLevel.put(3071, TechConstants.T_IS_TW_NON_BOX);
name = "ER Small Laser";
setInternalName("ISBAERSmallLaser");
addLookupName("IS BA ER Small Laser");
damage = 3;
shortRange = 2;
mediumRange = 4;
longRange = 5;
extremeRange = 8;
waterShortRange = 1;
waterMediumRange = 2;
waterLongRange = 3;
waterExtremeRange = 4;
tonnage = 0.35f;
criticals = 2;
flags = flags.or(F_NO_FIRES).or(F_BA_WEAPON).andNot(F_MECH_WEAPON).andNot(F_TANK_WEAPON).andNot(F_AERO_WEAPON).andNot(F_PROTO_WEAPON);
bv = 17;
cost = 11250;
shortAV = 3;
maxRange = RANGE_SHORT;
availRating = new int[] { EquipmentType.RATING_X,
EquipmentType.RATING_X, EquipmentType.RATING_D };
introDate = 3058;
techRating = EquipmentType.RATING_E;
techLevel.put(3058, techLevel.get(3071));
}
}
| chvink/kilomek | megamek/src/megamek/common/weapons/battlearmor/ISBAERSmallLaser.java | Java | gpl-3.0 | 1,993 |
<?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2006 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
if (!defined("_ECRIRE_INC_VERSION")) return;
// Controle la presence de la lib safehtml et cree la fonction
// de transformation du texte qui l'exploite
if (@is_dir(_DIR_RESTREINT.'safehtml')) {
// http://doc.spip.org/@inc_safehtml_dist
function inc_safehtml_dist($t) {
static $process, $test;
if (!$test) {
if ($f = include_spip('safehtml/classes/safehtml', false)) {
define('XML_HTMLSAX3', dirname($f).'/');
include($f);
$process = new safehtml();
$process->deleteTags[] = 'param'; // sinon bug Firefox
} else die('pas de safe');
if ($process)
$test = 1; # ok
else
$test = -1; # se rabattre sur interdire_scripts
}
if ($test > 0) {
# reset ($process->clear() ne vide que _xhtml...),
# on doit pouvoir programmer ca plus propremement
$process->_counter = array();
$process->_stack = array();
$process->_dcCounter = array();
$process->_dcStack = array();
$process->_listScope = 0;
$process->_liStack = array();
# $process->parse(''); # cas particulier ?
$process->clear();
$t = $process->parse($t);
}
return $t;
}
}
?> | VertigeASBL/DLPbeta | plugins/forms_et_tables_2_0/inc/forms_safehtml_191.php | PHP | gpl-3.0 | 1,799 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = elementIdClick;
var _ErrorHandler = require('../utils/ErrorHandler');
function elementIdClick(id) {
if (typeof id !== 'string' && typeof id !== 'number') {
throw new _ErrorHandler.ProtocolError('number or type of arguments don\'t agree with elementIdClick protocol command');
}
return this.requestHandler.create({
path: `/session/:sessionId/element/${id}/click`,
method: 'POST'
});
} /**
*
* Click on an element.
*
* @param {String} ID ID of a WebElement JSON object to route the command to
*
* @see https://w3c.github.io/webdriver/webdriver-spec.html#dfn-element-click
* @type protocol
*
*/
module.exports = exports['default']; | Cy6erlion/wharica | node_modules/webdriverio/build/lib/protocol/elementIdClick.js | JavaScript | gpl-3.0 | 800 |
package com.neveagleson.ecocraft.core.utility;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
/**
* Created by NevEagleson on 4/03/2015
*/
public class PlayerEntityFilter extends EntityFilter
{
@Override
public boolean isEntityValid(EntityLivingBase entity)
{
return entity instanceof EntityPlayer != negate;
}
}
| NevEagleson/EcoCraft | ecocraft/main/java/com/neveagleson/ecocraft/core/utility/PlayerEntityFilter.java | Java | gpl-3.0 | 436 |
/*! \file
\brief Declaration of the upnp_call_addport_t
*/
#ifndef __NEOIP_UPNP_CALL_ADDPORT_HPP__
#define __NEOIP_UPNP_CALL_ADDPORT_HPP__
/* system include */
/* local include */
#include "neoip_upnp_call_addport_cb.hpp"
#include "neoip_upnp_call_cb.hpp"
#include "neoip_tokeep_check.hpp"
#include "neoip_copy_ctor_checker.hpp"
#include "neoip_namespace.hpp"
NEOIP_NAMESPACE_BEGIN
// list of forward declaration
class upnp_disc_res_t;
class upnp_call_profile_t;
class upnp_sockfam_t;
class delay_t;
/** \brief handle the listener of the nslan
*/
class upnp_call_addport_t : NEOIP_COPY_CTOR_DENY, private upnp_call_cb_t {
private:
/*************** upnp_call_t ***************************************/
upnp_call_t * upnp_call;
bool neoip_upnp_call_cb(void *cb_userptr, upnp_call_t &cb_call, const upnp_err_t &upnp_err
, const strvar_db_t &replied_var) throw();
/*************** callback stuff ***************************************/
upnp_call_addport_cb_t *callback; //!< callback used to notify result
void * userptr; //!< userptr associated with the callback
bool notify_callback(const upnp_err_t &upnp_err) throw();
TOKEEP_CHECK_DECL_DFL(); //!< used to sanity check the 'tokeep' value returned by callback
public:
/*************** ctor/dtor ***************************************/
upnp_call_addport_t() throw();
~upnp_call_addport_t() throw();
/*************** setup function ***************************************/
upnp_call_addport_t &set_profile(const upnp_call_profile_t &profile) throw();
upnp_err_t start(const upnp_disc_res_t &disc_res, uint16_t port_pview, uint16_t port_lview
, const upnp_sockfam_t &sock_fam, const delay_t &lease_delay
, const std::string &description_str
, upnp_call_addport_cb_t *callback, void * userptr) throw();
};
NEOIP_NAMESPACE_END
#endif // __NEOIP_UPNP_CALL_ADDPORT_HPP__
| jeromeetienne/neoip | src/neoip_upnp/call/call_addport/neoip_upnp_call_addport.hpp | C++ | gpl-3.0 | 1,877 |
package wehavecookies56.kk.item.recipes;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import wehavecookies56.kk.item.ItemKingdomKeys;
import wehavecookies56.kk.lib.LocalStrings;
import wehavecookies56.kk.lib.Reference;
import wehavecookies56.kk.lib.Strings;
public class ItemSweetMemoriesRecipe extends ItemKingdomKeys{
public ItemSweetMemoriesRecipe(int par1) {
super(par1);
}
public void registerIcons(IconRegister par1IconRegister) {
itemIcon = par1IconRegister.registerIcon(Reference.MOD_ID + ":" + this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".")+1));
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List dataList, boolean bool){
dataList.add(LocalStrings.Sweetmemories);
}
public static final ResourceLocation texture = new ResourceLocation("kk", "textures/items/" + Strings.Sweetmemories + ".png");
}
| Wehavecookies56/Kingdom-Keys | kk_common/wehavecookies56/kk/item/recipes/ItemSweetMemoriesRecipe.java | Java | gpl-3.0 | 1,149 |
<?PHP
require_once("website.php");
$adminModuleUtils->checkAdminModule(MODULE_ELEARNING);
$mlText = $languageUtils->getMlText(__FILE__);
$formSubmitted = LibEnv::getEnvHttpPOST("formSubmitted");
if ($formSubmitted) {
$elearningQuestionId = LibEnv::getEnvHttpPOST("elearningQuestionId");
$question = LibEnv::getEnvHttpPOST("question");
$points = LibEnv::getEnvHttpPOST("points");
$question = LibString::cleanString($question);
$points = LibString::cleanString($points);
// Duplicate the question
$elearningQuestionUtils->duplicate($elearningQuestionId, '', $question, $points);
$str = LibHtml::urlRedirect("$gElearningUrl/exercise/compose.php");
printContent($str);
return;
} else {
$elearningQuestionId = LibEnv::getEnvHttpGET("elearningQuestionId");
$question = '';
$points = '';
if ($elearningQuestionId) {
if ($elearningQuestion = $elearningQuestionUtils->selectById($elearningQuestionId)) {
$question = $elearningQuestion->getQuestion();
$points = $elearningQuestion->getPoints();
}
}
$panelUtils->setHeader($mlText[0], "$gElearningUrl/exercise/compose.php");
$panelUtils->openForm($PHP_SELF);
$panelUtils->addLine($panelUtils->addCell($mlText[1], "nbr"), "<input type='text' name='question' value='$question' size='30'>");
$panelUtils->addLine();
$panelUtils->addLine($panelUtils->addCell($mlText[5], "nbr"), "<input type='text' name='points' value='$points' size='3'>");
$panelUtils->addLine();
$panelUtils->addLine($panelUtils->addCell($mlText[7], "br"), $panelUtils->getOk());
$panelUtils->addHiddenField('formSubmitted', 1);
$panelUtils->addHiddenField('elearningQuestionId', $elearningQuestionId);
$panelUtils->closeForm();
$str = $panelUtils->render();
printAdminPage($str);
}
?>
| stephaneeybert/learnintouch | modules/elearning/question/duplicate.php | PHP | gpl-3.0 | 1,789 |
from d51.django.auth.decorators import auth_required
from django.contrib.sites.models import Site
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import ImproperlyConfigured
from .services import load_service, SharingServiceInvalidForm
from .models import URL
SHARE_KEY='u'
@auth_required()
def share_url(request, service_name):
# TODO: this view needs testing
response = HttpResponseRedirect(request.GET.get('next', '/'))
url_to_share = request.GET.get(SHARE_KEY, None)
if url_to_share is None:
# TODO change to a 400
raise Http404
else:
full_url_to_share = 'http://%s%s' % ((Site.objects.get_current().domain, url_to_share)) if url_to_share.find(':') == -1 else url_to_share
url, created = URL.objects.get_or_create(
url=full_url_to_share,
)
try:
url.send(service_name, request.user, request.POST)
except SharingServiceInvalidForm:
service = load_service(service_name, url)
input = [] if request.method != 'POST' else [request.POST]
form = service.get_form_class()(*input)
templates, context = [
'sharing/%s/prompt.html'%service_name,
'sharing/prompt.html'
],{
'service_name':service_name,
'form': form,
'url':url_to_share,
'SHARE_KEY':SHARE_KEY,
'next':request.GET.get('next','/')
}
response = render_to_response(templates, context, context_instance=RequestContext(request))
except ImproperlyConfigured:
raise Http404
return response
| domain51/d51.django.apps.sharing | d51/django/apps/sharing/views.py | Python | gpl-3.0 | 1,793 |
#!/usr/bin/python3
import gpxpy
import datetime
import time
import os
import gpxpy.gpx
import sqlite3
import pl
import re
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
filebase = os.environ["XDG_DATA_HOME"]+"/"+os.environ["APP_ID"].split('_')[0]
def create_gpx():
# Creating a new file:
# --------------------
gpx = gpxpy.gpx.GPX()
# Create first track in our GPX:
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)
# Create first segment in our GPX track:
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)
# Create points:
return gpx
def write_gpx(gpx,name,act_type):
# You can add routes and waypoints, too...
tzname=None
npoints=None
# polyline encoder default values
numLevels = 18;
zoomFactor = 2;
epsilon = 0.0;
forceEndpoints = True;
##print('Created GPX:', gpx.to_xml())
ts = int(time.time())
filename = "%s/%i.gpx" % (filebase,ts)
a = open(filename, 'w')
a.write(gpx.to_xml())
a.close()
gpx.simplify()
#gpx.reduce_points(1000)
trk = pl.read_gpx_trk(gpx.to_xml(),tzname,npoints,2,None)
try:
polyline=pl.print_gpx_google_polyline(trk,numLevels,zoomFactor,epsilon,forceEndpoints)
except UnboundLocalError as er:
print(er)
print("Not enough points to create a polyline")
polyline=""
#polyline="polyline"
add_run(gpx,name,act_type,filename,polyline)
def add_point(gpx,lat,lng,elev):
gpx.tracks[0].segments[0].points.append(gpxpy.gpx.GPXTrackPoint(lat, lng, elevation=elev,time=datetime.datetime.now()))
def add_run(gpx, name,act_type,filename,polyline):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)"
start_time, end_time = gpx.get_time_bounds()
l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
print(max_speed)
#print('%sStopped distance: %sm' % stopped_distance)
maxspeed = 'Max speed: {:.2f}km/h'.format(max_speed * 60. ** 2 / 1000. if max_speed else 0)
duration = 'Duration: {:.2f}min'.format(gpx.get_duration() / 60)
print("-------------------------")
print(name)
print(start_time)
print(l2d)
print(maxspeed)
print("-------------------------")
try:
cursor.execute(sql, [None, name,start_time,l2d,duration,act_type,filename,polyline])
conn.commit()
except sqlite3.Error as er:
print(er)
conn.close()
def get_runs():
#add_run("1", "2", "3", "4")
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
ret_data=[]
sql = "SELECT * FROM activities LIMIT 30"
for i in cursor.execute(sql):
ret_data.append(dict(i))
conn.close()
return ret_data
def get_units():
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists settings
(units text)""")
ret_data=[]
sql = "SELECT units FROM settings"
cursor.execute(sql)
data=cursor.fetchone()
if data is None:
print("NONESIES")
cursor.execute("INSERT INTO settings VALUES ('kilometers')")
conn.commit()
conn.close()
return "kilometers"
return data
def set_units(label):
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("UPDATE settings SET units=? WHERE 1", (label,))
conn.commit()
conn.close()
def onetime_db_fix():
os.makedirs(filebase, exist_ok=True)
filename = "%s/%s" % (filebase,".dbfixed")
if not os.path.exists(filename):
print("Fixing db")
conn = sqlite3.connect('%s/activities.db' % filebase)
numonly = re.compile("(\d*\.\d*)")
cursor = conn.cursor()
a=get_runs()
sql="UPDATE activities SET distance=? WHERE id=?"
for i in a:
print(i["distance"])
b=numonly.search(i["distance"])
print(b.group(0))
print(b)
cursor.execute(sql, (b.group(0), i["id"]))
conn.commit()
conn.close()
dotfile=open(filename, "w")
dotfile.write("db fixed")
dotfile.close
else:
print("db already fixed")
def rm_run(run):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
sql = "DELETE from activities WHERE id=?"
try:
cursor.execute(sql, [run])
conn.commit()
except sqlite3.Error as er:
print("-------------______---_____---___----____--____---___-----")
print(er)
conn.close()
def km_to_mi(km):
return km * 0.62137
def get_data():
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
return moving_distance, moving_time
| VictorThompson/ActivityTracker | py/geepeeex.py | Python | gpl-3.0 | 5,539 |
/**
* Diese Datei ist Teil des Alexa Skills Rollenspiel Soloabenteuer.
* Copyright (C) 2016-2017 Ferenc Hechler (github@fh.anderemails.de)
*
* Der Alexa Skills Rollenspiel Soloabenteuer ist Freie Software:
* Sie koennen es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder spaeteren
* veroeffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Der Alexa Skills Rollenspiel Soloabenteuer wird in der Hoffnung,
* dass es nuetzlich sein wird, aber
* OHNE JEDE GEWAEHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewaehrleistung der MARKTFAEHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License fuer weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*/
package de.hechler.soloroleplay.data;
import java.util.ArrayList;
import java.util.List;
import de.hechler.soloroleplay.util.TextUtil;
public class Opponent {
public enum OpponentType {
FRIEND, FOE
}
private RestrictedParameterMap parameters = new RestrictedParameterMap(new String[]
{"WAFFE", "AT", "PA", "TP", "DK", "LEP", "AP", "RS", "AUP", "GS", "MR", "MU", "KK", "GE", "CH", "IN", "WS", "KO"}
);
private List<String> additions = new ArrayList<String>();
private OpponentType type;
private String name;
private String gegnerText;
public Opponent(OpponentType type, String name, String gegnerText) {
this.type = type;
this.name = name;
this.gegnerText = gegnerText;
}
public String getName() {
return name;
}
public OpponentType getType() {
return type;
}
public String getTypeName() {
return type == OpponentType.FRIEND ? "Freund" : "Gegner";
}
public boolean knowsParameter(String name) {
return parameters.isAllowed(name);
}
public void addParameter(String name, String value) {
parameters.addParameter(name, value);
}
public String getParameter(String paramName) {
return parameters.getValue(paramName);
}
public void addAddition(String addition) {
additions.add(addition);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getTypeName().toUpperCase()).append(": ").append(name).append(TextUtil.endl);
if (gegnerText != null) {
result.append("TEXT: ").append(gegnerText).append(TextUtil.endl);
}
result.append(parameters);
for (String addition:additions) {
result.append("ZUSATZ: ").append(addition).append(TextUtil.endl);
}
return result.toString();
}
public void describe(Response response) {
if (gegnerText != null) {
response.addDescription(gegnerText);
}
else {
response.addDescription(getTypeName()).addDescription(getName()+":");
describeParameter(response, "MU", "Mut");
describeParameter(response, "WAFFE", "Waffe");
describeParameter(response, "DK", "Distanzklasse");
describeParameter(response, "TP", "Trefferpunkte");
describeParameter(response, "AT", "Attacke");
describeParameter(response, "PA", "Parade");
describeParameter(response, "RS", "R"+TextUtil.UML_ue+"stungsschutz");
describeParameter(response, "LEP", "Lebenspunkte");
describeParameter(response, "AP", "Astralpunkte");
describeParameter(response, "AUP", "Ausdauerpunkte");
describeParameter(response, "GS", "Geschwindigkeit");
describeParameter(response, "MR", "Magieresistenz");
describeParameter(response, "KK", "K"+TextUtil.UML_oe+"rperkraft");
describeParameter(response, "GE", "Geschicklichkeit");
describeParameter(response, "CH", "Charisma");
describeParameter(response, "IN", "Intelligenz");
describeParameter(response, "WS", "Weisheit");
describeParameter(response, "KO", "Konstitution");
for (String addition:additions) {
response.addDescription(";").addDescription(TextUtil.handleMinus(addition));
}
}
response.addDescription(";");
}
private void describeParameter(Response response, String paramName, String plaintextName) {
String value = getParameter(paramName);
if ((value != null) && !value.trim().isEmpty()) {
response.addDescription(";").addDescription(plaintextName).addDescription(TextUtil.handleMinus(value));
}
}
}
| ferenc-hechler/RollenspielAlexaSkill | RoleplayMaster/RoleplayEngine/src/main/java/de/hechler/soloroleplay/data/Opponent.java | Java | gpl-3.0 | 4,316 |
/*
Copyright 2014 Travel Modelling Group, Department of Civil Engineering, University of Toronto
This file is part of XTMF.
XTMF is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
XTMF is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with XTMF. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using XTMF;
namespace TMG.Emme
{
public class ExtraAttributeData : IModule
{
[Parameter("Domain", "NODE", "Extra attribute domain (type). Accepted values are NODE, LINK, TURN, TRANSIT_LINE, or TRANSIT_SEGMENT")]
public string Domain;
[Parameter("Id", "@node1", "The 6-character ID string of the extra attribute, including the '@' symbol.")]
public string Id;
[Parameter("Default", 0.0f, "The default value for the extra attribute.")]
public float DefaultValue;
private HashSet<string> _AllowedDomains;
public ExtraAttributeData()
{
_AllowedDomains = new HashSet<string>
{
"NODE",
"LINK",
"TURN",
"TRANSIT_LINE",
"TRANSIT_SEGMENT"
};
}
public string Name
{
get;
set;
}
public float Progress
{
get { return 1.0f; }
}
private static Tuple<byte, byte, byte> _ProgressColour = new Tuple<byte, byte, byte>(100, 100, 150);
public Tuple<byte, byte, byte> ProgressColour
{
get { return _ProgressColour; }
}
public bool RuntimeValidation(ref string error)
{
if (!_AllowedDomains.Contains(Domain))
{
error = "Domain '" + Domain + "' is not supported. It must be one of NODE, LINK, TURN, TRANSIT_LINE, or TRANSIT_SEGMENT.";
return false;
}
if (!Id.StartsWith("@"))
{
error = "Extra attribute ID must begin with the '@' symbol (current value is '" + Id + "').";
return false;
}
return true;
}
}
public class ExtraAttributeContextManager : IEmmeTool
{
[RunParameter("Scenario", 0, "The number of the Emme scenario.")]
public int ScenarioNumber;
[Parameter("Delete Flag", true, "Tf set to true, this module will delete the attributes after running. Otherwise, this module will just ensure that the attributes exist and are initialized.")]
public bool DeleteFlag;
[Parameter("Reset To Default", false, "Reset the attributes to their default values if they already exist.")]
public bool ResetToDefault;
[SubModelInformation(Description="Attribute to create.")]
public List<ExtraAttributeData> AttributesToCreate;
[SubModelInformation(Description="Emme tools to run")]
public List<IEmmeTool> EmmeToolsToRun;
private const string ToolName = "tmg.XTMF_internal.temp_attribute_manager";
private IEmmeTool _RunningTool;
private float _Progress;
public bool Execute(Controller controller)
{
_Progress = 0.0f;
_RunningTool = null;
if (EmmeToolsToRun.Count == 0) return true;
var mc = controller as ModellerController;
if (mc == null)
throw new XTMFRuntimeException(this, "Controller is not a ModellerController!");
float numberOfTasks = AttributesToCreate.Count + 1;
bool[] createdAttributes = new bool[AttributesToCreate.Count];
/*
def __call__(self, xtmf_ScenarioNumber, xtmf_AttributeId, xtmf_AttributeDomain,
xtmf_AttributeDefault, xtmf_DeleteFlag):
*/
try
{
for (int i = 0; i < createdAttributes.Length; i++)
{
var attData = AttributesToCreate[i];
var args = string.Join(" ", ScenarioNumber, attData.Id, attData.Domain, attData.DefaultValue, false, ResetToDefault);
createdAttributes[i] = mc.Run(this, ToolName, args);
// ReSharper disable once PossibleLossOfFraction
_Progress = i / createdAttributes.Length / numberOfTasks;
}
_Progress = 1.0f / numberOfTasks;
foreach (var tool in EmmeToolsToRun)
{
tool.Execute(mc);
_Progress += 1.0f / numberOfTasks;
}
}
finally
{
if (DeleteFlag)
{
for (int i = 0; i < createdAttributes.Length; i++)
{
if (createdAttributes[i])
{
var attData = AttributesToCreate[i];
var args = string.Join(" ", ScenarioNumber, attData.Id, attData.Domain, attData.DefaultValue, true, ResetToDefault);
mc.Run(this, ToolName, args);
}
}
}
}
return true;
}
public string Name
{
get;
set;
}
public float Progress
{
get
{
if (_RunningTool != null)
{
return _Progress + _RunningTool.Progress / (EmmeToolsToRun.Count);
} else
{
return _Progress;
}
}
}
private static Tuple<byte, byte, byte> _ProgressColour = new Tuple<byte, byte, byte>(100, 100, 150);
public Tuple<byte, byte, byte> ProgressColour
{
get { return _ProgressColour; }
}
public bool RuntimeValidation(ref string error)
{
if(EmmeToolsToRun.Count == 0 && AttributesToCreate.Count > 0)
{
error = "In '"+Name+"' you must have at least one tool to run in order for ExtraAttributeContextManager to function properly.";
return false;
}
return true;
}
}
}
| TravelModellingGroup/XTMF | Code/TMG.Emme/ExtraAttributeContextManager.cs | C# | gpl-3.0 | 6,733 |
// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "codegen.h"
#include "deoptimizer.h"
#include "disasm.h"
#include "full-codegen.h"
#include "global-handles.h"
#include "macro-assembler.h"
#include "prettyprinter.h"
namespace v8 {
namespace internal {
LargeObjectChunk* Deoptimizer::eager_deoptimization_entry_code_ = NULL;
LargeObjectChunk* Deoptimizer::lazy_deoptimization_entry_code_ = NULL;
Deoptimizer* Deoptimizer::current_ = NULL;
DeoptimizingCodeListNode* Deoptimizer::deoptimizing_code_list_ = NULL;
Deoptimizer* Deoptimizer::New(JSFunction* function,
BailoutType type,
unsigned bailout_id,
Address from,
int fp_to_sp_delta) {
Deoptimizer* deoptimizer =
new Deoptimizer(function, type, bailout_id, from, fp_to_sp_delta);
ASSERT(current_ == NULL);
current_ = deoptimizer;
return deoptimizer;
}
Deoptimizer* Deoptimizer::Grab() {
Deoptimizer* result = current_;
ASSERT(result != NULL);
result->DeleteFrameDescriptions();
current_ = NULL;
return result;
}
void Deoptimizer::GenerateDeoptimizationEntries(MacroAssembler* masm,
int count,
BailoutType type) {
TableEntryGenerator generator(masm, type, count);
generator.Generate();
}
class DeoptimizingVisitor : public OptimizedFunctionVisitor {
public:
virtual void EnterContext(Context* context) {
if (FLAG_trace_deopt) {
PrintF("[deoptimize context: %" V8PRIxPTR "]\n",
reinterpret_cast<intptr_t>(context));
}
}
virtual void VisitFunction(JSFunction* function) {
Deoptimizer::DeoptimizeFunction(function);
}
virtual void LeaveContext(Context* context) {
context->ClearOptimizedFunctions();
}
};
void Deoptimizer::DeoptimizeAll() {
AssertNoAllocation no_allocation;
if (FLAG_trace_deopt) {
PrintF("[deoptimize all contexts]\n");
}
DeoptimizingVisitor visitor;
VisitAllOptimizedFunctions(&visitor);
}
void Deoptimizer::DeoptimizeGlobalObject(JSObject* object) {
AssertNoAllocation no_allocation;
DeoptimizingVisitor visitor;
VisitAllOptimizedFunctionsForGlobalObject(object, &visitor);
}
void Deoptimizer::VisitAllOptimizedFunctionsForContext(
Context* context, OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
ASSERT(context->IsGlobalContext());
visitor->EnterContext(context);
// Run through the list of optimized functions and deoptimize them.
Object* element = context->OptimizedFunctionsListHead();
while (!element->IsUndefined()) {
JSFunction* element_function = JSFunction::cast(element);
// Get the next link before deoptimizing as deoptimizing will clear the
// next link.
element = element_function->next_function_link();
visitor->VisitFunction(element_function);
}
visitor->LeaveContext(context);
}
void Deoptimizer::VisitAllOptimizedFunctionsForGlobalObject(
JSObject* object, OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
if (object->IsJSGlobalProxy()) {
Object* proto = object->GetPrototype();
ASSERT(proto->IsJSGlobalObject());
VisitAllOptimizedFunctionsForContext(
GlobalObject::cast(proto)->global_context(), visitor);
} else if (object->IsGlobalObject()) {
VisitAllOptimizedFunctionsForContext(
GlobalObject::cast(object)->global_context(), visitor);
}
}
void Deoptimizer::VisitAllOptimizedFunctions(
OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
// Run through the list of all global contexts and deoptimize.
Object* global = Heap::global_contexts_list();
while (!global->IsUndefined()) {
VisitAllOptimizedFunctionsForGlobalObject(Context::cast(global)->global(),
visitor);
global = Context::cast(global)->get(Context::NEXT_CONTEXT_LINK);
}
}
void Deoptimizer::HandleWeakDeoptimizedCode(
v8::Persistent<v8::Value> obj, void* data) {
DeoptimizingCodeListNode* node =
reinterpret_cast<DeoptimizingCodeListNode*>(data);
RemoveDeoptimizingCode(*node->code());
#ifdef DEBUG
node = Deoptimizer::deoptimizing_code_list_;
while (node != NULL) {
ASSERT(node != reinterpret_cast<DeoptimizingCodeListNode*>(data));
node = node->next();
}
#endif
}
void Deoptimizer::ComputeOutputFrames(Deoptimizer* deoptimizer) {
deoptimizer->DoComputeOutputFrames();
}
Deoptimizer::Deoptimizer(JSFunction* function,
BailoutType type,
unsigned bailout_id,
Address from,
int fp_to_sp_delta)
: function_(function),
bailout_id_(bailout_id),
bailout_type_(type),
from_(from),
fp_to_sp_delta_(fp_to_sp_delta),
output_count_(0),
output_(NULL),
deferred_heap_numbers_(0) {
if (FLAG_trace_deopt && type != OSR) {
PrintF("**** DEOPT: ");
function->PrintName();
PrintF(" at bailout #%u, address 0x%" V8PRIxPTR ", frame size %d\n",
bailout_id,
reinterpret_cast<intptr_t>(from),
fp_to_sp_delta - (2 * kPointerSize));
} else if (FLAG_trace_osr && type == OSR) {
PrintF("**** OSR: ");
function->PrintName();
PrintF(" at ast id #%u, address 0x%" V8PRIxPTR ", frame size %d\n",
bailout_id,
reinterpret_cast<intptr_t>(from),
fp_to_sp_delta - (2 * kPointerSize));
}
// Find the optimized code.
if (type == EAGER) {
ASSERT(from == NULL);
optimized_code_ = function_->code();
} else if (type == LAZY) {
optimized_code_ = FindDeoptimizingCodeFromAddress(from);
ASSERT(optimized_code_ != NULL);
} else if (type == OSR) {
// The function has already been optimized and we're transitioning
// from the unoptimized shared version to the optimized one in the
// function. The return address (from) points to unoptimized code.
optimized_code_ = function_->code();
ASSERT(optimized_code_->kind() == Code::OPTIMIZED_FUNCTION);
ASSERT(!optimized_code_->contains(from));
}
ASSERT(Heap::allow_allocation(false));
unsigned size = ComputeInputFrameSize();
input_ = new(size) FrameDescription(size, function);
}
Deoptimizer::~Deoptimizer() {
ASSERT(input_ == NULL && output_ == NULL);
}
void Deoptimizer::DeleteFrameDescriptions() {
delete input_;
for (int i = 0; i < output_count_; ++i) {
if (output_[i] != input_) delete output_[i];
}
delete[] output_;
input_ = NULL;
output_ = NULL;
ASSERT(!Heap::allow_allocation(true));
}
Address Deoptimizer::GetDeoptimizationEntry(int id, BailoutType type) {
ASSERT(id >= 0);
if (id >= kNumberOfEntries) return NULL;
LargeObjectChunk* base = NULL;
if (type == EAGER) {
if (eager_deoptimization_entry_code_ == NULL) {
eager_deoptimization_entry_code_ = CreateCode(type);
}
base = eager_deoptimization_entry_code_;
} else {
if (lazy_deoptimization_entry_code_ == NULL) {
lazy_deoptimization_entry_code_ = CreateCode(type);
}
base = lazy_deoptimization_entry_code_;
}
return
static_cast<Address>(base->GetStartAddress()) + (id * table_entry_size_);
}
int Deoptimizer::GetDeoptimizationId(Address addr, BailoutType type) {
LargeObjectChunk* base = NULL;
if (type == EAGER) {
base = eager_deoptimization_entry_code_;
} else {
base = lazy_deoptimization_entry_code_;
}
if (base == NULL ||
addr < base->GetStartAddress() ||
addr >= base->GetStartAddress() +
(kNumberOfEntries * table_entry_size_)) {
return kNotDeoptimizationEntry;
}
ASSERT_EQ(0,
static_cast<int>(addr - base->GetStartAddress()) % table_entry_size_);
return static_cast<int>(addr - base->GetStartAddress()) / table_entry_size_;
}
void Deoptimizer::Setup() {
// Do nothing yet.
}
void Deoptimizer::TearDown() {
if (eager_deoptimization_entry_code_ != NULL) {
eager_deoptimization_entry_code_->Free(EXECUTABLE);
eager_deoptimization_entry_code_ = NULL;
}
if (lazy_deoptimization_entry_code_ != NULL) {
lazy_deoptimization_entry_code_->Free(EXECUTABLE);
lazy_deoptimization_entry_code_ = NULL;
}
}
int Deoptimizer::GetOutputInfo(DeoptimizationOutputData* data,
unsigned id,
SharedFunctionInfo* shared) {
// TODO(kasperl): For now, we do a simple linear search for the PC
// offset associated with the given node id. This should probably be
// changed to a binary search.
int length = data->DeoptPoints();
Smi* smi_id = Smi::FromInt(id);
for (int i = 0; i < length; i++) {
if (data->AstId(i) == smi_id) {
return data->PcAndState(i)->value();
}
}
PrintF("[couldn't find pc offset for node=%u]\n", id);
PrintF("[method: %s]\n", *shared->DebugName()->ToCString());
// Print the source code if available.
HeapStringAllocator string_allocator;
StringStream stream(&string_allocator);
shared->SourceCodePrint(&stream, -1);
PrintF("[source:\n%s\n]", *stream.ToCString());
UNREACHABLE();
return -1;
}
int Deoptimizer::GetDeoptimizedCodeCount() {
int length = 0;
DeoptimizingCodeListNode* node = Deoptimizer::deoptimizing_code_list_;
while (node != NULL) {
length++;
node = node->next();
}
return length;
}
void Deoptimizer::DoComputeOutputFrames() {
if (bailout_type_ == OSR) {
DoComputeOsrOutputFrame();
return;
}
// Print some helpful diagnostic information.
int64_t start = OS::Ticks();
if (FLAG_trace_deopt) {
PrintF("[deoptimizing%s: begin 0x%08" V8PRIxPTR " ",
(bailout_type_ == LAZY ? " (lazy)" : ""),
reinterpret_cast<intptr_t>(function_));
function_->PrintName();
PrintF(" @%d]\n", bailout_id_);
}
// Determine basic deoptimization information. The optimized frame is
// described by the input data.
DeoptimizationInputData* input_data =
DeoptimizationInputData::cast(optimized_code_->deoptimization_data());
unsigned node_id = input_data->AstId(bailout_id_)->value();
ByteArray* translations = input_data->TranslationByteArray();
unsigned translation_index =
input_data->TranslationIndex(bailout_id_)->value();
// Do the input frame to output frame(s) translation.
TranslationIterator iterator(translations, translation_index);
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator.Next());
ASSERT(Translation::BEGIN == opcode);
USE(opcode);
// Read the number of output frames and allocate an array for their
// descriptions.
int count = iterator.Next();
ASSERT(output_ == NULL);
output_ = new FrameDescription*[count];
for (int i = 0; i < count; ++i) {
output_[i] = NULL;
}
output_count_ = count;
// Translate each output frame.
for (int i = 0; i < count; ++i) {
DoComputeFrame(&iterator, i);
}
// Print some helpful diagnostic information.
if (FLAG_trace_deopt) {
double ms = static_cast<double>(OS::Ticks() - start) / 1000;
int index = output_count_ - 1; // Index of the topmost frame.
JSFunction* function = output_[index]->GetFunction();
PrintF("[deoptimizing: end 0x%08" V8PRIxPTR " ",
reinterpret_cast<intptr_t>(function));
function->PrintName();
PrintF(" => node=%u, pc=0x%08" V8PRIxPTR ", state=%s, took %0.3f ms]\n",
node_id,
output_[index]->GetPc(),
FullCodeGenerator::State2String(
static_cast<FullCodeGenerator::State>(
output_[index]->GetState()->value())),
ms);
}
}
void Deoptimizer::MaterializeHeapNumbers() {
for (int i = 0; i < deferred_heap_numbers_.length(); i++) {
HeapNumberMaterializationDescriptor d = deferred_heap_numbers_[i];
Handle<Object> num = Factory::NewNumber(d.value());
if (FLAG_trace_deopt) {
PrintF("Materializing a new heap number %p [%e] in slot %p\n",
reinterpret_cast<void*>(*num),
d.value(),
d.slot_address());
}
Memory::Object_at(d.slot_address()) = *num;
}
}
void Deoptimizer::DoTranslateCommand(TranslationIterator* iterator,
int frame_index,
unsigned output_offset) {
disasm::NameConverter converter;
// A GC-safe temporary placeholder that we can put in the output frame.
const intptr_t kPlaceholder = reinterpret_cast<intptr_t>(Smi::FromInt(0));
// Ignore commands marked as duplicate and act on the first non-duplicate.
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator->Next());
while (opcode == Translation::DUPLICATE) {
opcode = static_cast<Translation::Opcode>(iterator->Next());
iterator->Skip(Translation::NumberOfOperandsFor(opcode));
opcode = static_cast<Translation::Opcode>(iterator->Next());
}
switch (opcode) {
case Translation::BEGIN:
case Translation::FRAME:
case Translation::DUPLICATE:
UNREACHABLE();
return;
case Translation::REGISTER: {
int input_reg = iterator->Next();
intptr_t input_value = input_->GetRegister(input_reg);
if (FLAG_trace_deopt) {
PrintF(
" 0x%08" V8PRIxPTR ": [top + %d] <- 0x%08" V8PRIxPTR " ; %s\n",
output_[frame_index]->GetTop() + output_offset,
output_offset,
input_value,
converter.NameOfCPURegister(input_reg));
}
output_[frame_index]->SetFrameSlot(output_offset, input_value);
return;
}
case Translation::INT32_REGISTER: {
int input_reg = iterator->Next();
intptr_t value = input_->GetRegister(input_reg);
bool is_smi = Smi::IsValid(value);
if (FLAG_trace_deopt) {
PrintF(
" 0x%08" V8PRIxPTR ": [top + %d] <- %" V8PRIdPTR " ; %s (%s)\n",
output_[frame_index]->GetTop() + output_offset,
output_offset,
value,
converter.NameOfCPURegister(input_reg),
is_smi ? "smi" : "heap number");
}
if (is_smi) {
intptr_t tagged_value =
reinterpret_cast<intptr_t>(Smi::FromInt(static_cast<int>(value)));
output_[frame_index]->SetFrameSlot(output_offset, tagged_value);
} else {
// We save the untagged value on the side and store a GC-safe
// temporary placeholder in the frame.
AddDoubleValue(output_[frame_index]->GetTop() + output_offset,
static_cast<double>(static_cast<int32_t>(value)));
output_[frame_index]->SetFrameSlot(output_offset, kPlaceholder);
}
return;
}
case Translation::DOUBLE_REGISTER: {
int input_reg = iterator->Next();
double value = input_->GetDoubleRegister(input_reg);
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": [top + %d] <- %e ; %s\n",
output_[frame_index]->GetTop() + output_offset,
output_offset,
value,
DoubleRegister::AllocationIndexToString(input_reg));
}
// We save the untagged value on the side and store a GC-safe
// temporary placeholder in the frame.
AddDoubleValue(output_[frame_index]->GetTop() + output_offset, value);
output_[frame_index]->SetFrameSlot(output_offset, kPlaceholder);
return;
}
case Translation::STACK_SLOT: {
int input_slot_index = iterator->Next();
unsigned input_offset =
input_->GetOffsetFromSlotIndex(this, input_slot_index);
intptr_t input_value = input_->GetFrameSlot(input_offset);
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": ",
output_[frame_index]->GetTop() + output_offset);
PrintF("[top + %d] <- 0x%08" V8PRIxPTR " ; [esp + %d]\n",
output_offset,
input_value,
input_offset);
}
output_[frame_index]->SetFrameSlot(output_offset, input_value);
return;
}
case Translation::INT32_STACK_SLOT: {
int input_slot_index = iterator->Next();
unsigned input_offset =
input_->GetOffsetFromSlotIndex(this, input_slot_index);
intptr_t value = input_->GetFrameSlot(input_offset);
bool is_smi = Smi::IsValid(value);
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": ",
output_[frame_index]->GetTop() + output_offset);
PrintF("[top + %d] <- %" V8PRIdPTR " ; [esp + %d] (%s)\n",
output_offset,
value,
input_offset,
is_smi ? "smi" : "heap number");
}
if (is_smi) {
intptr_t tagged_value =
reinterpret_cast<intptr_t>(Smi::FromInt(static_cast<int>(value)));
output_[frame_index]->SetFrameSlot(output_offset, tagged_value);
} else {
// We save the untagged value on the side and store a GC-safe
// temporary placeholder in the frame.
AddDoubleValue(output_[frame_index]->GetTop() + output_offset,
static_cast<double>(static_cast<int32_t>(value)));
output_[frame_index]->SetFrameSlot(output_offset, kPlaceholder);
}
return;
}
case Translation::DOUBLE_STACK_SLOT: {
int input_slot_index = iterator->Next();
unsigned input_offset =
input_->GetOffsetFromSlotIndex(this, input_slot_index);
double value = input_->GetDoubleFrameSlot(input_offset);
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": [top + %d] <- %e ; [esp + %d]\n",
output_[frame_index]->GetTop() + output_offset,
output_offset,
value,
input_offset);
}
// We save the untagged value on the side and store a GC-safe
// temporary placeholder in the frame.
AddDoubleValue(output_[frame_index]->GetTop() + output_offset, value);
output_[frame_index]->SetFrameSlot(output_offset, kPlaceholder);
return;
}
case Translation::LITERAL: {
Object* literal = ComputeLiteral(iterator->Next());
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": [top + %d] <- ",
output_[frame_index]->GetTop() + output_offset,
output_offset);
literal->ShortPrint();
PrintF(" ; literal\n");
}
intptr_t value = reinterpret_cast<intptr_t>(literal);
output_[frame_index]->SetFrameSlot(output_offset, value);
return;
}
case Translation::ARGUMENTS_OBJECT: {
// Use the arguments marker value as a sentinel and fill in the arguments
// object after the deoptimized frame is built.
ASSERT(frame_index == 0); // Only supported for first frame.
if (FLAG_trace_deopt) {
PrintF(" 0x%08" V8PRIxPTR ": [top + %d] <- ",
output_[frame_index]->GetTop() + output_offset,
output_offset);
Heap::arguments_marker()->ShortPrint();
PrintF(" ; arguments object\n");
}
intptr_t value = reinterpret_cast<intptr_t>(Heap::arguments_marker());
output_[frame_index]->SetFrameSlot(output_offset, value);
return;
}
}
}
bool Deoptimizer::DoOsrTranslateCommand(TranslationIterator* iterator,
int* input_offset) {
disasm::NameConverter converter;
FrameDescription* output = output_[0];
// The input values are all part of the unoptimized frame so they
// are all tagged pointers.
uintptr_t input_value = input_->GetFrameSlot(*input_offset);
Object* input_object = reinterpret_cast<Object*>(input_value);
Translation::Opcode opcode =
static_cast<Translation::Opcode>(iterator->Next());
bool duplicate = (opcode == Translation::DUPLICATE);
if (duplicate) {
opcode = static_cast<Translation::Opcode>(iterator->Next());
}
switch (opcode) {
case Translation::BEGIN:
case Translation::FRAME:
case Translation::DUPLICATE:
UNREACHABLE(); // Malformed input.
return false;
case Translation::REGISTER: {
int output_reg = iterator->Next();
if (FLAG_trace_osr) {
PrintF(" %s <- 0x%08" V8PRIxPTR " ; [sp + %d]\n",
converter.NameOfCPURegister(output_reg),
input_value,
*input_offset);
}
output->SetRegister(output_reg, input_value);
break;
}
case Translation::INT32_REGISTER: {
// Abort OSR if we don't have a number.
if (!input_object->IsNumber()) return false;
int output_reg = iterator->Next();
int int32_value = input_object->IsSmi()
? Smi::cast(input_object)->value()
: FastD2I(input_object->Number());
// Abort the translation if the conversion lost information.
if (!input_object->IsSmi() &&
FastI2D(int32_value) != input_object->Number()) {
if (FLAG_trace_osr) {
PrintF("**** %g could not be converted to int32 ****\n",
input_object->Number());
}
return false;
}
if (FLAG_trace_osr) {
PrintF(" %s <- %d (int32) ; [sp + %d]\n",
converter.NameOfCPURegister(output_reg),
int32_value,
*input_offset);
}
output->SetRegister(output_reg, int32_value);
break;
}
case Translation::DOUBLE_REGISTER: {
// Abort OSR if we don't have a number.
if (!input_object->IsNumber()) return false;
int output_reg = iterator->Next();
double double_value = input_object->Number();
if (FLAG_trace_osr) {
PrintF(" %s <- %g (double) ; [sp + %d]\n",
DoubleRegister::AllocationIndexToString(output_reg),
double_value,
*input_offset);
}
output->SetDoubleRegister(output_reg, double_value);
break;
}
case Translation::STACK_SLOT: {
int output_index = iterator->Next();
unsigned output_offset =
output->GetOffsetFromSlotIndex(this, output_index);
if (FLAG_trace_osr) {
PrintF(" [sp + %d] <- 0x%08" V8PRIxPTR " ; [sp + %d]\n",
output_offset,
input_value,
*input_offset);
}
output->SetFrameSlot(output_offset, input_value);
break;
}
case Translation::INT32_STACK_SLOT: {
// Abort OSR if we don't have a number.
if (!input_object->IsNumber()) return false;
int output_index = iterator->Next();
unsigned output_offset =
output->GetOffsetFromSlotIndex(this, output_index);
int int32_value = input_object->IsSmi()
? Smi::cast(input_object)->value()
: DoubleToInt32(input_object->Number());
// Abort the translation if the conversion lost information.
if (!input_object->IsSmi() &&
FastI2D(int32_value) != input_object->Number()) {
if (FLAG_trace_osr) {
PrintF("**** %g could not be converted to int32 ****\n",
input_object->Number());
}
return false;
}
if (FLAG_trace_osr) {
PrintF(" [sp + %d] <- %d (int32) ; [sp + %d]\n",
output_offset,
int32_value,
*input_offset);
}
output->SetFrameSlot(output_offset, int32_value);
break;
}
case Translation::DOUBLE_STACK_SLOT: {
static const int kLowerOffset = 0 * kPointerSize;
static const int kUpperOffset = 1 * kPointerSize;
// Abort OSR if we don't have a number.
if (!input_object->IsNumber()) return false;
int output_index = iterator->Next();
unsigned output_offset =
output->GetOffsetFromSlotIndex(this, output_index);
double double_value = input_object->Number();
uint64_t int_value = BitCast<uint64_t, double>(double_value);
int32_t lower = static_cast<int32_t>(int_value);
int32_t upper = static_cast<int32_t>(int_value >> kBitsPerInt);
if (FLAG_trace_osr) {
PrintF(" [sp + %d] <- 0x%08x (upper bits of %g) ; [sp + %d]\n",
output_offset + kUpperOffset,
upper,
double_value,
*input_offset);
PrintF(" [sp + %d] <- 0x%08x (lower bits of %g) ; [sp + %d]\n",
output_offset + kLowerOffset,
lower,
double_value,
*input_offset);
}
output->SetFrameSlot(output_offset + kLowerOffset, lower);
output->SetFrameSlot(output_offset + kUpperOffset, upper);
break;
}
case Translation::LITERAL: {
// Just ignore non-materialized literals.
iterator->Next();
break;
}
case Translation::ARGUMENTS_OBJECT: {
// Optimized code assumes that the argument object has not been
// materialized and so bypasses it when doing arguments access.
// We should have bailed out before starting the frame
// translation.
UNREACHABLE();
return false;
}
}
if (!duplicate) *input_offset -= kPointerSize;
return true;
}
void Deoptimizer::PatchStackCheckCode(Code* unoptimized_code,
Code* check_code,
Code* replacement_code) {
// Iterate over the stack check table and patch every stack check
// call to an unconditional call to the replacement code.
ASSERT(unoptimized_code->kind() == Code::FUNCTION);
Address stack_check_cursor = unoptimized_code->instruction_start() +
unoptimized_code->stack_check_table_offset();
uint32_t table_length = Memory::uint32_at(stack_check_cursor);
stack_check_cursor += kIntSize;
for (uint32_t i = 0; i < table_length; ++i) {
uint32_t pc_offset = Memory::uint32_at(stack_check_cursor + kIntSize);
Address pc_after = unoptimized_code->instruction_start() + pc_offset;
PatchStackCheckCodeAt(pc_after, check_code, replacement_code);
stack_check_cursor += 2 * kIntSize;
}
}
void Deoptimizer::RevertStackCheckCode(Code* unoptimized_code,
Code* check_code,
Code* replacement_code) {
// Iterate over the stack check table and revert the patched
// stack check calls.
ASSERT(unoptimized_code->kind() == Code::FUNCTION);
Address stack_check_cursor = unoptimized_code->instruction_start() +
unoptimized_code->stack_check_table_offset();
uint32_t table_length = Memory::uint32_at(stack_check_cursor);
stack_check_cursor += kIntSize;
for (uint32_t i = 0; i < table_length; ++i) {
uint32_t pc_offset = Memory::uint32_at(stack_check_cursor + kIntSize);
Address pc_after = unoptimized_code->instruction_start() + pc_offset;
RevertStackCheckCodeAt(pc_after, check_code, replacement_code);
stack_check_cursor += 2 * kIntSize;
}
}
unsigned Deoptimizer::ComputeInputFrameSize() const {
unsigned fixed_size = ComputeFixedSize(function_);
// The fp-to-sp delta already takes the context and the function
// into account so we have to avoid double counting them (-2).
unsigned result = fixed_size + fp_to_sp_delta_ - (2 * kPointerSize);
#ifdef DEBUG
if (bailout_type_ == OSR) {
// TODO(kasperl): It would be nice if we could verify that the
// size matches with the stack height we can compute based on the
// environment at the OSR entry. The code for that his built into
// the DoComputeOsrOutputFrame function for now.
} else {
unsigned stack_slots = optimized_code_->stack_slots();
unsigned outgoing_size = ComputeOutgoingArgumentSize();
ASSERT(result == fixed_size + (stack_slots * kPointerSize) + outgoing_size);
}
#endif
return result;
}
unsigned Deoptimizer::ComputeFixedSize(JSFunction* function) const {
// The fixed part of the frame consists of the return address, frame
// pointer, function, context, and all the incoming arguments.
static const unsigned kFixedSlotSize = 4 * kPointerSize;
return ComputeIncomingArgumentSize(function) + kFixedSlotSize;
}
unsigned Deoptimizer::ComputeIncomingArgumentSize(JSFunction* function) const {
// The incoming arguments is the values for formal parameters and
// the receiver. Every slot contains a pointer.
unsigned arguments = function->shared()->formal_parameter_count() + 1;
return arguments * kPointerSize;
}
unsigned Deoptimizer::ComputeOutgoingArgumentSize() const {
DeoptimizationInputData* data = DeoptimizationInputData::cast(
optimized_code_->deoptimization_data());
unsigned height = data->ArgumentsStackHeight(bailout_id_)->value();
return height * kPointerSize;
}
Object* Deoptimizer::ComputeLiteral(int index) const {
DeoptimizationInputData* data = DeoptimizationInputData::cast(
optimized_code_->deoptimization_data());
FixedArray* literals = data->LiteralArray();
return literals->get(index);
}
void Deoptimizer::AddDoubleValue(intptr_t slot_address,
double value) {
HeapNumberMaterializationDescriptor value_desc(
reinterpret_cast<Address>(slot_address), value);
deferred_heap_numbers_.Add(value_desc);
}
LargeObjectChunk* Deoptimizer::CreateCode(BailoutType type) {
// We cannot run this if the serializer is enabled because this will
// cause us to emit relocation information for the external
// references. This is fine because the deoptimizer's code section
// isn't meant to be serialized at all.
ASSERT(!Serializer::enabled());
bool old_debug_code = FLAG_debug_code;
FLAG_debug_code = false;
MacroAssembler masm(NULL, 16 * KB);
GenerateDeoptimizationEntries(&masm, kNumberOfEntries, type);
CodeDesc desc;
masm.GetCode(&desc);
ASSERT(desc.reloc_size == 0);
LargeObjectChunk* chunk = LargeObjectChunk::New(desc.instr_size, EXECUTABLE);
memcpy(chunk->GetStartAddress(), desc.buffer, desc.instr_size);
CPU::FlushICache(chunk->GetStartAddress(), desc.instr_size);
FLAG_debug_code = old_debug_code;
return chunk;
}
Code* Deoptimizer::FindDeoptimizingCodeFromAddress(Address addr) {
DeoptimizingCodeListNode* node = Deoptimizer::deoptimizing_code_list_;
while (node != NULL) {
if (node->code()->contains(addr)) return *node->code();
node = node->next();
}
return NULL;
}
void Deoptimizer::RemoveDeoptimizingCode(Code* code) {
ASSERT(deoptimizing_code_list_ != NULL);
// Run through the code objects to find this one and remove it.
DeoptimizingCodeListNode* prev = NULL;
DeoptimizingCodeListNode* current = deoptimizing_code_list_;
while (current != NULL) {
if (*current->code() == code) {
// Unlink from list. If prev is NULL we are looking at the first element.
if (prev == NULL) {
deoptimizing_code_list_ = current->next();
} else {
prev->set_next(current->next());
}
delete current;
return;
}
// Move to next in list.
prev = current;
current = current->next();
}
// Deoptimizing code is removed through weak callback. Each object is expected
// to be removed once and only once.
UNREACHABLE();
}
FrameDescription::FrameDescription(uint32_t frame_size,
JSFunction* function)
: frame_size_(frame_size),
function_(function),
top_(kZapUint32),
pc_(kZapUint32),
fp_(kZapUint32) {
// Zap all the registers.
for (int r = 0; r < Register::kNumRegisters; r++) {
SetRegister(r, kZapUint32);
}
// Zap all the slots.
for (unsigned o = 0; o < frame_size; o += kPointerSize) {
SetFrameSlot(o, kZapUint32);
}
}
unsigned FrameDescription::GetOffsetFromSlotIndex(Deoptimizer* deoptimizer,
int slot_index) {
if (slot_index >= 0) {
// Local or spill slots. Skip the fixed part of the frame
// including all arguments.
unsigned base = static_cast<unsigned>(
GetFrameSize() - deoptimizer->ComputeFixedSize(GetFunction()));
return base - ((slot_index + 1) * kPointerSize);
} else {
// Incoming parameter.
unsigned base = static_cast<unsigned>(GetFrameSize() -
deoptimizer->ComputeIncomingArgumentSize(GetFunction()));
return base - ((slot_index + 1) * kPointerSize);
}
}
void TranslationBuffer::Add(int32_t value) {
// Encode the sign bit in the least significant bit.
bool is_negative = (value < 0);
uint32_t bits = ((is_negative ? -value : value) << 1) |
static_cast<int32_t>(is_negative);
// Encode the individual bytes using the least significant bit of
// each byte to indicate whether or not more bytes follow.
do {
uint32_t next = bits >> 7;
contents_.Add(((bits << 1) & 0xFF) | (next != 0));
bits = next;
} while (bits != 0);
}
int32_t TranslationIterator::Next() {
ASSERT(HasNext());
// Run through the bytes until we reach one with a least significant
// bit of zero (marks the end).
uint32_t bits = 0;
for (int i = 0; true; i += 7) {
uint8_t next = buffer_->get(index_++);
bits |= (next >> 1) << i;
if ((next & 1) == 0) break;
}
// The bits encode the sign in the least significant bit.
bool is_negative = (bits & 1) == 1;
int32_t result = bits >> 1;
return is_negative ? -result : result;
}
Handle<ByteArray> TranslationBuffer::CreateByteArray() {
int length = contents_.length();
Handle<ByteArray> result = Factory::NewByteArray(length, TENURED);
memcpy(result->GetDataStartAddress(), contents_.ToVector().start(), length);
return result;
}
void Translation::BeginFrame(int node_id, int literal_id, unsigned height) {
buffer_->Add(FRAME);
buffer_->Add(node_id);
buffer_->Add(literal_id);
buffer_->Add(height);
}
void Translation::StoreRegister(Register reg) {
buffer_->Add(REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreInt32Register(Register reg) {
buffer_->Add(INT32_REGISTER);
buffer_->Add(reg.code());
}
void Translation::StoreDoubleRegister(DoubleRegister reg) {
buffer_->Add(DOUBLE_REGISTER);
buffer_->Add(DoubleRegister::ToAllocationIndex(reg));
}
void Translation::StoreStackSlot(int index) {
buffer_->Add(STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreInt32StackSlot(int index) {
buffer_->Add(INT32_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreDoubleStackSlot(int index) {
buffer_->Add(DOUBLE_STACK_SLOT);
buffer_->Add(index);
}
void Translation::StoreLiteral(int literal_id) {
buffer_->Add(LITERAL);
buffer_->Add(literal_id);
}
void Translation::StoreArgumentsObject() {
buffer_->Add(ARGUMENTS_OBJECT);
}
void Translation::MarkDuplicate() {
buffer_->Add(DUPLICATE);
}
int Translation::NumberOfOperandsFor(Opcode opcode) {
switch (opcode) {
case ARGUMENTS_OBJECT:
case DUPLICATE:
return 0;
case BEGIN:
case REGISTER:
case INT32_REGISTER:
case DOUBLE_REGISTER:
case STACK_SLOT:
case INT32_STACK_SLOT:
case DOUBLE_STACK_SLOT:
case LITERAL:
return 1;
case FRAME:
return 3;
}
UNREACHABLE();
return -1;
}
#ifdef OBJECT_PRINT
const char* Translation::StringFor(Opcode opcode) {
switch (opcode) {
case BEGIN:
return "BEGIN";
case FRAME:
return "FRAME";
case REGISTER:
return "REGISTER";
case INT32_REGISTER:
return "INT32_REGISTER";
case DOUBLE_REGISTER:
return "DOUBLE_REGISTER";
case STACK_SLOT:
return "STACK_SLOT";
case INT32_STACK_SLOT:
return "INT32_STACK_SLOT";
case DOUBLE_STACK_SLOT:
return "DOUBLE_STACK_SLOT";
case LITERAL:
return "LITERAL";
case ARGUMENTS_OBJECT:
return "ARGUMENTS_OBJECT";
case DUPLICATE:
return "DUPLICATE";
}
UNREACHABLE();
return "";
}
#endif
DeoptimizingCodeListNode::DeoptimizingCodeListNode(Code* code): next_(NULL) {
// Globalize the code object and make it weak.
code_ = Handle<Code>::cast((GlobalHandles::Create(code)));
GlobalHandles::MakeWeak(reinterpret_cast<Object**>(code_.location()),
this,
Deoptimizer::HandleWeakDeoptimizedCode);
}
DeoptimizingCodeListNode::~DeoptimizingCodeListNode() {
GlobalHandles::Destroy(reinterpret_cast<Object**>(code_.location()));
}
} } // namespace v8::internal
| chriskmanx/qmole | QMOLEDEV/node/deps/v8/src/deoptimizer.cc | C++ | gpl-3.0 | 37,813 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace ApiPinger
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| cullenglassner/ApiPinger | Program.cs | C# | gpl-3.0 | 545 |
(function() {
var Agent, AgentSet, Agents, Animator, Color, ColorMap, Evented, Link, Links, Model, Patch, Patches, Shapes, Util, shapes, u, util,
__hasProp = {}.hasOwnProperty,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Util = util = u = {
error: function(s) {
throw new Error(s);
},
MaxINT: Math.pow(2, 53),
MinINT: -Math.pow(2, 53),
MaxINT32: 0 | 0x7fffffff,
MinINT32: 0 | 0x80000000,
isArray: Array.isArray || function(obj) {
return !!(obj && obj.concat && obj.unshift && !obj.callee);
},
isFunction: function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
},
isString: function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
},
randomSeed: function(seed) {
if (seed == null) {
seed = 123456;
}
return Math.random = function() {
var x;
x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
};
},
randomInt: function(max) {
return Math.floor(Math.random() * max);
},
randomInt2: function(min, max) {
return min + Math.floor(Math.random() * (max - min));
},
randomNormal: function(mean, sigma) {
var norm, u1, u2;
if (mean == null) {
mean = 0.0;
}
if (sigma == null) {
sigma = 1.0;
}
u1 = 1.0 - Math.random();
u2 = Math.random();
norm = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2);
return norm * sigma + mean;
},
randomFloat: function(max) {
return Math.random() * max;
},
randomFloat2: function(min, max) {
return min + Math.random() * (max - min);
},
randomCentered: function(r) {
return this.randomFloat2(-r / 2, r / 2);
},
log10: function(n) {
return Math.log(n) / Math.LN10;
},
log2: function(n) {
return this.logN(n, 2);
},
logN: function(n, base) {
return Math.log(n) / Math.log(base);
},
mod: function(v, n) {
return ((v % n) + n) % n;
},
wrap: function(v, min, max) {
return min + this.mod(v - min, max - min);
},
clamp: function(v, min, max) {
return Math.max(Math.min(v, max), min);
},
sign: function(v) {
if (v < 0) {
return -1;
} else {
return 1;
}
},
fixed: function(n, p) {
if (p == null) {
p = 2;
}
p = Math.pow(10, p);
return Math.round(n * p) / p;
},
aToFixed: function(a, p) {
var i, _i, _len, _results;
if (p == null) {
p = 2;
}
_results = [];
for (_i = 0, _len = a.length; _i < _len; _i++) {
i = a[_i];
_results.push(i.toFixed(p));
}
return _results;
},
tls: function(n) {
return n.toLocaleString();
},
randomColor: function(c) {
var i, _i;
if (c == null) {
c = [];
}
if (c.str != null) {
c.str = null;
}
for (i = _i = 0; _i <= 2; i = ++_i) {
c[i] = this.randomInt(256);
}
return c;
},
randomGray: function(c, min, max) {
var i, r, _i;
if (c == null) {
c = [];
}
if (min == null) {
min = 64;
}
if (max == null) {
max = 192;
}
if (arguments.length === 2) {
return this.randomGray(null, c, min);
}
if (c.str != null) {
c.str = null;
}
r = this.randomInt2(min, max);
for (i = _i = 0; _i <= 2; i = ++_i) {
c[i] = r;
}
return c;
},
randomMapColor: function(c, set) {
if (c == null) {
c = [];
}
if (set == null) {
set = [0, 63, 127, 191, 255];
}
return this.setColor(c, this.oneOf(set), this.oneOf(set), this.oneOf(set));
},
randomBrightColor: function(c) {
if (c == null) {
c = [];
}
return this.randomMapColor(c, [0, 127, 255]);
},
randomHSBColor: function(c) {
if (c == null) {
c = [];
}
return c = this.hsbToRgb([this.randomInt(51) * 5, 255, 255]);
},
setColor: function(c, r, g, b, a) {
if (c.str != null) {
c.str = null;
}
c[0] = r;
c[1] = g;
c[2] = b;
if (a != null) {
c[3] = a;
}
return c;
},
setGray: function(c, g, a) {
return this.setColor(c, g, g, g, a);
},
scaleColor: function(max, s, c) {
var i, val, _i, _len;
if (c == null) {
c = [];
}
if (c.str != null) {
c.str = null;
}
for (i = _i = 0, _len = max.length; _i < _len; i = ++_i) {
val = max[i];
c[i] = this.clamp(Math.round(val * s), 0, 255);
}
return c;
},
colorStr: function(c) {
var s;
if ((s = c.str) != null) {
return s;
}
if (c.length === 4 && c[3] > 1) {
this.error("alpha > 1");
}
return c.str = c.length === 3 ? "rgb(" + c + ")" : "rgba(" + c + ")";
},
colorsEqual: function(c1, c2) {
return c1.toString() === c2.toString();
},
rgbToGray: function(c) {
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
},
rgbToHsb: function(c) {
var b, d, g, h, max, min, r, s, v;
r = c[0] / 255;
g = c[1] / 255;
b = c[2] / 255;
max = Math.max(r, g, b);
min = Math.min(r, g, b);
v = max;
h = 0;
d = max - min;
s = max === 0 ? 0 : d / max;
if (max !== min) {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
}
}
return [Math.round(255 * h / 6), Math.round(255 * s), Math.round(255 * v)];
},
hsbToRgb: function(c) {
var b, f, g, h, i, p, q, r, s, t, v;
h = c[0] / 255;
s = c[1] / 255;
v = c[2] / 255;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
},
rgbMap: function(R, G, B) {
var b, g, i, map, r, _i, _j, _k, _len, _len1, _len2;
if (G == null) {
G = R;
}
if (B == null) {
B = R;
}
if (typeof R === "number") {
R = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; 0 <= R ? _i < R : _i > R; i = 0 <= R ? ++_i : --_i) {
_results.push(Math.round(i * 255 / (R - 1)));
}
return _results;
})();
}
if (typeof G === "number") {
G = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; 0 <= G ? _i < G : _i > G; i = 0 <= G ? ++_i : --_i) {
_results.push(Math.round(i * 255 / (G - 1)));
}
return _results;
})();
}
if (typeof B === "number") {
B = (function() {
var _i, _results;
_results = [];
for (i = _i = 0; 0 <= B ? _i < B : _i > B; i = 0 <= B ? ++_i : --_i) {
_results.push(Math.round(i * 255 / (B - 1)));
}
return _results;
})();
}
map = [];
for (_i = 0, _len = R.length; _i < _len; _i++) {
r = R[_i];
for (_j = 0, _len1 = G.length; _j < _len1; _j++) {
g = G[_j];
for (_k = 0, _len2 = B.length; _k < _len2; _k++) {
b = B[_k];
map.push([r, g, b]);
}
}
}
return map;
},
grayMap: function() {
var i, _i, _results;
_results = [];
for (i = _i = 0; _i <= 255; i = ++_i) {
_results.push([i, i, i]);
}
return _results;
},
hsbMap: function(n, s, b) {
var i, _i, _results;
if (n == null) {
n = 256;
}
if (s == null) {
s = 255;
}
if (b == null) {
b = 255;
}
_results = [];
for (i = _i = 0; 0 <= n ? _i < n : _i > n; i = 0 <= n ? ++_i : --_i) {
_results.push(this.hsbToRgb([i * 255 / (n - 1), s, b]));
}
return _results;
},
gradientMap: function(nColors, stops, locs) {
var ctx, grad, i, id, _i, _j, _ref, _ref1, _results;
if (locs == null) {
locs = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(i / (stops.length - 1));
}
return _results;
})();
}
ctx = this.createCtx(nColors, 1);
grad = ctx.createLinearGradient(0, 0, nColors, 0);
for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
grad.addColorStop(locs[i], this.colorStr(stops[i]));
}
ctx.fillStyle = grad;
ctx.fillRect(0, 0, nColors, 1);
id = this.ctxToImageData(ctx).data;
_results = [];
for (i = _j = 0, _ref1 = id.length; _j < _ref1; i = _j += 4) {
_results.push([id[i], id[i + 1], id[i + 2]]);
}
return _results;
},
isLittleEndian: function() {
var d32;
d32 = new Uint32Array([0x01020304]);
return (new Uint8ClampedArray(d32.buffer))[0] === 4;
},
degToRad: function(degrees) {
return degrees * Math.PI / 180;
},
radToDeg: function(radians) {
return radians * 180 / Math.PI;
},
subtractRads: function(rad1, rad2) {
var PI, dr;
dr = rad1 - rad2;
PI = Math.PI;
if (dr <= -PI) {
dr += 2 * PI;
}
if (dr > PI) {
dr -= 2 * PI;
}
return dr;
},
ownKeys: function(obj) {
var key, value, _results;
_results = [];
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = obj[key];
_results.push(key);
}
return _results;
},
ownVarKeys: function(obj) {
var key, value, _results;
_results = [];
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = obj[key];
if (!this.isFunction(value)) {
_results.push(key);
}
}
return _results;
},
ownValues: function(obj) {
var key, value, _results;
_results = [];
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = obj[key];
_results.push(value);
}
return _results;
},
cloneObject: function(obj) {
var key, newObj, value;
newObj = {};
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = obj[key];
newObj[key] = obj[key];
}
if (obj.__proto__ !== Object.prototype) {
console.log("cloneObject, setting proto");
newObj.__proto__ = obj.__proto__;
}
return newObj;
},
cloneClass: function(oldClass, newName) {
var ctorStr;
ctorStr = oldClass.toString().replace(/^/, "var ctor = ");
if (newName) {
ctorStr = ctorStr.replace(/function.*{/, "function " + newName + "() {");
}
eval(ctorStr);
ctor.prototype = this.cloneObject(oldClass.prototype);
ctor.constructor = oldClass.constructor;
ctor.prototype.constructor = oldClass.prototype.constructor;
return ctor;
},
mixin: function(destObj, srcObject) {
var key, _ref, _results;
for (key in srcObject) {
if (!__hasProp.call(srcObject, key)) continue;
destObj[key] = srcObject[key];
}
_ref = srcObject.__proto__;
_results = [];
for (key in _ref) {
if (!__hasProp.call(_ref, key)) continue;
_results.push(destObj.__proto__[key] = srcObject.__proto__[key]);
}
return _results;
},
parseToPrimitive: function(s) {
var e;
try {
return JSON.parse(s);
} catch (_error) {
e = _error;
return decodeURIComponent(s);
}
},
parseQueryString: function(query) {
var res, s, t, _i, _len, _ref;
if (query == null) {
query = window.location.search.substring(1);
}
res = {};
_ref = query.split("&");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
s = _ref[_i];
if (!(query.length !== 0)) {
continue;
}
t = s.split("=");
res[t[0]] = t.length === 1 ? true : this.parseToPrimitive(t[1]);
}
return res;
},
any: function(array) {
return array.length !== 0;
},
empty: function(array) {
return array.length === 0;
},
clone: function(array, begin, end) {
var op;
op = array.slice != null ? "slice" : "subarray";
if (begin != null) {
return array[op](begin, end);
} else {
return array[op](0);
}
},
last: function(array) {
if (this.empty(array)) {
this.error("last: empty array");
}
return array[array.length - 1];
},
oneOf: function(array) {
if (this.empty(array)) {
this.error("oneOf: empty array");
}
return array[this.randomInt(array.length)];
},
nOf: function(array, n) {
var o, r;
n = Math.min(array.length, Math.floor(n));
r = [];
while (r.length < n) {
o = this.oneOf(array);
if (__indexOf.call(r, o) < 0) {
r.push(o);
}
}
return r;
},
contains: function(array, item, f) {
return this.indexOf(array, item, f) >= 0;
},
removeItem: function(array, item, f) {
var i;
if (!((i = this.indexOf(array, item, f)) < 0)) {
return array.splice(i, 1);
} else {
return this.error("removeItem: item not found");
}
},
removeItems: function(array, items, f) {
var i, _i, _len;
for (_i = 0, _len = items.length; _i < _len; _i++) {
i = items[_i];
this.removeItem(array, i, f);
}
return array;
},
insertItem: function(array, item, f) {
var i;
i = this.sortedIndex(array, item, f);
if (array[i] === item) {
error("insertItem: item already in array");
}
return array.splice(i, 0, item);
},
shuffle: function(array) {
return array.sort(function() {
return 0.5 - Math.random();
});
},
minOneOf: function(array, f, valueToo) {
var a, o, r, r1, _i, _len;
if (f == null) {
f = this.identity;
}
if (valueToo == null) {
valueToo = false;
}
if (this.empty(array)) {
this.error("minOneOf: empty array");
}
r = Infinity;
o = null;
if (this.isString(f)) {
f = this.propFcn(f);
}
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
if ((r1 = f(a)) < r) {
r = r1;
o = a;
}
}
if (valueToo) {
return [o, r];
} else {
return o;
}
},
maxOneOf: function(array, f, valueToo) {
var a, o, r, r1, _i, _len;
if (f == null) {
f = this.identity;
}
if (valueToo == null) {
valueToo = false;
}
if (this.empty(array)) {
this.error("maxOneOf: empty array");
}
r = -Infinity;
o = null;
if (this.isString(f)) {
f = this.propFcn(f);
}
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
if ((r1 = f(a)) > r) {
r = r1;
o = a;
}
}
if (valueToo) {
return [o, r];
} else {
return o;
}
},
firstOneOf: function(array, f) {
var a, i, _i, _len;
for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) {
a = array[i];
if (f(a)) {
return i;
}
}
return -1;
},
histOf: function(array, bin, f) {
var a, i, r, ri, val, _i, _j, _len, _len1;
if (bin == null) {
bin = 1;
}
if (f == null) {
f = function(i) {
return i;
};
}
r = [];
if (this.isString(f)) {
f = this.propFcn(f);
}
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
i = Math.floor(f(a) / bin);
r[i] = (ri = r[i]) != null ? ri + 1 : 1;
}
for (i = _j = 0, _len1 = r.length; _j < _len1; i = ++_j) {
val = r[i];
if (val == null) {
r[i] = 0;
}
}
return r;
},
sortBy: function(array, f) {
if (this.isString(f)) {
f = this.propFcn(f);
}
return array.sort(function(a, b) {
return f(a) - f(b);
});
},
sortNums: function(array, ascending) {
var f;
if (ascending == null) {
ascending = true;
}
f = ascending ? function(a, b) {
return a - b;
} : function(a, b) {
return b - a;
};
if (array.sort != null) {
return array.sort(f);
} else {
return Array.prototype.sort.call(array, f);
}
},
uniq: function(array) {
var i, _i, _ref;
if (array.length < 2) {
return array;
}
for (i = _i = _ref = array.length - 1; _i >= 1; i = _i += -1) {
if (array[i - 1] === array[i]) {
array.splice(i, 1);
}
}
return array;
},
flatten: function(matrix) {
return matrix.reduce(function(a, b) {
return a.concat(b);
});
},
aProp: function(array, propOrFn) {
var a, _i, _j, _len, _len1, _results, _results1;
if (typeof propOrFn === 'function') {
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
_results.push(propOrFn(a));
}
return _results;
} else {
_results1 = [];
for (_j = 0, _len1 = array.length; _j < _len1; _j++) {
a = array[_j];
_results1.push(a[propOrFn]);
}
return _results1;
}
},
aToObj: function(array, names) {
var i, n, _i, _len;
for (i = _i = 0, _len = names.length; _i < _len; i = ++_i) {
n = names[i];
array[n] = array[i];
}
return array;
},
aMax: function(array) {
var a, v, _i, _len;
v = array[0];
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
v = Math.max(v, a);
}
return v;
},
aMin: function(array) {
var a, v, _i, _len;
v = array[0];
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
v = Math.min(v, a);
}
return v;
},
aSum: function(array) {
var a, v, _i, _len;
v = 0;
for (_i = 0, _len = array.length; _i < _len; _i++) {
a = array[_i];
v += a;
}
return v;
},
aAvg: function(array) {
return this.aSum(array) / array.length;
},
aMid: function(array) {
array = array.sort != null ? this.clone(array) : this.typedToJS(array);
this.sortNums(array);
return array[Math.floor(array.length / 2)];
},
aStats: function(array) {
var avg, max, mid, min;
min = this.aMin(array);
max = this.aMax(array);
avg = this.aAvg(array);
mid = this.aMid(array);
return {
min: min,
max: max,
avg: avg,
mid: mid
};
},
aNaNs: function(array) {
var i, v, _i, _len, _results;
_results = [];
for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) {
v = array[i];
if (isNaN(v)) {
_results.push(i);
}
}
return _results;
},
aRamp: function(start, stop, numItems, useInts) {
var array, num, step;
if (useInts == null) {
useInts = false;
}
step = (stop - start) / (numItems - 1);
array = (function() {
var _i, _results;
_results = [];
for (num = _i = start; step > 0 ? _i <= stop : _i >= stop; num = _i += step) {
_results.push(num);
}
return _results;
})();
if (useInts) {
array = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
num = array[_i];
_results.push(Math.round(num));
}
return _results;
})();
}
return array;
},
aRange: function(start, stop) {
var _i, _results;
return (function() {
_results = [];
for (var _i = start; start <= stop ? _i <= stop : _i >= stop; start <= stop ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this);
},
aPairwise: function(a1, a2, f) {
var i, v, _i, _len, _results;
v = 0;
_results = [];
for (i = _i = 0, _len = a1.length; _i < _len; i = ++_i) {
v = a1[i];
_results.push(f(v, a2[i]));
}
return _results;
},
aPairSum: function(a1, a2) {
return this.aPairwise(a1, a2, function(a, b) {
return a + b;
});
},
aPairDif: function(a1, a2) {
return this.aPairwise(a1, a2, function(a, b) {
return a - b;
});
},
aPairMul: function(a1, a2) {
return this.aPairwise(a1, a2, function(a, b) {
return a * b;
});
},
typedToJS: function(typedArray) {
var i, _i, _len, _results;
_results = [];
for (_i = 0, _len = typedArray.length; _i < _len; _i++) {
i = typedArray[_i];
_results.push(i);
}
return _results;
},
lerp: function(lo, hi, scale) {
if (lo <= hi) {
return lo + (hi - lo) * scale;
} else {
return lo - (lo - hi) * scale;
}
},
lerpScale: function(number, lo, hi) {
return (number - lo) / (hi - lo);
},
lerp2: function(x0, y0, x1, y1, scale) {
return [this.lerp(x0, x1, scale), this.lerp(y0, y1, scale)];
},
normalize: function(array, lo, hi) {
var max, min, num, scale, _i, _len, _results;
if (lo == null) {
lo = 0;
}
if (hi == null) {
hi = 1;
}
min = this.aMin(array);
max = this.aMax(array);
scale = 1 / (max - min);
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
num = array[_i];
_results.push(this.lerp(lo, hi, scale * (num - min)));
}
return _results;
},
normalize8: function(array) {
return new Uint8ClampedArray(this.normalize(array, -.5, 255.5));
},
normalizeInt: function(array, lo, hi) {
var i, _i, _len, _ref, _results;
_ref = this.normalize(array, lo, hi);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
_results.push(Math.round(i));
}
return _results;
},
sortedIndex: function(array, item, f) {
var high, low, mid, value;
if (f == null) {
f = function(o) {
return o;
};
}
if (this.isString(f)) {
f = this.propFcn(f);
}
value = f(item);
low = 0;
high = array.length;
while (low < high) {
mid = (low + high) >>> 1;
if (f(array[mid]) < value) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
},
identity: function(o) {
return o;
},
propFcn: function(prop) {
return function(o) {
return o[prop];
};
},
indexOf: function(array, item, property) {
var i;
if (property != null) {
i = this.sortedIndex(array, item, property === "" ? null : property);
if (array[i] === item) {
return i;
} else {
return -1;
}
} else {
return array.indexOf(item);
}
},
radsToward: function(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
},
inCone: function(heading, cone, radius, x1, y1, x2, y2) {
var angle12;
if (radius < this.distance(x1, y1, x2, y2)) {
return false;
}
angle12 = this.radsToward(x1, y1, x2, y2);
return cone / 2 >= Math.abs(this.subtractRads(heading, angle12));
},
distance: function(x1, y1, x2, y2) {
var dx, dy;
dx = x1 - x2;
dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
},
sqDistance: function(x1, y1, x2, y2) {
var dx, dy;
dx = x1 - x2;
dy = y1 - y2;
return dx * dx + dy * dy;
},
polarToXY: function(r, theta, x, y) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
return [x + r * Math.cos(theta), y + r * Math.sin(theta)];
},
torusDistance: function(x1, y1, x2, y2, w, h) {
return Math.sqrt(this.torusSqDistance(x1, y1, x2, y2, w, h));
},
torusSqDistance: function(x1, y1, x2, y2, w, h) {
var dx, dxMin, dy, dyMin;
dx = Math.abs(x2 - x1);
dy = Math.abs(y2 - y1);
dxMin = Math.min(dx, w - dx);
dyMin = Math.min(dy, h - dy);
return dxMin * dxMin + dyMin * dyMin;
},
torusWraps: function(x1, y1, x2, y2, w, h) {
var dx, dy;
dx = Math.abs(x2 - x1);
dy = Math.abs(y2 - y1);
return dx > w - dx || dy > h - dy;
},
torus4Pts: function(x1, y1, x2, y2, w, h) {
var x2r, y2r;
x2r = x2 < x1 ? x2 + w : x2 - w;
y2r = y2 < y1 ? y2 + h : y2 - h;
return [[x2, y2], [x2r, y2], [x2, y2r], [x2r, y2r]];
},
torusPt: function(x1, y1, x2, y2, w, h) {
var x, x2r, y, y2r;
x2r = x2 < x1 ? x2 + w : x2 - w;
y2r = y2 < y1 ? y2 + h : y2 - h;
x = Math.abs(x2r - x1) < Math.abs(x2 - x1) ? x2r : x2;
y = Math.abs(y2r - y1) < Math.abs(y2 - y1) ? y2r : y2;
return [x, y];
},
torusRadsToward: function(x1, y1, x2, y2, w, h) {
var _ref;
_ref = this.torusPt(x1, y1, x2, y2, w, h), x2 = _ref[0], y2 = _ref[1];
return this.radsToward(x1, y1, x2, y2);
},
inTorusCone: function(heading, cone, radius, x1, y1, x2, y2, w, h) {
var p, _i, _len, _ref;
_ref = this.torus4Pts(x1, y1, x2, y2, w, h);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
p = _ref[_i];
if (this.inCone(heading, cone, radius, x1, y1, p[0], p[1])) {
return true;
}
}
return false;
},
fileIndex: {},
importImage: function(name, f) {
var img;
if (f == null) {
f = function() {};
}
if ((img = this.fileIndex[name]) != null) {
f(img);
} else {
this.fileIndex[name] = img = new Image();
img.isDone = false;
img.crossOrigin = "Anonymous";
img.onload = function() {
f(img);
return img.isDone = true;
};
img.src = name;
}
return img;
},
xhrLoadFile: function(name, method, type, f) {
var xhr;
if (method == null) {
method = "GET";
}
if (type == null) {
type = "text";
}
if (f == null) {
f = function() {};
}
if ((xhr = this.fileIndex[name]) != null) {
f(xhr.response);
} else {
this.fileIndex[name] = xhr = new XMLHttpRequest();
xhr.isDone = false;
xhr.open(method, name);
xhr.responseType = type;
xhr.onload = function() {
f(xhr.response);
return xhr.isDone = true;
};
xhr.send();
}
return xhr;
},
filesLoaded: function(files) {
var array, v;
if (files == null) {
files = this.fileIndex;
}
array = (function() {
var _i, _len, _ref, _results;
_ref = this.ownValues(files);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
v = _ref[_i];
_results.push(v.isDone);
}
return _results;
}).call(this);
return array.reduce((function(a, b) {
return a && b;
}), true);
},
waitOnFiles: function(f, files) {
if (files == null) {
files = this.fileIndex;
}
return this.waitOn(((function(_this) {
return function() {
return _this.filesLoaded(files);
};
})(this)), f);
},
waitOn: function(done, f) {
if (done()) {
return f();
} else {
return setTimeout(((function(_this) {
return function() {
return _this.waitOn(done, f);
};
})(this)), 1000);
}
},
cloneImage: function(img) {
var i;
(i = new Image()).src = img.src;
return i;
},
imageToData: function(img, f, arrayType) {
if (f == null) {
f = this.pixelByte(0);
}
if (arrayType == null) {
arrayType = Uint8ClampedArray;
}
return this.imageRowsToData(img, img.height, f, arrayType);
},
imageRowsToData: function(img, rowsPerSlice, f, arrayType) {
var ctx, data, dataStart, i, idata, rows, rowsDone, _i, _ref;
if (f == null) {
f = this.pixelByte(0);
}
if (arrayType == null) {
arrayType = Uint8ClampedArray;
}
rowsDone = 0;
data = new arrayType(img.width * img.height);
while (rowsDone < img.height) {
rows = Math.min(img.height - rowsDone, rowsPerSlice);
ctx = this.imageSliceToCtx(img, 0, rowsDone, img.width, rows);
idata = this.ctxToImageData(ctx).data;
dataStart = rowsDone * img.width;
for (i = _i = 0, _ref = idata.length / 4; _i < _ref; i = _i += 1) {
data[dataStart + i] = f(idata, 4 * i);
}
rowsDone += rows;
}
return data;
},
pixelBytesToInt: function(a) {
var ImageByteFmts;
ImageByteFmts = [[2], [1, 2], [0, 1, 2], [3, 0, 1, 2]];
if (typeof a === "number") {
a = ImageByteFmts[a - 1];
}
return function(id, i) {
var j, val, _i, _len;
val = 0;
for (_i = 0, _len = a.length; _i < _len; _i++) {
j = a[_i];
val = val * 256 + id[i + j];
}
return val;
};
},
pixelByte: function(n) {
return function(id, i) {
return id[i + n];
};
},
createCanvas: function(width, height) {
var can;
can = document.createElement('canvas');
can.width = width;
can.height = height;
return can;
},
createCtx: function(width, height, ctxType) {
var can, _ref;
if (ctxType == null) {
ctxType = "2d";
}
can = this.createCanvas(width, height);
if (ctxType === "2d") {
return can.getContext("2d");
} else {
return (_ref = can.getContext("webgl")) != null ? _ref : can.getContext("experimental-webgl");
}
},
createLayer: function(div, width, height, z, ctx) {
var element;
if (ctx == null) {
ctx = "2d";
}
if (ctx === "img") {
element = ctx = new Image();
ctx.width = width;
ctx.height = height;
} else {
element = (ctx = this.createCtx(width, height, ctx)).canvas;
}
this.insertLayer(div, element, width, height, z);
return ctx;
},
insertLayer: function(div, element, w, h, z) {
element.setAttribute('style', "position:absolute;top:0;left:0;width:" + w + ";height:" + h + ";z-index:" + z);
return div.appendChild(element);
},
setCtxSmoothing: function(ctx, smoothing) {
ctx.imageSmoothingEnabled = smoothing;
ctx.mozImageSmoothingEnabled = smoothing;
ctx.oImageSmoothingEnabled = smoothing;
return ctx.webkitImageSmoothingEnabled = smoothing;
},
setIdentity: function(ctx) {
ctx.save();
return ctx.setTransform(1, 0, 0, 1, 0, 0);
},
clearCtx: function(ctx) {
if (ctx.save != null) {
this.setIdentity(ctx);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
return ctx.restore();
} else {
ctx.clearColor(0, 0, 0, 0);
return ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT);
}
},
fillCtx: function(ctx, color) {
if (ctx.fillStyle != null) {
this.setIdentity(ctx);
ctx.fillStyle = this.colorStr(color);
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
return ctx.restore();
} else {
ctx.clearColor.apply(ctx, __slice.call(color).concat([1]));
return ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT);
}
},
ctxDrawText: function(ctx, string, x, y, color, setIdentity) {
if (color == null) {
color = [0, 0, 0];
}
if (setIdentity == null) {
setIdentity = true;
}
if (setIdentity) {
this.setIdentity(ctx);
}
ctx.fillStyle = this.colorStr(color);
ctx.fillText(string, x, y);
if (setIdentity) {
return ctx.restore();
}
},
ctxTextParams: function(ctx, font, align, baseline) {
if (align == null) {
align = "center";
}
if (baseline == null) {
baseline = "middle";
}
ctx.font = font;
ctx.textAlign = align;
return ctx.textBaseline = baseline;
},
elementTextParams: function(e, font, align, baseline) {
if (align == null) {
align = "center";
}
if (baseline == null) {
baseline = "middle";
}
if (e.canvas != null) {
e = e.canvas;
}
e.style.font = font;
e.style.textAlign = align;
return e.style.textBaseline = baseline;
},
imageToCtx: function(img, w, h) {
var ctx;
if ((w != null) && (h != null)) {
ctx = this.createCtx(w, h);
ctx.drawImage(img, 0, 0, w, h);
} else {
ctx = this.createCtx(img.width, img.height);
ctx.drawImage(img, 0, 0);
}
return ctx;
},
imageSliceToCtx: function(img, sx, sy, sw, sh, ctx) {
if (ctx != null) {
ctx.canvas.width = sw;
ctx.canvas.height = sh;
} else {
ctx = this.createCtx(sw, sh);
}
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
return ctx;
},
imageToCtxDownStepped: function(img, tw, th) {
var can, ctx, ctx1, h, ihalf, step, steps, w, _i;
ctx1 = this.createCtx(tw, th);
w = img.width;
h = img.height;
ihalf = function(n) {
return Math.ceil(n / 2);
};
steps = Math.ceil(this.log2((w / tw) > (h / th) ? w / tw : h / th));
console.log("steps", steps);
if (steps <= 1) {
ctx1.drawImage(img, 0, 0, tw, th);
} else {
console.log("img w/h", w, h, "->", ihalf(w), ihalf(h));
ctx = this.createCtx(w = ihalf(w), h = ihalf(h));
can = ctx.canvas;
ctx.drawImage(img, 0, 0, w, h);
for (step = _i = steps; steps <= 2 ? _i < 2 : _i > 2; step = steps <= 2 ? ++_i : --_i) {
console.log("can w/h", w, h, "->", ihalf(w), ihalf(h));
ctx.drawImage(can, 0, 0, w, h, 0, 0, w = ihalf(w), h = ihalf(h));
}
console.log("target w/h", w, h, "->", tw, th);
ctx1.drawImage(can, 0, 0, w, h, 0, 0, tw, th);
}
return ctx1;
},
ctxToDataUrl: function(ctx) {
return ctx.canvas.toDataURL("image/png");
},
ctxToDataUrlImage: function(ctx, f) {
var img;
img = new Image();
if (f != null) {
img.onload = function() {
return f(img);
};
}
img.src = ctx.canvas.toDataURL("image/png");
return img;
},
ctxToImageData: function(ctx) {
return ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
},
drawCenteredImage: function(ctx, img, rad, x, y, dx, dy) {
ctx.translate(x, y);
ctx.rotate(rad);
return ctx.drawImage(img, -dx / 2, -dy / 2);
},
copyCtx: function(ctx0) {
var ctx;
ctx = this.createCtx(ctx0.canvas.width, ctx0.canvas.height);
ctx.drawImage(ctx0.canvas, 0, 0);
return ctx;
},
resizeCtx: function(ctx, width, height, scale) {
var copy;
if (scale == null) {
scale = false;
}
copy = this.copyCtx(ctx);
ctx.canvas.width = width;
ctx.canvas.height = height;
return ctx.drawImage(copy.canvas, 0, 0);
}
};
Evented = (function() {
function Evented() {
this.events = {};
}
Evented.prototype.emit = function() {
var args, cb, name, _i, _len, _ref, _results;
name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (this.events[name]) {
_ref = this.events[name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cb = _ref[_i];
_results.push(cb.apply(null, args));
}
return _results;
}
};
Evented.prototype.on = function(name, cb) {
var _base;
return ((_base = this.events)[name] != null ? _base[name] : _base[name] = []).push(cb);
};
Evented.prototype.off = function(name, cb) {
var l;
if (this.events[name]) {
if (cb) {
return this.events[name] = (function() {
var _i, _len, _ref, _results;
_ref = this.events[name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
if (l !== cb) {
_results.push(l);
}
}
return _results;
}).call(this);
} else {
return delete this.events[name];
}
}
};
return Evented;
})();
Color = {
rgbString: function(r, g, b, a) {
if (a == null) {
a = 1;
}
if (a > 1) {
throw new Error("alpha > 1");
}
if (a === 1) {
return "rgb(" + r + "," + g + "," + b + ")";
} else {
return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
},
rgbIntensity: function(r, g, b) {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
},
rgbToHex: function(r, g, b) {
return "#" + (0x1000000 | (b | g << 8 | r << 16)).toString(16).slice(-6);
},
typedArrayColor: function(r, g, b, a) {
var pixel, rgba;
if (a == null) {
a = 255;
}
rgba = new Uint8ClampedArray([r, g, b, a]);
pixel = new Uint32Array(rgba.buffer)[0];
return {
pixel: pixel,
rgba: rgba
};
},
ctx1x1: u.createCtx(1, 1),
stringToRGB: function(string) {
var a, b, g, r, _ref;
this.ctx1x1.fillStyle = string;
this.ctx1x1.fillRect(0, 0, 1, 1);
_ref = this.ctx1x1.getImageData(0, 0, 1, 1).data, r = _ref[0], g = _ref[1], b = _ref[2], a = _ref[3];
if ((r + g + b !== 0) || (string.match(/^black$/i)) || (string === "#000" || string === "#000000") || (string.match(/rgba{0,1}\(0,0,0/i)) || (string.match(/hsla{0,1}\(0,0%,0%/i))) {
return [r, g, b];
}
return null;
},
rgbToHsv: function(r, g, b) {
var d, h, max, min, s, v;
r = r / 255;
g = g / 255;
b = b / 255;
max = Math.max(r, g, b);
min = Math.min(r, g, b);
v = max;
h = 0;
d = max - min;
s = max === 0 ? 0 : d / max;
if (max !== min) {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
}
}
return [Math.round(255 * h / 6), Math.round(255 * s), Math.round(255 * v)];
},
hsvToRgb: function(h, s, v) {
var b, f, g, i, p, q, r, t;
h = h / 255;
s = s / 255;
v = v / 255;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
},
randomColor: function() {
var i, _i, _results;
_results = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
_results.push(u.randomInt(256));
}
return _results;
},
rgbDistance: function(r1, g1, b1, r2, g2, b2) {
var db, dg, dr, rMean, _ref;
rMean = Math.round((r1 + r2) / 2);
_ref = [r1 - r2, g1 - g2, b1 - b2], dr = _ref[0], dg = _ref[1], db = _ref[2];
return Math.sqrt((((512 + rMean) * dr * dr) >> 8) + (4 * dg * dg) + (((767 - rMean) * db * db) >> 8));
},
rgbLerp: function(value, min, max, rgb1, rgb0) {
var i, scale, _i, _results;
if (rgb0 == null) {
rgb0 = [0, 0, 0];
}
scale = u.lerpScale(value, min, max);
_results = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
_results.push(Math.round(u.lerp(rgb0[i], rgb1[i], scale)));
}
return _results;
},
options: function() {
return {
rgb: true,
hsv: true,
pixel: true,
rgbString: true,
hexString: true,
intensity: true
};
},
colorObject: function(r, g, b, a, opt) {
var o, pixel, rgba, _ref, _ref1, _ref2;
if (a == null) {
a = 1;
}
if (opt == null) {
opt = this.options();
}
o = {
r: r,
g: g,
b: b,
a: a
};
if (opt.rgb) {
o.rgb = [r, g, b];
}
if (opt.hsv) {
o.hsv = this.rgbToHsv(r, g, b);
_ref = o.hsv, o.h = _ref[0], o.s = _ref[1], o.v = _ref[2];
}
if (opt.pixel) {
o.a255 = Math.round(a * 255);
_ref1 = this.typedArrayColor(r, g, b, o.a255), pixel = _ref1.pixel, rgba = _ref1.rgba;
_ref2 = [pixel, rgba], o.pixel = _ref2[0], o.rgba = _ref2[1];
}
if (opt.rgbString) {
o.rgbString = this.rgbString(r, g, b, a);
}
if (opt.hexString) {
o.hexString = this.rgbToHex(r, g, b);
}
if (opt.intensity) {
o.intensity = this.rgbIntensity(r, g, b);
}
return o;
},
ColorMap: ColorMap = (function(_super) {
__extends(ColorMap, _super);
function ColorMap(rgbArray, options, dupsOK) {
var i, rgb, _i, _len;
this.options = options != null ? options : Color.options();
this.dupsOK = dupsOK != null ? dupsOK : false;
ColorMap.__super__.constructor.call(this, 0);
this.rgbIndex = {};
this.nameIndex = {};
for (i = _i = 0, _len = rgbArray.length; _i < _len; i = ++_i) {
rgb = rgbArray[i];
this.addColor.apply(this, rgb);
}
}
ColorMap.prototype.addColor = function(r, g, b, a) {
var color, rgbString;
if (a == null) {
a = 1;
}
rgbString = Color.rgbString(r, g, b, a);
if (!this.dupsOK) {
color = this.rgbIndex[rgbString];
if (color) {
console.log("dup color", color);
}
}
if (!color) {
color = Color.colorObject(r, g, b, a, this.options);
color.ix = this.length;
color.map = this;
this.rgbIndex[rgbString] = color;
this.push(color);
}
return color;
};
ColorMap.prototype.sort = function(f) {
var color, i, _i, _len;
ColorMap.__super__.sort.call(this, f);
for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
color = this[i];
color.ix = i;
}
return this;
};
ColorMap.prototype.sortBy = function(key, ascenting) {
var compare;
if (ascenting == null) {
ascenting = true;
}
compare = function(a, b) {
if (ascenting) {
return a[key] - b[key];
} else {
return b[key] - a[key];
}
};
return this.sort(compare);
};
ColorMap.prototype.findRGB = function(r, g, b, a) {
if (a == null) {
a = 1;
}
return this.rgbIndex[Color.rgbString(r, g, b, a)];
};
ColorMap.prototype.findKey = function(key, value) {
var color, i, _i, _len;
for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
color = this[i];
if (color[key] === value) {
return color;
}
}
return void 0;
};
ColorMap.prototype.randomIndex = function() {
return u.randomInt(this.length);
};
ColorMap.prototype.randomColor = function() {
return this[this.randomIndex()];
};
ColorMap.prototype.scaleColor = function(number, min, max, minColor, maxColor) {
var index, scale;
if (minColor == null) {
minColor = 0;
}
if (maxColor == null) {
maxColor = this.length - 1;
}
scale = u.lerpScale(number, min, max);
if (minColor.ix != null) {
minColor = minColor.ix;
}
if (maxColor.ix != null) {
maxColor = maxColor.ix;
}
index = Math.round(u.lerp(minColor, maxColor, scale));
return this[index];
};
ColorMap.prototype.findClosest = function(r, g, b) {
var color, d, i, ixMin, minDist, _i, _len;
if ((color = this.findRGB(r, g, b))) {
return color;
}
minDist = Infinity;
ixMin = 0;
for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
color = this[i];
d = Color.rgbDistance.apply(Color, __slice.call(color.rgb).concat([r], [g], [b]));
if (d < minDist) {
minDist = d;
ixMin = i;
}
}
return this[ixMin];
};
return ColorMap;
})(Array),
intensityArray: function(size) {
var i, _i, _results;
if (size == null) {
size = 256;
}
_results = [];
for (i = _i = 0; 0 <= size ? _i < size : _i > size; i = 0 <= size ? ++_i : --_i) {
_results.push(Math.round(i * 255 / (size - 1)));
}
return _results;
},
grayColorArray: function(size) {
var i, _i, _len, _ref, _results;
if (size == null) {
size = 256;
}
_ref = this.intensityArray(size);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
_results.push([i, i, i]);
}
return _results;
},
grayColorMap: function(size, options) {
var i;
if (size == null) {
size = 256;
}
return new ColorMap((function() {
var _i, _len, _ref, _results;
_ref = this.intensityArray(size);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
_results.push([i, i, i]);
}
return _results;
}).call(this), options);
},
threeArrays: function(A1, A2, A3) {
var A, _ref;
if (A2 == null) {
A2 = A1;
}
if (A3 == null) {
A3 = A1;
}
_ref = (function() {
var _i, _len, _ref, _results;
_ref = [A1, A2, A3];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
A = _ref[_i];
if (A === 1) {
A = [255];
}
if (typeof A === "number") {
_results.push(u.aRamp(0, 255, A, true));
} else {
_results.push(A);
}
}
return _results;
})(), A1 = _ref[0], A2 = _ref[1], A3 = _ref[2];
return [A1, A2, A3];
},
rgbColorArray: function(R, G, B) {
var array, b, g, r, _i, _j, _k, _len, _len1, _len2, _ref;
if (G == null) {
G = R;
}
if (B == null) {
B = R;
}
_ref = this.threeArrays(R, G, B), R = _ref[0], G = _ref[1], B = _ref[2];
array = [];
for (_i = 0, _len = R.length; _i < _len; _i++) {
r = R[_i];
for (_j = 0, _len1 = G.length; _j < _len1; _j++) {
g = G[_j];
for (_k = 0, _len2 = B.length; _k < _len2; _k++) {
b = B[_k];
array.push([r, g, b]);
}
}
}
return array;
},
rgbColorMap: function(R, G, B, options) {
if (G == null) {
G = R;
}
if (B == null) {
B = R;
}
return new ColorMap(this.rgbColorArray(R, G, B), options);
},
hsvColorArray: function(H, S, V) {
var a, array, h, s, v, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _results;
if (S == null) {
S = H;
}
if (V == null) {
V = H;
}
_ref = this.threeArrays(H, S, V), H = _ref[0], S = _ref[1], V = _ref[2];
array = [];
for (_i = 0, _len = V.length; _i < _len; _i++) {
v = V[_i];
for (_j = 0, _len1 = S.length; _j < _len1; _j++) {
s = S[_j];
for (_k = 0, _len2 = H.length; _k < _len2; _k++) {
h = H[_k];
array.push([h, s, v]);
}
}
}
_results = [];
for (_l = 0, _len3 = array.length; _l < _len3; _l++) {
a = array[_l];
_results.push(this.hsvToRgb.apply(this, a));
}
return _results;
},
hsvColorMap: function(H, S, V, options) {
if (S == null) {
S = [255];
}
if (V == null) {
V = H;
}
return new ColorMap(this.hsvColorArray(H, S, V), options);
},
gradientColorArray: function(nColors, stops, locs) {
var ctx, grad, i, id, _i, _j, _ref, _ref1, _results;
if (locs == null) {
locs = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
_results.push(i / (stops.length - 1));
}
return _results;
})();
}
ctx = u.createCtx(nColors, 1);
grad = ctx.createLinearGradient(0, 0, nColors, 0);
for (i = _i = 0, _ref = stops.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
grad.addColorStop(locs[i], this.rgbString.apply(this, stops[i]));
}
ctx.fillStyle = grad;
ctx.fillRect(0, 0, nColors, 1);
id = u.ctxToImageData(ctx).data;
_results = [];
for (i = _j = 0, _ref1 = id.length; _j < _ref1; i = _j += 4) {
_results.push([id[i], id[i + 1], id[i + 2]]);
}
return _results;
},
gradientColorMap: function(nColors, stops, locs, options) {
return new ColorMap(this.gradientColorArray(nColors, stops, locs), options);
},
nameColorMap: function(colorPairs, options) {
var color, i, k, map, name, names, rgbs, v, _i, _len;
rgbs = (function() {
var _results;
_results = [];
for (k in colorPairs) {
v = colorPairs[k];
_results.push(v);
}
return _results;
})();
names = (function() {
var _results;
_results = [];
for (k in colorPairs) {
v = colorPairs[k];
_results.push(k);
}
return _results;
})();
map = new ColorMap(rgbs, options, true);
for (i = _i = 0, _len = map.length; _i < _len; i = ++_i) {
color = map[i];
name = names[i];
map.nameIndex[name] = color;
}
return map;
},
randomColorArray: function(nColors) {
var i, rand255, _i, _results;
rand255 = function() {
return u.randomInt(256);
};
_results = [];
for (i = _i = 0; 0 <= nColors ? _i < nColors : _i > nColors; i = 0 <= nColors ? ++_i : --_i) {
_results.push([rand255(), rand255(), rand255()]);
}
return _results;
},
randomColorMap: function(nColors, options) {
return new ColorMap(this.randomColorArray(nColors), options);
}
};
shapes = Shapes = (function() {
var ccirc, cimg, circ, csq, fillSlot, poly, spriteSheets;
poly = function(c, a) {
var i, p, _i, _len;
for (i = _i = 0, _len = a.length; _i < _len; i = ++_i) {
p = a[i];
if (i === 0) {
c.moveTo(p[0], p[1]);
} else {
c.lineTo(p[0], p[1]);
}
}
return null;
};
circ = function(c, x, y, s) {
return c.arc(x, y, s / 2, 0, 2 * Math.PI);
};
ccirc = function(c, x, y, s) {
return c.arc(x, y, s / 2, 0, 2 * Math.PI, true);
};
cimg = function(c, x, y, s, img) {
c.scale(1, -1);
c.drawImage(img, x - s / 2, y - s / 2, s, s);
return c.scale(1, -1);
};
csq = function(c, x, y, s) {
return c.fillRect(x - s / 2, y - s / 2, s, s);
};
fillSlot = function(slot, img) {
slot.ctx.save();
slot.ctx.scale(1, -1);
slot.ctx.drawImage(img, slot.x, -(slot.y + slot.spriteSize), slot.spriteSize, slot.spriteSize);
return slot.ctx.restore();
};
spriteSheets = [];
return {
"default": {
rotate: true,
draw: function(c) {
return poly(c, [[.5, 0], [-.5, -.5], [-.25, 0], [-.5, .5]]);
}
},
triangle: {
rotate: true,
draw: function(c) {
return poly(c, [[.5, 0], [-.5, -.4], [-.5, .4]]);
}
},
arrow: {
rotate: true,
draw: function(c) {
return poly(c, [[.5, 0], [0, .5], [0, .2], [-.5, .2], [-.5, -.2], [0, -.2], [0, -.5]]);
}
},
bug: {
rotate: true,
draw: function(c) {
c.strokeStyle = c.fillStyle;
c.lineWidth = .05;
poly(c, [[.4, .225], [.2, 0], [.4, -.225]]);
c.stroke();
c.beginPath();
circ(c, .12, 0, .26);
circ(c, -.05, 0, .26);
return circ(c, -.27, 0, .4);
}
},
pyramid: {
rotate: false,
draw: function(c) {
return poly(c, [[0, .5], [-.433, -.25], [.433, -.25]]);
}
},
circle: {
shortcut: function(c, x, y, s) {
c.beginPath();
circ(c, x, y, s);
c.closePath();
return c.fill();
},
rotate: false,
draw: function(c) {
return circ(c, 0, 0, 1);
}
},
square: {
shortcut: function(c, x, y, s) {
return csq(c, x, y, s);
},
rotate: false,
draw: function(c) {
return csq(c, 0, 0, 1);
}
},
pentagon: {
rotate: false,
draw: function(c) {
return poly(c, [[0, .45], [-.45, .1], [-.3, -.45], [.3, -.45], [.45, .1]]);
}
},
ring: {
rotate: false,
draw: function(c) {
circ(c, 0, 0, 1);
c.closePath();
return ccirc(c, 0, 0, .6);
}
},
filledRing: {
rotate: false,
draw: function(c) {
var tempStyle;
circ(c, 0, 0, 1);
tempStyle = c.fillStyle;
c.fillStyle = c.strokeStyle;
c.fill();
c.fillStyle = tempStyle;
c.beginPath();
return circ(c, 0, 0, .8);
}
},
person: {
rotate: false,
draw: function(c) {
poly(c, [[.15, .2], [.3, 0], [.125, -.1], [.125, .05], [.1, -.15], [.25, -.5], [.05, -.5], [0, -.25], [-.05, -.5], [-.25, -.5], [-.1, -.15], [-.125, .05], [-.125, -.1], [-.3, 0], [-.15, .2]]);
c.closePath();
return circ(c, 0, .35, .30);
}
},
names: function() {
var name, val, _results;
_results = [];
for (name in this) {
if (!__hasProp.call(this, name)) continue;
val = this[name];
if ((val.rotate != null) && (val.draw != null)) {
_results.push(name);
}
}
return _results;
},
add: function(name, rotate, draw, shortcut) {
var s;
s = this[name] = u.isFunction(draw) ? {
rotate: rotate,
draw: draw
} : {
rotate: rotate,
img: draw,
draw: function(c) {
return cimg(c, .5, .5, 1, this.img);
}
};
if ((s.img != null) && !s.rotate) {
s.shortcut = function(c, x, y, s) {
return cimg(c, x, y, s, this.img);
};
}
if (shortcut != null) {
return s.shortcut = shortcut;
}
},
poly: poly,
circ: circ,
ccirc: ccirc,
cimg: cimg,
csq: csq,
spriteSheets: spriteSheets,
draw: function(ctx, shape, x, y, size, rad, color, strokeColor) {
if (shape.shortcut != null) {
if (shape.img == null) {
ctx.fillStyle = u.colorStr(color);
}
shape.shortcut(ctx, x, y, size);
} else {
ctx.save();
ctx.translate(x, y);
if (size !== 1) {
ctx.scale(size, size);
}
if (rad !== 0) {
ctx.rotate(rad);
}
if (shape.img != null) {
shape.draw(ctx);
} else {
ctx.fillStyle = u.colorStr(color);
if (strokeColor) {
ctx.strokeStyle = u.colorStr(strokeColor);
ctx.lineWidth = 0.05;
}
ctx.save();
ctx.beginPath();
shape.draw(ctx);
ctx.closePath();
ctx.restore();
ctx.fill();
if (strokeColor) {
ctx.stroke();
}
}
ctx.restore();
}
return shape;
},
drawSprite: function(ctx, s, x, y, size, rad) {
if (rad === 0) {
ctx.drawImage(s.ctx.canvas, s.x, s.y, s.spriteSize, s.spriteSize, x - size / 2, y - size / 2, size, size);
} else {
ctx.save();
ctx.translate(x, y);
ctx.rotate(rad);
ctx.drawImage(s.ctx.canvas, s.x, s.y, s.spriteSize, s.spriteSize, -size / 2, -size / 2, size, size);
ctx.restore();
}
return s;
},
shapeToSprite: function(name, color, size, strokeColor) {
var ctx, foundSlot, img, index, shape, slot, slotSize, spriteSize, strokePadding, x, y;
spriteSize = Math.ceil(size);
strokePadding = 4;
slotSize = spriteSize + strokePadding;
shape = this[name];
index = shape.img != null ? name : "" + name + "-" + (u.colorStr(color));
ctx = spriteSheets[slotSize];
if (ctx == null) {
spriteSheets[slotSize] = ctx = u.createCtx(slotSize * 10, slotSize);
ctx.nextX = 0;
ctx.nextY = 0;
ctx.index = {};
}
if ((foundSlot = ctx.index[index]) != null) {
return foundSlot;
}
if (slotSize * ctx.nextX === ctx.canvas.width) {
u.resizeCtx(ctx, ctx.canvas.width, ctx.canvas.height + slotSize);
ctx.nextX = 0;
ctx.nextY++;
}
x = slotSize * ctx.nextX + strokePadding / 2;
y = slotSize * ctx.nextY + strokePadding / 2;
slot = {
ctx: ctx,
x: x,
y: y,
size: size,
spriteSize: spriteSize,
name: name,
color: color,
strokeColor: strokeColor,
index: index
};
ctx.index[index] = slot;
if ((img = shape.img) != null) {
if (img.height !== 0) {
fillSlot(slot, img);
} else {
img.onload = function() {
return fillSlot(slot, img);
};
}
} else {
ctx.save();
ctx.translate((ctx.nextX + 0.5) * slotSize, (ctx.nextY + 0.5) * slotSize);
ctx.scale(spriteSize, spriteSize);
ctx.fillStyle = u.colorStr(color);
if (strokeColor) {
ctx.strokeStyle = u.colorStr(strokeColor);
ctx.lineWidth = 0.05;
}
ctx.save();
ctx.beginPath();
shape.draw(ctx);
ctx.closePath();
ctx.restore();
ctx.fill();
if (strokeColor) {
ctx.stroke();
}
ctx.restore();
}
ctx.nextX++;
return slot;
}
};
})();
AgentSet = (function(_super) {
__extends(AgentSet, _super);
AgentSet.asSet = function(a, setType) {
var _ref;
if (setType == null) {
setType = AgentSet;
}
a.__proto__ = (_ref = setType.prototype) != null ? _ref : setType.constructor.prototype;
if (a[0] != null) {
a.model = a[0].model;
}
return a;
};
function AgentSet(model, agentClass, name, mainSet) {
this.model = model;
this.agentClass = agentClass;
this.name = name;
this.mainSet = mainSet;
AgentSet.__super__.constructor.call(this, 0);
if (this.mainSet == null) {
this.breeds = [];
}
this.agentClass.prototype.breed = this;
this.agentClass.prototype.model = this.model;
this.ownVariables = [];
if (this.mainSet == null) {
this.ID = 0;
}
}
AgentSet.prototype.create = function() {};
AgentSet.prototype.add = function(o) {
if (this.mainSet != null) {
this.mainSet.add(o);
} else {
o.id = this.ID++;
}
this.push(o);
return o;
};
AgentSet.prototype.remove = function(o) {
if (this.mainSet != null) {
u.removeItem(this.mainSet, o);
}
u.removeItem(this, o);
return this;
};
AgentSet.prototype.setDefault = function(name, value) {
this.agentClass.prototype[name] = value;
return this;
};
AgentSet.prototype.own = function(vars) {
var name, _i, _len, _ref;
_ref = vars.split(" ");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
this.setDefault(name, null);
this.ownVariables.push(name);
}
return this;
};
AgentSet.prototype.setBreed = function(a) {
var k, proto, v;
if (a.breed.mainSet != null) {
u.removeItem(a.breed, a, "id");
}
if (this.mainSet != null) {
u.insertItem(this, a, "id");
}
proto = a.__proto__ = this.agentClass.prototype;
for (k in a) {
if (!__hasProp.call(a, k)) continue;
v = a[k];
if (proto[k] != null) {
delete a[k];
}
}
return a;
};
AgentSet.prototype.exclude = function(breeds) {
var o;
breeds = breeds.split(" ");
return this.asSet((function() {
var _i, _len, _ref, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
if (_ref = o.breed.name, __indexOf.call(breeds, _ref) < 0) {
_results.push(o);
}
}
return _results;
}).call(this));
};
AgentSet.prototype.floodFill = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) {
var floodFunc, _results;
if (asetLast == null) {
asetLast = [];
}
floodFunc = this.floodFillOnce(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast);
_results = [];
while (floodFunc) {
_results.push(floodFunc = floodFunc());
}
return _results;
};
AgentSet.prototype.floodFillOnce = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) {
var asetNext, n, p, stopEarly, _i, _j, _k, _len, _len1, _len2, _ref;
if (asetLast == null) {
asetLast = [];
}
for (_i = 0, _len = aset.length; _i < _len; _i++) {
p = aset[_i];
fJoin(p, asetLast);
}
asetNext = [];
for (_j = 0, _len1 = aset.length; _j < _len1; _j++) {
p = aset[_j];
_ref = fNeighbors(p);
for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) {
n = _ref[_k];
if (fCandidate(n, aset)) {
if (asetNext.indexOf(n) < 0) {
asetNext.push(n);
}
}
}
}
stopEarly = fCallback && fCallback(aset, asetNext);
if (stopEarly || asetNext.length === 0) {
return null;
} else {
return (function(_this) {
return function() {
return _this.floodFillOnce(asetNext, fCandidate, fJoin, fCallback, fNeighbors, aset);
};
})(this);
}
};
AgentSet.prototype.uniq = function() {
return u.uniq(this);
};
AgentSet.prototype.asSet = function(a, setType) {
if (setType == null) {
setType = this;
}
return AgentSet.asSet(a, setType);
};
AgentSet.prototype.asOrderedSet = function(a) {
return this.asSet(a).sortById();
};
AgentSet.prototype.toString = function() {
var a;
return "[" + ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
a = this[_i];
_results.push(a.toString());
}
return _results;
}).call(this)).join(", ") + "]";
};
AgentSet.prototype.getProp = function(prop) {
return u.aProp(this, prop);
};
AgentSet.prototype.getPropWith = function(prop, value) {
var o;
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
if (o[prop] === value) {
_results.push(o);
}
}
return _results;
}).call(this));
};
AgentSet.prototype.setProp = function(prop, value) {
var i, o, _i, _j, _len, _len1;
if (u.isArray(value)) {
for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
o = this[i];
o[prop] = value[i];
}
return this;
} else {
for (_j = 0, _len1 = this.length; _j < _len1; _j++) {
o = this[_j];
o[prop] = value;
}
return this;
}
};
AgentSet.prototype.maxProp = function(prop) {
return u.aMax(this.getProp(prop));
};
AgentSet.prototype.minProp = function(prop) {
return u.aMin(this.getProp(prop));
};
AgentSet.prototype.histOfProp = function(prop, bin) {
if (bin == null) {
bin = 1;
}
return u.histOf(this, bin, prop);
};
AgentSet.prototype.shuffle = function() {
return u.shuffle(this);
};
AgentSet.prototype.sortById = function() {
return u.sortBy(this, "id");
};
AgentSet.prototype.clone = function() {
return this.asSet(u.clone(this));
};
AgentSet.prototype.last = function() {
return u.last(this);
};
AgentSet.prototype.any = function() {
return u.any(this);
};
AgentSet.prototype.other = function(a) {
var o;
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
if (o !== a) {
_results.push(o);
}
}
return _results;
}).call(this));
};
AgentSet.prototype.oneOf = function() {
return u.oneOf(this);
};
AgentSet.prototype.nOf = function(n) {
return this.asSet(u.nOf(this, n));
};
AgentSet.prototype.minOneOf = function(f, valueToo) {
if (valueToo == null) {
valueToo = false;
}
return u.minOneOf(this, f, valueToo);
};
AgentSet.prototype.maxOneOf = function(f, valueToo) {
if (valueToo == null) {
valueToo = false;
}
return u.maxOneOf(this, f, valueToo);
};
AgentSet.prototype.draw = function(ctx) {
var o, _i, _len;
u.clearCtx(ctx);
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
if (!o.hidden) {
o.draw(ctx);
}
}
return null;
};
AgentSet.prototype.show = function() {
var o, _i, _len;
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
o.hidden = false;
}
return this.draw(this.model.contexts[this.name]);
};
AgentSet.prototype.hide = function() {
var o, _i, _len;
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
o.hidden = true;
}
return this.draw(this.model.contexts[this.name]);
};
AgentSet.prototype.inRadius = function(o, d, meToo) {
var a, d2, h, w, x, y;
if (meToo == null) {
meToo = false;
}
d2 = d * d;
x = o.x;
y = o.y;
if (this.model.patches.isTorus) {
w = this.model.patches.numX;
h = this.model.patches.numY;
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
a = this[_i];
if (u.torusSqDistance(x, y, a.x, a.y, w, h) <= d2 && (meToo || a !== o)) {
_results.push(a);
}
}
return _results;
}).call(this));
} else {
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
a = this[_i];
if (u.sqDistance(x, y, a.x, a.y) <= d2 && (meToo || a !== o)) {
_results.push(a);
}
}
return _results;
}).call(this));
}
};
AgentSet.prototype.inCone = function(o, heading, cone, radius, meToo) {
var a, h, rSet, w, x, y;
if (meToo == null) {
meToo = false;
}
rSet = this.inRadius(o, radius, meToo);
x = o.x;
y = o.y;
if (this.model.patches.isTorus) {
w = this.model.patches.numX;
h = this.model.patches.numY;
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = rSet.length; _i < _len; _i++) {
a = rSet[_i];
if ((a === o && meToo) || u.inTorusCone(heading, cone, radius, x, y, a.x, a.y, w, h)) {
_results.push(a);
}
}
return _results;
})());
} else {
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = rSet.length; _i < _len; _i++) {
a = rSet[_i];
if ((a === o && meToo) || u.inCone(heading, cone, radius, x, y, a.x, a.y)) {
_results.push(a);
}
}
return _results;
})());
}
};
AgentSet.prototype.on = function(name, cb) {
var agent, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
agent = this[_i];
_results.push(agent.on(name, cb));
}
return _results;
};
AgentSet.prototype.off = function(name, cb) {
var agent, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
agent = this[_i];
_results.push(agent.off(name, cb));
}
return _results;
};
AgentSet.prototype.ask = function(f) {
var o, _i, _len;
if (u.isString(f)) {
eval("f=function(o){return " + f + ";}");
}
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
f(o);
}
return this;
};
AgentSet.prototype["with"] = function(f) {
var o;
if (u.isString(f)) {
eval("f=function(o){return " + f + ";}");
}
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
o = this[_i];
if (f(o)) {
_results.push(o);
}
}
return _results;
}).call(this));
};
return AgentSet;
})(Array);
Patch = (function() {
Patch.prototype.id = null;
Patch.prototype.breed = null;
Patch.prototype.x = null;
Patch.prototype.y = null;
Patch.prototype.n = null;
Patch.prototype.n4 = null;
Patch.prototype.color = [0, 0, 0];
Patch.prototype.hidden = false;
Patch.prototype.label = null;
Patch.prototype.labelColor = [0, 0, 0];
Patch.prototype.labelOffset = [0, 0];
Patch.prototype.pRect = null;
function Patch(x, y) {
this.x = x;
this.y = y;
u.mixin(this, new Evented());
}
Patch.prototype.toString = function() {
return "{id:" + this.id + " xy:" + [this.x, this.y] + " c:" + this.color + "}";
};
Patch.prototype.scaleColor = function(c, s) {
if (!this.hasOwnProperty("color")) {
this.color = u.clone(this.color);
}
return u.scaleColor(c, s, this.color);
};
Patch.prototype.draw = function(ctx) {
var x, y, _ref;
ctx.fillStyle = u.colorStr(this.color);
ctx.fillRect(this.x - .5, this.y - .5, 1, 1);
if (this.label != null) {
_ref = this.breed.patchXYtoPixelXY(this.x, this.y), x = _ref[0], y = _ref[1];
return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor);
}
};
Patch.prototype.agentsHere = function() {
var a, _ref;
return (_ref = this.agents) != null ? _ref : (function() {
var _i, _len, _ref1, _results;
_ref1 = this.model.agents;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
a = _ref1[_i];
if (a.p === this) {
_results.push(a);
}
}
return _results;
}).call(this);
};
Patch.prototype.isOnEdge = function() {
return this.x === this.breed.minX || this.x === this.breed.maxX || this.y === this.breed.minY || this.y === this.breed.maxY;
};
Patch.prototype.sprout = function(num, breed, init) {
if (num == null) {
num = 1;
}
if (breed == null) {
breed = this.model.agents;
}
if (init == null) {
init = function() {};
}
return breed.create(num, (function(_this) {
return function(a) {
a.setXY(_this.x, _this.y);
init(a);
return a;
};
})(this));
};
return Patch;
})();
Patches = (function(_super) {
__extends(Patches, _super);
function Patches() {
var k, v, _ref;
Patches.__super__.constructor.apply(this, arguments);
this.monochrome = false;
_ref = this.model.world;
for (k in _ref) {
if (!__hasProp.call(_ref, k)) continue;
v = _ref[k];
this[k] = v;
}
if (this.mainSet == null) {
this.populate();
}
}
Patches.prototype.populate = function() {
var x, y, _i, _j, _ref, _ref1, _ref2, _ref3;
for (y = _i = _ref = this.maxY, _ref1 = this.minY; _i >= _ref1; y = _i += -1) {
for (x = _j = _ref2 = this.minX, _ref3 = this.maxX; _j <= _ref3; x = _j += 1) {
this.add(new this.agentClass(x, y));
}
}
if (this.hasNeighbors) {
this.setNeighbors();
}
if (!this.isHeadless) {
return this.setPixels();
}
};
Patches.prototype.cacheAgentsHere = function() {
var p, _i, _len;
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
p.agents = [];
}
return null;
};
Patches.prototype.usePixels = function(drawWithPixels) {
var ctx;
this.drawWithPixels = drawWithPixels != null ? drawWithPixels : true;
ctx = this.model.contexts.patches;
return u.setCtxSmoothing(ctx, !this.drawWithPixels);
};
Patches.prototype.cacheRect = function(radius, meToo) {
var p, _i, _len;
if (meToo == null) {
meToo = false;
}
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
p.pRect = this.patchRect(p, radius, radius, meToo);
p.pRect.radius = radius;
}
return radius;
};
Patches.prototype.setNeighbors = function() {
var n, p, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
p.n = this.patchRect(p, 1, 1);
_results.push(p.n4 = this.asSet((function() {
var _j, _len1, _ref, _results1;
_ref = p.n;
_results1 = [];
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
n = _ref[_j];
if (n.x === p.x || n.y === p.y) {
_results1.push(n);
}
}
return _results1;
})()));
}
return _results;
};
Patches.prototype.setPixels = function() {
if (this.size === 1) {
this.usePixels();
this.pixelsCtx = this.model.contexts.patches;
} else {
this.pixelsCtx = u.createCtx(this.numX, this.numY);
}
this.pixelsImageData = this.pixelsCtx.getImageData(0, 0, this.numX, this.numY);
this.pixelsData = this.pixelsImageData.data;
if (this.pixelsData instanceof Uint8Array) {
this.pixelsData32 = new Uint32Array(this.pixelsData.buffer);
return this.pixelsAreLittleEndian = u.isLittleEndian();
}
};
Patches.prototype.draw = function(ctx) {
if (this.monochrome) {
return u.fillCtx(ctx, this.agentClass.prototype.color);
} else if (this.drawWithPixels) {
return this.drawScaledPixels(ctx);
} else {
return Patches.__super__.draw.call(this, ctx);
}
};
Patches.prototype.patchIndex = function(x, y) {
return x - this.minX + this.numX * (this.maxY - y);
};
Patches.prototype.patchXY = function(x, y) {
return this[this.patchIndex(x, y)];
};
Patches.prototype.clamp = function(x, y) {
return [u.clamp(x, this.minXcor, this.maxXcor), u.clamp(y, this.minYcor, this.maxYcor)];
};
Patches.prototype.wrap = function(x, y) {
return [u.wrap(x, this.minXcor, this.maxXcor), u.wrap(y, this.minYcor, this.maxYcor)];
};
Patches.prototype.coord = function(x, y) {
if (this.isTorus) {
return this.wrap(x, y);
} else {
return this.clamp(x, y);
}
};
Patches.prototype.isOnWorld = function(x, y) {
return this.isTorus || ((this.minXcor <= x && x <= this.maxXcor) && (this.minYcor <= y && y <= this.maxYcor));
};
Patches.prototype.patch = function(x, y) {
var _ref;
_ref = this.coord(x, y), x = _ref[0], y = _ref[1];
x = u.clamp(Math.round(x), this.minX, this.maxX);
y = u.clamp(Math.round(y), this.minY, this.maxY);
return this.patchXY(x, y);
};
Patches.prototype.randomPt = function() {
return [u.randomFloat2(this.minXcor, this.maxXcor), u.randomFloat2(this.minYcor, this.maxYcor)];
};
Patches.prototype.toBits = function(p) {
return p * this.size;
};
Patches.prototype.fromBits = function(b) {
return b / this.size;
};
Patches.prototype.patchRect = function(p, dx, dy, meToo) {
var pnext, rect, x, y, _i, _j, _ref, _ref1, _ref2, _ref3;
if (meToo == null) {
meToo = false;
}
if ((p.pRect != null) && p.pRect.radius === dx) {
return p.pRect;
}
rect = [];
for (y = _i = _ref = p.y - dy, _ref1 = p.y + dy; _i <= _ref1; y = _i += 1) {
for (x = _j = _ref2 = p.x - dx, _ref3 = p.x + dx; _j <= _ref3; x = _j += 1) {
if (this.isTorus || ((this.minX <= x && x <= this.maxX) && (this.minY <= y && y <= this.maxY))) {
if (this.isTorus) {
if (x < this.minX) {
x += this.numX;
}
if (x > this.maxX) {
x -= this.numX;
}
if (y < this.minY) {
y += this.numY;
}
if (y > this.maxY) {
y -= this.numY;
}
}
pnext = this.patchXY(x, y);
if (pnext == null) {
u.error("patchRect: x,y out of bounds, see console.log");
console.log("x " + x + " y " + y + " p.x " + p.x + " p.y " + p.y + " dx " + dx + " dy " + dy);
}
if (meToo || p !== pnext) {
rect.push(pnext);
}
}
}
}
return this.asSet(rect);
};
Patches.prototype.importDrawing = function(imageSrc, f) {
return u.importImage(imageSrc, (function(_this) {
return function(img) {
_this.installDrawing(img);
if (f != null) {
return f();
}
};
})(this));
};
Patches.prototype.installDrawing = function(img, ctx) {
if (ctx == null) {
ctx = this.model.contexts.drawing;
}
u.setIdentity(ctx);
ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);
return ctx.restore();
};
Patches.prototype.pixelByteIndex = function(p) {
return 4 * p.id;
};
Patches.prototype.pixelWordIndex = function(p) {
return p.id;
};
Patches.prototype.pixelXYtoPatchXY = function(x, y) {
return [this.minXcor + (x / this.size), this.maxYcor - (y / this.size)];
};
Patches.prototype.patchXYtoPixelXY = function(x, y) {
return [(x - this.minXcor) * this.size, (this.maxYcor - y) * this.size];
};
Patches.prototype.importColors = function(imageSrc, f, map) {
return u.importImage(imageSrc, (function(_this) {
return function(img) {
_this.installColors(img, map);
if (f != null) {
return f();
}
};
})(this));
};
Patches.prototype.installColors = function(img, map) {
var data, i, p, _i, _len;
u.setIdentity(this.pixelsCtx);
this.pixelsCtx.drawImage(img, 0, 0, this.numX, this.numY);
data = this.pixelsCtx.getImageData(0, 0, this.numX, this.numY).data;
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
i = this.pixelByteIndex(p);
p.color = map != null ? map[i] : [data[i++], data[i++], data[i]];
}
return this.pixelsCtx.restore();
};
Patches.prototype.drawScaledPixels = function(ctx) {
if (this.size !== 1) {
u.setIdentity(ctx);
}
if (this.pixelsData32 != null) {
this.drawScaledPixels32(ctx);
} else {
this.drawScaledPixels8(ctx);
}
if (this.size !== 1) {
return ctx.restore();
}
};
Patches.prototype.drawScaledPixels8 = function(ctx) {
var a, c, data, i, j, p, _i, _j, _len;
data = this.pixelsData;
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
i = this.pixelByteIndex(p);
c = p.color;
a = c.length === 4 ? c[3] : 255;
for (j = _j = 0; _j <= 2; j = ++_j) {
data[i + j] = c[j];
}
data[i + 3] = a;
}
this.pixelsCtx.putImageData(this.pixelsImageData, 0, 0);
if (this.size === 1) {
return;
}
return ctx.drawImage(this.pixelsCtx.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height);
};
Patches.prototype.drawScaledPixels32 = function(ctx) {
var a, c, data, i, p, _i, _len;
data = this.pixelsData32;
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
i = this.pixelWordIndex(p);
c = p.color;
a = c.length === 4 ? c[3] : 255;
if (this.pixelsAreLittleEndian) {
data[i] = (a << 24) | (c[2] << 16) | (c[1] << 8) | c[0];
} else {
data[i] = (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | a;
}
}
this.pixelsCtx.putImageData(this.pixelsImageData, 0, 0);
if (this.size === 1) {
return;
}
return ctx.drawImage(this.pixelsCtx.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height);
};
Patches.prototype.floodFillOnce = function(aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast) {
if (fNeighbors == null) {
fNeighbors = (function(p) {
return p.n;
});
}
if (asetLast == null) {
asetLast = [];
}
return Patches.__super__.floodFillOnce.call(this, aset, fCandidate, fJoin, fCallback, fNeighbors, asetLast);
};
Patches.prototype.diffuse = function(v, rate, c) {
var dv, dv8, n, nn, p, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref;
if (this[0]._diffuseNext == null) {
for (_i = 0, _len = this.length; _i < _len; _i++) {
p = this[_i];
p._diffuseNext = 0;
}
}
for (_j = 0, _len1 = this.length; _j < _len1; _j++) {
p = this[_j];
dv = p[v] * rate;
dv8 = dv / 8;
nn = p.n.length;
p._diffuseNext += p[v] - dv + (8 - nn) * dv8;
_ref = p.n;
for (_k = 0, _len2 = _ref.length; _k < _len2; _k++) {
n = _ref[_k];
n._diffuseNext += dv8;
}
}
for (_l = 0, _len3 = this.length; _l < _len3; _l++) {
p = this[_l];
p[v] = p._diffuseNext;
p._diffuseNext = 0;
if (c) {
p.scaleColor(c, p[v]);
}
}
return null;
};
return Patches;
})(AgentSet);
Agent = (function() {
Agent.prototype.id = null;
Agent.prototype.breed = null;
Agent.prototype.x = 0;
Agent.prototype.y = 0;
Agent.prototype.p = null;
Agent.prototype.size = 1;
Agent.prototype.color = null;
Agent.prototype.strokeColor = null;
Agent.prototype.shape = "default";
Agent.prototype.hidden = false;
Agent.prototype.label = null;
Agent.prototype.labelColor = [0, 0, 0];
Agent.prototype.labelOffset = [0, 0];
Agent.prototype.penDown = false;
Agent.prototype.penSize = 1;
Agent.prototype.heading = null;
Agent.prototype.sprite = null;
Agent.prototype.cacheLinks = false;
Agent.prototype.links = null;
Agent.prototype.isDragging = false;
function Agent() {
u.mixin(this, new Evented());
this.x = this.y = 0;
this.p = this.model.patches.patch(this.x, this.y);
if (this.color == null) {
this.color = u.randomColor();
}
if (this.heading == null) {
this.heading = u.randomFloat(Math.PI * 2);
}
if (this.p.agents != null) {
this.p.agents.push(this);
}
if (this.cacheLinks) {
this.links = [];
}
}
Agent.prototype.scaleColor = function(c, s) {
if (!this.hasOwnProperty("color")) {
this.color = u.clone(this.color);
}
return u.scaleColor(c, s, this.color);
};
Agent.prototype.toString = function() {
var h;
return "{id:" + this.id + " xy:" + (u.aToFixed([this.x, this.y])) + " c:" + this.color + " h: " + (h = this.heading.toFixed(2)) + "/" + (Math.round(u.radToDeg(h))) + "}";
};
Agent.prototype.setXY = function(x, y) {
var drawing, p, x0, y0, _ref, _ref1;
if (this.penDown) {
_ref = [this.x, this.y], x0 = _ref[0], y0 = _ref[1];
}
_ref1 = this.model.patches.coord(x, y), this.x = _ref1[0], this.y = _ref1[1];
p = this.p;
this.p = this.model.patches.patch(this.x, this.y);
if ((p.agents != null) && p !== this.p) {
u.removeItem(p.agents, this);
this.p.agents.push(this);
}
if (this.penDown) {
drawing = this.model.drawing;
drawing.strokeStyle = u.colorStr(this.color);
drawing.lineWidth = this.model.patches.fromBits(this.penSize);
drawing.beginPath();
drawing.moveTo(x0, y0);
drawing.lineTo(x, y);
return drawing.stroke();
}
};
Agent.prototype.moveTo = function(a) {
return this.setXY(a.x, a.y);
};
Agent.prototype.forward = function(d) {
return this.setXY(this.x + d * Math.cos(this.heading), this.y + d * Math.sin(this.heading));
};
Agent.prototype.rotate = function(rad) {
return this.heading = u.wrap(this.heading + rad, 0, Math.PI * 2);
};
Agent.prototype.right = function(rad) {
return this.rotate(-rad);
};
Agent.prototype.left = function(rad) {
return this.rotate(rad);
};
Agent.prototype.draw = function(ctx) {
var rad, shape, x, y, _ref;
shape = Shapes[this.shape];
rad = shape.rotate ? this.heading : 0;
if ((this.sprite != null) || this.breed.useSprites) {
if (this.sprite == null) {
this.setSprite();
}
Shapes.drawSprite(ctx, this.sprite, this.x, this.y, this.size, rad);
} else {
Shapes.draw(ctx, shape, this.x, this.y, this.size, rad, this.color, this.strokeColor);
}
if (this.label != null) {
_ref = this.model.patches.patchXYtoPixelXY(this.x, this.y), x = _ref[0], y = _ref[1];
return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor);
}
};
Agent.prototype.setSprite = function(sprite) {
var s;
if ((s = sprite) != null) {
this.sprite = s;
this.color = s.color;
this.strokeColor = s.strokeColor;
this.shape = s.shape;
return this.size = s.size;
} else {
if (this.color == null) {
this.color = u.randomColor;
}
return this.sprite = Shapes.shapeToSprite(this.shape, this.color, this.model.patches.toBits(this.size), this.strokeColor);
}
};
Agent.prototype.stamp = function() {
return this.draw(this.model.drawing);
};
Agent.prototype.distanceXY = function(x, y) {
if (this.model.patches.isTorus) {
return u.torusDistance(this.x, this.y, x, y, this.model.patches.numX, this.model.patches.numY);
} else {
return u.distance(this.x, this.y, x, y);
}
};
Agent.prototype.distance = function(o) {
return this.distanceXY(o.x, o.y);
};
Agent.prototype.torusPtXY = function(x, y) {
return u.torusPt(this.x, this.y, x, y, this.model.patches.numX, this.model.patches.numY);
};
Agent.prototype.torusPt = function(o) {
return this.torusPtXY(o.x, o.y);
};
Agent.prototype.face = function(o) {
return this.heading = this.towards(o);
};
Agent.prototype.towardsXY = function(x, y) {
var ps;
if ((ps = this.model.patches).isTorus) {
return u.torusRadsToward(this.x, this.y, x, y, ps.numX, ps.numY);
} else {
return u.radsToward(this.x, this.y, x, y);
}
};
Agent.prototype.towards = function(o) {
return this.towardsXY(o.x, o.y);
};
Agent.prototype.patchAtHeadingAndDistance = function(h, d) {
var dx, dy, _ref;
_ref = u.polarToXY(d, h + this.heading), dx = _ref[0], dy = _ref[1];
return this.patchAt(dx, dy);
};
Agent.prototype.patchLeftAndAhead = function(dh, d) {
return this.patchAtHeadingAndDistance(dh, d);
};
Agent.prototype.patchRightAndAhead = function(dh, d) {
return this.patchAtHeadingAndDistance(-dh, d);
};
Agent.prototype.patchAhead = function(d) {
return this.patchAtHeadingAndDistance(0, d);
};
Agent.prototype.canMove = function(d) {
return this.patchAhead(d) != null;
};
Agent.prototype.patchAt = function(dx, dy) {
var ps, x, y;
x = this.x + dx;
y = this.y + dy;
if ((ps = this.model.patches).isOnWorld(x, y)) {
return ps.patch(x, y);
} else {
return null;
}
};
Agent.prototype.die = function() {
var l, _i, _ref;
this.breed.remove(this);
_ref = this.myLinks();
for (_i = _ref.length - 1; _i >= 0; _i += -1) {
l = _ref[_i];
l.die();
}
if (this.p.agents != null) {
u.removeItem(this.p.agents, this);
}
return null;
};
Agent.prototype.hatch = function(num, breed, init) {
if (num == null) {
num = 1;
}
if (breed == null) {
breed = this.model.agents;
}
if (init == null) {
init = function() {};
}
return breed.create(num, (function(_this) {
return function(a) {
var k, v;
a.setXY(_this.x, _this.y);
for (k in _this) {
if (!__hasProp.call(_this, k)) continue;
v = _this[k];
if (k !== "id") {
a[k] = v;
}
}
init(a);
return a;
};
})(this));
};
Agent.prototype.inCone = function(aset, cone, radius, meToo) {
if (meToo == null) {
meToo = false;
}
return aset.inCone(this.p, this.heading, cone, radius, meToo);
};
Agent.prototype.hitTest = function(x, y) {
return this.distanceXY(x, y) < this.size * this.model.patches.size;
};
Agent.prototype.otherEnd = function(l) {
if (l.end1 === this) {
return l.end2;
} else {
return l.end1;
}
};
Agent.prototype.myLinks = function() {
var l, _ref;
return (_ref = this.links) != null ? _ref : (function() {
var _i, _len, _ref1, _results;
_ref1 = this.model.links;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
l = _ref1[_i];
if ((l.end1 === this) || (l.end2 === this)) {
_results.push(l);
}
}
return _results;
}).call(this);
};
Agent.prototype.linkNeighbors = function() {
var l, _i, _len, _ref, _results;
_ref = this.myLinks();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
_results.push(this.otherEnd(l));
}
return _results;
};
Agent.prototype.myInLinks = function() {
var l, _i, _len, _ref, _results;
_ref = this.myLinks();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
if (l.end2 === this) {
_results.push(l);
}
}
return _results;
};
Agent.prototype.inLinkNeighbors = function() {
var l, _i, _len, _ref, _results;
_ref = this.myLinks();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
if (l.end2 === this) {
_results.push(l.end1);
}
}
return _results;
};
Agent.prototype.myOutLinks = function() {
var l, _i, _len, _ref, _results;
_ref = this.myLinks();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
if (l.end1 === this) {
_results.push(l);
}
}
return _results;
};
Agent.prototype.outLinkNeighbors = function() {
var l, _i, _len, _ref, _results;
_ref = this.myLinks();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
l = _ref[_i];
if (l.end1 === this) {
_results.push(l.end2);
}
}
return _results;
};
Agent.prototype.setDraggable = function() {
this.on('dragstart', (function(_this) {
return function(mouseEvent) {
return _this.dragging = true;
};
})(this));
this.on('dragend', (function(_this) {
return function(mouseEvent) {
return _this.dragging = false;
};
})(this));
return this.on('drag', (function(_this) {
return function(mouseEvent) {
return _this.setXY(mouseEvent.patchX, mouseEvent.patchY);
};
})(this));
};
return Agent;
})();
Agents = (function(_super) {
__extends(Agents, _super);
function Agents() {
Agents.__super__.constructor.apply(this, arguments);
this.useSprites = false;
}
Agents.prototype.cacheLinks = function() {
return this.agentClass.prototype.cacheLinks = true;
};
Agents.prototype.setUseSprites = function(useSprites) {
this.useSprites = useSprites != null ? useSprites : true;
};
Agents.prototype["in"] = function(array) {
var o;
return this.asSet((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
o = array[_i];
if (o.breed === this) {
_results.push(o);
}
}
return _results;
}).call(this));
};
Agents.prototype.create = function(num, init) {
var i, _i, _results;
if (init == null) {
init = function() {};
}
_results = [];
for (i = _i = 1; _i <= num; i = _i += 1) {
_results.push((function(o) {
init(o);
return o;
})(this.add(new this.agentClass)));
}
return _results;
};
Agents.prototype.clear = function() {
while (this.any()) {
this.last().die();
}
return null;
};
Agents.prototype.inPatches = function(patches) {
var array, p, _i, _len;
array = [];
for (_i = 0, _len = patches.length; _i < _len; _i++) {
p = patches[_i];
array.push.apply(array, p.agentsHere());
}
if (this.mainSet != null) {
return this["in"](array);
} else {
return this.asSet(array);
}
};
Agents.prototype.inRect = function(a, dx, dy, meToo) {
var rect;
if (meToo == null) {
meToo = false;
}
rect = this.model.patches.patchRect(a.p, dx, dy, true);
rect = this.inPatches(rect);
if (!meToo) {
u.removeItem(rect, a);
}
return rect;
};
Agents.prototype.inCone = function(a, heading, cone, radius, meToo) {
var as;
if (meToo == null) {
meToo = false;
}
as = this.inRect(a, radius, radius, true);
return Agents.__super__.inCone.call(this, a, heading, cone, radius, meToo);
};
Agents.prototype.inRadius = function(a, radius, meToo) {
var as;
if (meToo == null) {
meToo = false;
}
as = this.inRect(a, radius, radius, true);
return Agents.__super__.inRadius.call(this, a, radius, meToo);
};
Agents.prototype.setDraggable = function() {
var agent, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
agent = this[_i];
_results.push(agent.setDraggable());
}
return _results;
};
return Agents;
})(AgentSet);
Link = (function() {
Link.prototype.id = null;
Link.prototype.breed = null;
Link.prototype.end1 = null;
Link.prototype.end2 = null;
Link.prototype.color = [130, 130, 130];
Link.prototype.thickness = 2;
Link.prototype.hidden = false;
Link.prototype.label = null;
Link.prototype.labelColor = [0, 0, 0];
Link.prototype.labelOffset = [0, 0];
Link.prototype.isDragging = false;
function Link(end1, end2) {
this.end1 = end1;
this.end2 = end2;
u.mixin(this, new Evented());
if (this.end1.links != null) {
this.end1.links.push(this);
this.end2.links.push(this);
}
}
Link.prototype.draw = function(ctx) {
var pt, x, x0, y, y0, _ref, _ref1;
ctx.save();
ctx.strokeStyle = u.colorStr(this.color);
ctx.lineWidth = this.model.patches.fromBits(this.thickness);
ctx.beginPath();
if (!this.model.patches.isTorus) {
ctx.moveTo(this.end1.x, this.end1.y);
ctx.lineTo(this.end2.x, this.end2.y);
} else {
pt = this.end1.torusPt(this.end2);
ctx.moveTo(this.end1.x, this.end1.y);
ctx.lineTo.apply(ctx, pt);
if (pt[0] !== this.end2.x || pt[1] !== this.end2.y) {
pt = this.end2.torusPt(this.end1);
ctx.moveTo(this.end2.x, this.end2.y);
ctx.lineTo.apply(ctx, pt);
}
}
ctx.closePath();
ctx.stroke();
ctx.restore();
if (this.label != null) {
_ref = u.lerp2(this.end1.x, this.end1.y, this.end2.x, this.end2.y, .5), x0 = _ref[0], y0 = _ref[1];
_ref1 = this.model.patches.patchXYtoPixelXY(x0, y0), x = _ref1[0], y = _ref1[1];
return u.ctxDrawText(ctx, this.label, x + this.labelOffset[0], y + this.labelOffset[1], this.labelColor);
}
};
Link.prototype.die = function() {
this.breed.remove(this);
if (this.end1.links != null) {
u.removeItem(this.end1.links, this);
}
if (this.end2.links != null) {
u.removeItem(this.end2.links, this);
}
return null;
};
Link.prototype.hitTest = function(x, y) {
var a, distance;
distance = u.aSum((function() {
var _i, _len, _ref, _results;
_ref = this.bothEnds();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
a = _ref[_i];
_results.push(a.distanceXY(x, y));
}
return _results;
}).call(this));
return distance - this.length() < 1 / this.model.patches.size;
};
Link.prototype.bothEnds = function() {
return [this.end1, this.end2];
};
Link.prototype.length = function() {
return this.end1.distance(this.end2);
};
Link.prototype.otherEnd = function(a) {
if (this.end1 === a) {
return this.end2;
} else {
return this.end1;
}
};
Link.prototype.setDraggable = function() {
this.on('dragstart', (function(_this) {
return function(mouseEvent) {
return _this.dragging = true;
};
})(this));
this.on('dragend', (function(_this) {
return function(mouseEvent) {
return _this.dragging = false;
};
})(this));
return this.on('drag', (function(_this) {
return function(mouseEvent) {
_this.end1.setXY(_this.end1.p.x - mouseEvent.dx, _this.end1.p.y - mouseEvent.dy);
return _this.end2.setXY(_this.end2.p.x - mouseEvent.dx, _this.end2.p.y - mouseEvent.dy);
};
})(this));
};
return Link;
})();
Links = (function(_super) {
__extends(Links, _super);
function Links() {
Links.__super__.constructor.apply(this, arguments);
}
Links.prototype.create = function(from, to, init) {
var a, _i, _len, _results;
if (init == null) {
init = function() {};
}
if (to.length == null) {
to = [to];
}
_results = [];
for (_i = 0, _len = to.length; _i < _len; _i++) {
a = to[_i];
_results.push((function(o) {
init(o);
return o;
})(this.add(new this.agentClass(from, a))));
}
return _results;
};
Links.prototype.clear = function() {
while (this.any()) {
this.last().die();
}
return null;
};
Links.prototype.allEnds = function() {
var l, n, _i, _len;
n = this.asSet([]);
for (_i = 0, _len = this.length; _i < _len; _i++) {
l = this[_i];
n.push(l.end1, l.end2);
}
return n;
};
Links.prototype.nodes = function() {
return this.allEnds().sortById().uniq();
};
Links.prototype.layoutCircle = function(list, radius, startAngle, direction) {
var a, dTheta, i, _i, _len;
if (startAngle == null) {
startAngle = Math.PI / 2;
}
if (direction == null) {
direction = -1;
}
dTheta = 2 * Math.PI / list.length;
for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) {
a = list[i];
a.setXY(0, 0);
a.heading = startAngle + direction * dTheta * i;
a.forward(radius);
}
return null;
};
Links.prototype.setDraggable = function() {
var link, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
link = this[_i];
_results.push(link.setDraggable());
}
return _results;
};
return Links;
})(AgentSet);
Model = (function() {
Model.prototype.contextsInit = {
patches: {
z: 10,
ctx: "2d"
},
drawing: {
z: 20,
ctx: "2d"
},
links: {
z: 30,
ctx: "2d"
},
agents: {
z: 40,
ctx: "2d"
},
spotlight: {
z: 50,
ctx: "2d"
}
};
function Model(divOrOpts, size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless) {
var ctx, div, k, v, _ref;
if (size == null) {
size = 13;
}
if (minX == null) {
minX = -16;
}
if (maxX == null) {
maxX = 16;
}
if (minY == null) {
minY = -16;
}
if (maxY == null) {
maxY = 16;
}
if (isTorus == null) {
isTorus = false;
}
if (hasNeighbors == null) {
hasNeighbors = true;
}
if (isHeadless == null) {
isHeadless = false;
}
u.mixin(this, new Evented());
if (typeof divOrOpts === 'string') {
div = divOrOpts;
this.setWorldDeprecated(size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless);
} else {
div = divOrOpts.div;
isHeadless = divOrOpts.isHeadless = divOrOpts.isHeadless || (div == null);
this.setWorld(divOrOpts);
}
this.contexts = {};
if (!isHeadless) {
(this.div = document.getElementById(div)).setAttribute('style', "position:relative; width:" + this.world.pxWidth + "px; height:" + this.world.pxHeight + "px");
_ref = this.contextsInit;
for (k in _ref) {
if (!__hasProp.call(_ref, k)) continue;
v = _ref[k];
this.contexts[k] = ctx = u.createLayer(this.div, this.world.pxWidth, this.world.pxHeight, v.z, v.ctx);
if (ctx.canvas != null) {
this.setCtxTransform(ctx);
}
if (ctx.canvas != null) {
ctx.canvas.style.pointerEvents = 'none';
}
u.elementTextParams(ctx, "10px sans-serif", "center", "middle");
}
this.drawing = this.contexts.drawing;
this.drawing.clear = (function(_this) {
return function() {
return u.clearCtx(_this.drawing);
};
})(this);
this.contexts.spotlight.globalCompositeOperation = "xor";
}
this.anim = new Animator(this);
this.refreshLinks = this.refreshAgents = this.refreshPatches = true;
this.Patches = Patches;
this.Patch = u.cloneClass(Patch);
this.Agents = Agents;
this.Agent = u.cloneClass(Agent);
this.Links = Links;
this.Link = u.cloneClass(Link);
this.patches = new this.Patches(this, this.Patch, "patches");
this.agents = new this.Agents(this, this.Agent, "agents");
this.links = new this.Links(this, this.Link, "links");
this.debugging = false;
this.modelReady = false;
this.globalNames = null;
this.globalNames = u.ownKeys(this);
this.globalNames.set = false;
this.startup();
u.waitOnFiles((function(_this) {
return function() {
_this.modelReady = true;
_this.setup();
if (!_this.globalNames.set) {
return _this.globals();
}
};
})(this));
}
Model.prototype.setWorld = function(opts) {
var defaults, hasNeighbors, isHeadless, isTorus, k, maxX, maxXcor, maxY, maxYcor, minX, minXcor, minY, minYcor, numX, numY, pxHeight, pxWidth, size, v, w;
w = defaults = {
size: 13,
minX: -16,
maxX: 16,
minY: -16,
maxY: 16,
isTorus: false,
hasNeighbors: true,
isHeadless: false
};
for (k in opts) {
if (!__hasProp.call(opts, k)) continue;
v = opts[k];
w[k] = v;
}
size = w.size, minX = w.minX, maxX = w.maxX, minY = w.minY, maxY = w.maxY, isTorus = w.isTorus, hasNeighbors = w.hasNeighbors, isHeadless = w.isHeadless;
numX = maxX - minX + 1;
numY = maxY - minY + 1;
pxWidth = numX * size;
pxHeight = numY * size;
minXcor = minX - .5;
maxXcor = maxX + .5;
minYcor = minY - .5;
maxYcor = maxY + .5;
return this.world = {
size: size,
minX: minX,
maxX: maxX,
minY: minY,
maxY: maxY,
minXcor: minXcor,
maxXcor: maxXcor,
minYcor: minYcor,
maxYcor: maxYcor,
numX: numX,
numY: numY,
pxWidth: pxWidth,
pxHeight: pxHeight,
isTorus: isTorus,
hasNeighbors: hasNeighbors,
isHeadless: isHeadless
};
};
Model.prototype.setWorldDeprecated = function(size, minX, maxX, minY, maxY, isTorus, hasNeighbors, isHeadless) {
var maxXcor, maxYcor, minXcor, minYcor, numX, numY, pxHeight, pxWidth;
numX = maxX - minX + 1;
numY = maxY - minY + 1;
pxWidth = numX * size;
pxHeight = numY * size;
minXcor = minX - .5;
maxXcor = maxX + .5;
minYcor = minY - .5;
maxYcor = maxY + .5;
return this.world = {
size: size,
minX: minX,
maxX: maxX,
minY: minY,
maxY: maxY,
minXcor: minXcor,
maxXcor: maxXcor,
minYcor: minYcor,
maxYcor: maxYcor,
numX: numX,
numY: numY,
pxWidth: pxWidth,
pxHeight: pxHeight,
isTorus: isTorus,
hasNeighbors: hasNeighbors,
isHeadless: isHeadless
};
};
Model.prototype.setCtxTransform = function(ctx) {
ctx.canvas.width = this.world.pxWidth;
ctx.canvas.height = this.world.pxHeight;
ctx.save();
ctx.scale(this.world.size, -this.world.size);
return ctx.translate(-this.world.minXcor, -this.world.maxYcor);
};
Model.prototype.globals = function(globalNames) {
if (globalNames != null) {
this.globalNames = globalNames;
return this.globalNames.set = true;
} else {
return this.globalNames = u.removeItems(u.ownKeys(this), this.globalNames);
}
};
Model.prototype.setFastPatches = function() {
return this.patches.usePixels();
};
Model.prototype.setMonochromePatches = function() {
return this.patches.monochrome = true;
};
Model.prototype.setCacheAgentsHere = function() {
return this.patches.cacheAgentsHere();
};
Model.prototype.setCacheMyLinks = function() {
return this.agents.cacheLinks();
};
Model.prototype.setCachePatchRect = function(radius, meToo) {
if (meToo == null) {
meToo = false;
}
return this.patches.cacheRect(radius, meToo);
};
Model.prototype.startup = function() {};
Model.prototype.setup = function() {};
Model.prototype.step = function() {};
Model.prototype.start = function() {
u.waitOn(((function(_this) {
return function() {
return _this.modelReady;
};
})(this)), ((function(_this) {
return function() {
return _this.anim.start();
};
})(this)));
return this;
};
Model.prototype.stop = function() {
return this.anim.stop();
};
Model.prototype.once = function() {
if (!this.anim.stopped) {
this.stop();
}
return this.anim.once();
};
Model.prototype.reset = function(restart) {
var k, v, _ref;
if (restart == null) {
restart = false;
}
console.log("reset: anim");
this.anim.reset();
console.log("reset: contexts");
_ref = this.contexts;
for (k in _ref) {
v = _ref[k];
if (v.canvas != null) {
v.restore();
this.setCtxTransform(v);
}
}
console.log("reset: patches");
this.patches = new this.Patches(this, this.Patch, "patches");
console.log("reset: agents");
this.agents = new this.Agents(this, this.Agent, "agents");
console.log("reset: links");
this.links = new this.Links(this, this.Link, "links");
u.s.spriteSheets.length = 0;
console.log("reset: setup");
this.setup();
if (this.debugging) {
this.setRootVars();
}
if (restart) {
return this.start();
}
};
Model.prototype.draw = function(force) {
if (force == null) {
force = this.anim.stopped;
}
if (force || this.refreshPatches || this.anim.draws === 1) {
this.patches.draw(this.contexts.patches);
}
if (force || this.refreshLinks || this.anim.draws === 1) {
this.links.draw(this.contexts.links);
}
if (force || this.refreshAgents || this.anim.draws === 1) {
this.agents.draw(this.contexts.agents);
}
if (this.spotlightAgent != null) {
this.drawSpotlight(this.spotlightAgent, this.contexts.spotlight);
}
return this.emit('draw');
};
Model.prototype._step = function() {
this.step();
return this.emit('step');
};
Model.prototype.setSpotlight = function(spotlightAgent) {
this.spotlightAgent = spotlightAgent;
if (this.spotlightAgent == null) {
return u.clearCtx(this.contexts.spotlight);
}
};
Model.prototype.drawSpotlight = function(agent, ctx) {
u.clearCtx(ctx);
u.fillCtx(ctx, [0, 0, 0, 0.6]);
ctx.beginPath();
ctx.arc(agent.x, agent.y, 3, 0, 2 * Math.PI, false);
return ctx.fill();
};
Model.prototype.createBreeds = function(s, agentClass, breedSet) {
var b, breed, breeds, c, cname, _i, _len, _ref;
breeds = [];
breeds.classes = {};
breeds.sets = {};
_ref = s.split(" ");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
b = _ref[_i];
cname = b.charAt(0).toUpperCase() + b.substr(1);
c = u.cloneClass(agentClass, cname);
breed = this[b] = new breedSet(this, c, b, agentClass.prototype.breed);
breeds.push(breed);
breeds.sets[b] = breed;
breeds.classes["" + b + "Class"] = c;
}
return breeds;
};
Model.prototype.patchBreeds = function(s) {
return this.patches.breeds = this.createBreeds(s, this.Patch, this.Patches);
};
Model.prototype.agentBreeds = function(s) {
return this.agents.breeds = this.createBreeds(s, this.Agent, this.Agents);
};
Model.prototype.linkBreeds = function(s) {
return this.links.breeds = this.createBreeds(s, this.Link, this.Links);
};
Model.prototype.asSet = function(a, setType) {
if (setType == null) {
setType = AgentSet;
}
return AgentSet.asSet(a, setType);
};
Model.prototype.debug = function(debugging) {
this.debugging = debugging != null ? debugging : true;
u.waitOn(((function(_this) {
return function() {
return _this.modelReady;
};
})(this)), ((function(_this) {
return function() {
return _this.setRootVars();
};
})(this)));
return this;
};
Model.prototype.setRootVars = function() {
window.psc = this.Patches;
window.pc = this.Patch;
window.ps = this.patches;
window.p0 = this.patches[0];
window.asc = this.Agents;
window.ac = this.Agent;
window.as = this.agents;
window.a0 = this.agents[0];
window.lsc = this.Links;
window.lc = this.Link;
window.ls = this.links;
window.l0 = this.links[0];
window.dr = this.drawing;
window.u = Util;
window.cx = this.contexts;
window.an = this.anim;
window.gl = this.globals();
window.dv = this.div;
return window.app = this;
};
return Model;
})();
this.ABM = {
util: util,
shapes: shapes,
Util: Util,
Color: Color,
Shapes: Shapes,
AgentSet: AgentSet,
Patch: Patch,
Patches: Patches,
Agent: Agent,
Agents: Agents,
Link: Link,
Links: Links,
Animator: Animator,
Evented: Evented,
Model: Model
};
Animator = (function() {
function Animator(model, rate, multiStep) {
this.model = model;
this.rate = rate != null ? rate : 30;
this.multiStep = multiStep != null ? multiStep : model.world.isHeadless;
this.animateDraws = __bind(this.animateDraws, this);
this.animateSteps = __bind(this.animateSteps, this);
this.isHeadless = model.world.isHeadless;
this.reset();
}
Animator.prototype.setRate = function(rate, multiStep) {
this.rate = rate;
this.multiStep = multiStep != null ? multiStep : this.isHeadless;
return this.resetTimes();
};
Animator.prototype.start = function() {
if (!this.stopped) {
return;
}
this.resetTimes();
this.stopped = false;
return this.animate();
};
Animator.prototype.stop = function() {
this.stopped = true;
if (this.animHandle != null) {
cancelAnimationFrame(this.animHandle);
}
if (this.timeoutHandle != null) {
clearTimeout(this.timeoutHandle);
}
if (this.intervalHandle != null) {
clearInterval(this.intervalHandle);
}
return this.animHandle = this.timerHandle = this.intervalHandle = null;
};
Animator.prototype.resetTimes = function() {
this.startMS = this.now();
this.startTick = this.ticks;
return this.startDraw = this.draws;
};
Animator.prototype.reset = function() {
this.stop();
return this.ticks = this.draws = 0;
};
Animator.prototype.step = function() {
this.ticks++;
return this.model._step();
};
Animator.prototype.draw = function() {
this.draws++;
return this.model.draw();
};
Animator.prototype.once = function() {
this.step();
return this.draw();
};
Animator.prototype.now = function() {
return (typeof performance !== "undefined" && performance !== null ? performance : Date).now();
};
Animator.prototype.ms = function() {
return this.now() - this.startMS;
};
Animator.prototype.ticksPerSec = function() {
var elapsed;
if ((elapsed = this.ticks - this.startTick) === 0) {
return 0;
} else {
return Math.round(elapsed * 1000 / this.ms());
}
};
Animator.prototype.drawsPerSec = function() {
var elapsed;
if ((elapsed = this.draws - this.startDraw) === 0) {
return 0;
} else {
return Math.round(elapsed * 1000 / this.ms());
}
};
Animator.prototype.toString = function() {
return "ticks: " + this.ticks + ", draws: " + this.draws + ", rate: " + this.rate + " tps/dps: " + (this.ticksPerSec()) + "/" + (this.drawsPerSec());
};
Animator.prototype.animateSteps = function() {
this.step();
if (!this.stopped) {
return this.timeoutHandle = setTimeout(this.animateSteps, 10);
}
};
Animator.prototype.animateDraws = function() {
if (this.isHeadless) {
if (this.ticksPerSec() < this.rate) {
this.step();
}
} else if (this.drawsPerSec() < this.rate) {
if (!this.multiStep) {
this.step();
}
this.draw();
}
if (!this.stopped) {
return this.animHandle = requestAnimationFrame(this.animateDraws);
}
};
Animator.prototype.animate = function() {
if (this.multiStep) {
this.animateSteps();
}
if (!(this.isHeadless && this.multiStep)) {
return this.animateDraws();
}
};
return Animator;
})();
}).call(this);
| Caroisawesome/Grill-Editor | lib/agentscript.js | JavaScript | gpl-3.0 | 121,427 |
<?php
// Text
$_['text_upload'] = 'Файл успешно загружен!';
// Error
$_['error_filename'] = 'Имя файла должно быть от 3 до 64 символов!';
$_['error_filetype'] = 'Неправильный тип файла!';
$_['error_upload'] = 'Необходимо загрузить файл!';
| akryzhanovskiy/E-Shop | html/catalog/language/russian/tool/upload.php | PHP | gpl-3.0 | 349 |
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
Copyright (C) 2013-2014 Robert Beckebans
Copyright (C) 2014 Carl Kenner
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "precompiled.h"
#include "tr_local.h"
#include "Framebuffer.h"
idCVar r_drawEyeColor( "r_drawEyeColor", "0", CVAR_RENDERER | CVAR_BOOL, "Draw a colored box, red = left eye, blue = right eye, grey = non-stereo" );
idCVar r_motionBlur( "r_motionBlur", "0", CVAR_RENDERER | CVAR_INTEGER | CVAR_ARCHIVE, "1 - 5, log2 of the number of motion blur samples" );
idCVar r_forceZPassStencilShadows( "r_forceZPassStencilShadows", "0", CVAR_RENDERER | CVAR_BOOL, "force Z-pass rendering for performance testing" );
idCVar r_useStencilShadowPreload( "r_useStencilShadowPreload", "0", CVAR_RENDERER | CVAR_BOOL, "use stencil shadow preload algorithm instead of Z-fail" );
idCVar r_skipShaderPasses( "r_skipShaderPasses", "0", CVAR_RENDERER | CVAR_BOOL, "" );
idCVar r_skipInteractionFastPath( "r_skipInteractionFastPath", "1", CVAR_RENDERER | CVAR_BOOL, "" );
idCVar r_useLightStencilSelect( "r_useLightStencilSelect", "0", CVAR_RENDERER | CVAR_BOOL, "use stencil select pass" );
extern idCVar stereoRender_swapEyes;
backEndState_t backEnd;
/*
================
SetVertexParm
================
*/
static ID_INLINE void SetVertexParm( renderParm_t rp, const float* value )
{
renderProgManager.SetUniformValue( rp, value );
}
/*
================
SetVertexParms
================
*/
static ID_INLINE void SetVertexParms( renderParm_t rp, const float* value, int num )
{
for( int i = 0; i < num; i++ )
{
renderProgManager.SetUniformValue( ( renderParm_t )( rp + i ), value + ( i * 4 ) );
}
}
/*
================
SetFragmentParm
================
*/
static ID_INLINE void SetFragmentParm( renderParm_t rp, const float* value )
{
renderProgManager.SetUniformValue( rp, value );
}
/*
================
RB_SetMVP
================
*/
void RB_SetMVP( const idRenderMatrix& mvp )
{
SetVertexParms( RENDERPARM_MVPMATRIX_X, mvp[0], 4 );
}
/*
================
RB_SetMVPWithStereoOffset
================
*/
static void RB_SetMVPWithStereoOffset( const idRenderMatrix& mvp, const float stereoOffset )
{
idRenderMatrix offset = mvp;
offset[0][3] += stereoOffset;
SetVertexParms( RENDERPARM_MVPMATRIX_X, offset[0], 4 );
}
static const float zero[4] = { 0, 0, 0, 0 };
static const float one[4] = { 1, 1, 1, 1 };
static const float negOne[4] = { -1, -1, -1, -1 };
/*
================
RB_SetVertexColorParms
================
*/
static void RB_SetVertexColorParms( stageVertexColor_t svc )
{
switch( svc )
{
case SVC_IGNORE:
SetVertexParm( RENDERPARM_VERTEXCOLOR_MODULATE, zero );
SetVertexParm( RENDERPARM_VERTEXCOLOR_ADD, one );
break;
case SVC_MODULATE:
SetVertexParm( RENDERPARM_VERTEXCOLOR_MODULATE, one );
SetVertexParm( RENDERPARM_VERTEXCOLOR_ADD, zero );
break;
case SVC_INVERSE_MODULATE:
SetVertexParm( RENDERPARM_VERTEXCOLOR_MODULATE, negOne );
SetVertexParm( RENDERPARM_VERTEXCOLOR_ADD, one );
break;
}
}
/*
================
RB_DrawElementsWithCounters
================
*/
void RB_DrawElementsWithCounters( const drawSurf_t* surf )
{
// get vertex buffer
const vertCacheHandle_t vbHandle = surf->ambientCache;
idVertexBuffer* vertexBuffer;
if( vertexCache.CacheIsStatic( vbHandle ) )
{
vertexBuffer = &vertexCache.staticData.vertexBuffer;
}
else
{
const uint64 frameNum = ( int )( vbHandle >> VERTCACHE_FRAME_SHIFT ) & VERTCACHE_FRAME_MASK;
if( frameNum != ( ( vertexCache.currentFrame - 1 ) & VERTCACHE_FRAME_MASK ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, vertexBuffer == NULL" );
return;
}
vertexBuffer = &vertexCache.frameData[vertexCache.drawListNum].vertexBuffer;
}
const int vertOffset = ( int )( vbHandle >> VERTCACHE_OFFSET_SHIFT ) & VERTCACHE_OFFSET_MASK;
// get index buffer
const vertCacheHandle_t ibHandle = surf->indexCache;
idIndexBuffer* indexBuffer;
if( vertexCache.CacheIsStatic( ibHandle ) )
{
indexBuffer = &vertexCache.staticData.indexBuffer;
}
else
{
const uint64 frameNum = ( int )( ibHandle >> VERTCACHE_FRAME_SHIFT ) & VERTCACHE_FRAME_MASK;
if( frameNum != ( ( vertexCache.currentFrame - 1 ) & VERTCACHE_FRAME_MASK ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, indexBuffer == NULL" );
return;
}
indexBuffer = &vertexCache.frameData[vertexCache.drawListNum].indexBuffer;
}
// RB: 64 bit fixes, changed int to GLintptr
const GLintptr indexOffset = ( GLintptr )( ibHandle >> VERTCACHE_OFFSET_SHIFT ) & VERTCACHE_OFFSET_MASK;
// RB end
RENDERLOG_PRINTF( "Binding Buffers: %p:%i %p:%i\n", vertexBuffer, vertOffset, indexBuffer, indexOffset );
if( surf->jointCache )
{
// DG: this happens all the time in the erebus1 map with blendlight.vfp,
// so don't call assert (through verify) here until it's fixed (if fixable)
// else the game crashes on linux when using debug builds
// FIXME: fix this properly if possible?
// RB: yes but it would require an additional blend light skinned shader
//if( !verify( renderProgManager.ShaderUsesJoints() ) )
if( !renderProgManager.ShaderUsesJoints() )
// DG end
{
return;
}
}
else
{
if( !verify( !renderProgManager.ShaderUsesJoints() || renderProgManager.ShaderHasOptionalSkinning() ) )
{
return;
}
}
if( surf->jointCache )
{
idJointBuffer jointBuffer;
if( !vertexCache.GetJointBuffer( surf->jointCache, &jointBuffer ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, jointBuffer == NULL" );
return;
}
assert( ( jointBuffer.GetOffset() & ( glConfig.uniformBufferOffsetAlignment - 1 ) ) == 0 );
// RB: 64 bit fixes, changed GLuint to GLintptr
const GLintptr ubo = reinterpret_cast< GLintptr >( jointBuffer.GetAPIObject() );
// RB end
glBindBufferRange( GL_UNIFORM_BUFFER, 0, ubo, jointBuffer.GetOffset(), jointBuffer.GetNumJoints() * sizeof( idJointMat ) );
}
renderProgManager.CommitUniforms();
// RB: 64 bit fixes, changed GLuint to GLintptr
if( backEnd.glState.currentIndexBuffer != ( GLintptr )indexBuffer->GetAPIObject() || !r_useStateCaching.GetBool() )
{
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ( GLintptr )indexBuffer->GetAPIObject() );
backEnd.glState.currentIndexBuffer = ( GLintptr )indexBuffer->GetAPIObject();
}
if( ( backEnd.glState.vertexLayout != LAYOUT_DRAW_VERT ) || ( backEnd.glState.currentVertexBuffer != ( GLintptr )vertexBuffer->GetAPIObject() ) || !r_useStateCaching.GetBool() )
{
glBindBuffer( GL_ARRAY_BUFFER, ( GLintptr )vertexBuffer->GetAPIObject() );
backEnd.glState.currentVertexBuffer = ( GLintptr )vertexBuffer->GetAPIObject();
glEnableVertexAttribArray( PC_ATTRIB_INDEX_VERTEX );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_NORMAL );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_COLOR );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_COLOR2 );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_ST );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_TANGENT );
#if defined(USE_GLES2) || defined(USE_GLES3)
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_XYZ_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_NORMAL, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_NORMAL_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_COLOR_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_COLOR2_OFFSET ) );
#if defined(USE_ANGLE)
glVertexAttribPointer( PC_ATTRIB_INDEX_ST, 2, GL_HALF_FLOAT_OES, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_ST_OFFSET ) );
#else
glVertexAttribPointer( PC_ATTRIB_INDEX_ST, 2, GL_HALF_FLOAT, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_ST_OFFSET ) );
#endif
glVertexAttribPointer( PC_ATTRIB_INDEX_TANGENT, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( vertOffset + DRAWVERT_TANGENT_OFFSET ) );
#else
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof( idDrawVert ), ( void* )( DRAWVERT_XYZ_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_NORMAL, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( DRAWVERT_NORMAL_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( DRAWVERT_COLOR_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( DRAWVERT_COLOR2_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_ST, 2, GL_HALF_FLOAT, GL_TRUE, sizeof( idDrawVert ), ( void* )( DRAWVERT_ST_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_TANGENT, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idDrawVert ), ( void* )( DRAWVERT_TANGENT_OFFSET ) );
#endif // #if defined(USE_GLES2) || defined(USE_GLES3)
backEnd.glState.vertexLayout = LAYOUT_DRAW_VERT;
}
// RB end
#if defined(USE_GLES3) //defined(USE_GLES2)
glDrawElements( GL_TRIANGLES,
r_singleTriangle.GetBool() ? 3 : surf->numIndexes,
GL_INDEX_TYPE,
( triIndex_t* )indexOffset );
#else
glDrawElementsBaseVertex( GL_TRIANGLES,
r_singleTriangle.GetBool() ? 3 : surf->numIndexes,
GL_INDEX_TYPE,
( triIndex_t* )indexOffset,
vertOffset / sizeof( idDrawVert ) );
#endif
// RB: added stats
backEnd.pc.c_drawElements++;
backEnd.pc.c_drawIndexes += surf->numIndexes;
// RB end
}
/*
======================
RB_GetShaderTextureMatrix
======================
*/
static void RB_GetShaderTextureMatrix( const float* shaderRegisters, const textureStage_t* texture, float matrix[16] )
{
matrix[0 * 4 + 0] = shaderRegisters[ texture->matrix[0][0] ];
matrix[1 * 4 + 0] = shaderRegisters[ texture->matrix[0][1] ];
matrix[2 * 4 + 0] = 0.0f;
matrix[3 * 4 + 0] = shaderRegisters[ texture->matrix[0][2] ];
matrix[0 * 4 + 1] = shaderRegisters[ texture->matrix[1][0] ];
matrix[1 * 4 + 1] = shaderRegisters[ texture->matrix[1][1] ];
matrix[2 * 4 + 1] = 0.0f;
matrix[3 * 4 + 1] = shaderRegisters[ texture->matrix[1][2] ];
// we attempt to keep scrolls from generating incredibly large texture values, but
// center rotations and center scales can still generate offsets that need to be > 1
if( matrix[3 * 4 + 0] < -40.0f || matrix[12] > 40.0f )
{
matrix[3 * 4 + 0] -= ( int )matrix[3 * 4 + 0];
}
if( matrix[13] < -40.0f || matrix[13] > 40.0f )
{
matrix[13] -= ( int )matrix[13];
}
matrix[0 * 4 + 2] = 0.0f;
matrix[1 * 4 + 2] = 0.0f;
matrix[2 * 4 + 2] = 1.0f;
matrix[3 * 4 + 2] = 0.0f;
matrix[0 * 4 + 3] = 0.0f;
matrix[1 * 4 + 3] = 0.0f;
matrix[2 * 4 + 3] = 0.0f;
matrix[3 * 4 + 3] = 1.0f;
}
/*
======================
RB_LoadShaderTextureMatrix
======================
*/
static void RB_LoadShaderTextureMatrix( const float* shaderRegisters, const textureStage_t* texture )
{
float texS[4] = { 1.0f, 0.0f, 0.0f, 0.0f };
float texT[4] = { 0.0f, 1.0f, 0.0f, 0.0f };
if( texture->hasMatrix )
{
float matrix[16];
RB_GetShaderTextureMatrix( shaderRegisters, texture, matrix );
texS[0] = matrix[0 * 4 + 0];
texS[1] = matrix[1 * 4 + 0];
texS[2] = matrix[2 * 4 + 0];
texS[3] = matrix[3 * 4 + 0];
texT[0] = matrix[0 * 4 + 1];
texT[1] = matrix[1 * 4 + 1];
texT[2] = matrix[2 * 4 + 1];
texT[3] = matrix[3 * 4 + 1];
RENDERLOG_PRINTF( "Setting Texture Matrix\n" );
renderLog.Indent();
RENDERLOG_PRINTF( "Texture Matrix S : %4.3f, %4.3f, %4.3f, %4.3f\n", texS[0], texS[1], texS[2], texS[3] );
RENDERLOG_PRINTF( "Texture Matrix T : %4.3f, %4.3f, %4.3f, %4.3f\n", texT[0], texT[1], texT[2], texT[3] );
renderLog.Outdent();
}
SetVertexParm( RENDERPARM_TEXTUREMATRIX_S, texS );
SetVertexParm( RENDERPARM_TEXTUREMATRIX_T, texT );
}
/*
=====================
RB_BakeTextureMatrixIntoTexgen
=====================
*/
static void RB_BakeTextureMatrixIntoTexgen( idPlane lightProject[3], const float* textureMatrix )
{
float genMatrix[16];
float final[16];
genMatrix[0 * 4 + 0] = lightProject[0][0];
genMatrix[1 * 4 + 0] = lightProject[0][1];
genMatrix[2 * 4 + 0] = lightProject[0][2];
genMatrix[3 * 4 + 0] = lightProject[0][3];
genMatrix[0 * 4 + 1] = lightProject[1][0];
genMatrix[1 * 4 + 1] = lightProject[1][1];
genMatrix[2 * 4 + 1] = lightProject[1][2];
genMatrix[3 * 4 + 1] = lightProject[1][3];
genMatrix[0 * 4 + 2] = 0.0f;
genMatrix[1 * 4 + 2] = 0.0f;
genMatrix[2 * 4 + 2] = 0.0f;
genMatrix[3 * 4 + 2] = 0.0f;
genMatrix[0 * 4 + 3] = lightProject[2][0];
genMatrix[1 * 4 + 3] = lightProject[2][1];
genMatrix[2 * 4 + 3] = lightProject[2][2];
genMatrix[3 * 4 + 3] = lightProject[2][3];
R_MatrixMultiply( genMatrix, textureMatrix, final );
lightProject[0][0] = final[0 * 4 + 0];
lightProject[0][1] = final[1 * 4 + 0];
lightProject[0][2] = final[2 * 4 + 0];
lightProject[0][3] = final[3 * 4 + 0];
lightProject[1][0] = final[0 * 4 + 1];
lightProject[1][1] = final[1 * 4 + 1];
lightProject[1][2] = final[2 * 4 + 1];
lightProject[1][3] = final[3 * 4 + 1];
}
/*
======================
RB_BindVariableStageImage
Handles generating a cinematic frame if needed
======================
*/
static void RB_BindVariableStageImage( const textureStage_t* texture, const float* shaderRegisters )
{
if( texture->cinematic )
{
cinData_t cin;
if( r_skipDynamicTextures.GetBool() )
{
globalImages->defaultImage->Bind();
return;
}
// offset time by shaderParm[7] (FIXME: make the time offset a parameter of the shader?)
// We make no attempt to optimize for multiple identical cinematics being in view, or
// for cinematics going at a lower framerate than the renderer.
cin = texture->cinematic->ImageForTime( backEnd.viewDef->renderView.time[0] + idMath::Ftoi( 1000.0f * backEnd.viewDef->renderView.shaderParms[11] ) );
if( cin.imageY != NULL )
{
GL_SelectTexture( 0 );
cin.imageY->Bind();
GL_SelectTexture( 1 );
cin.imageCr->Bind();
GL_SelectTexture( 2 );
cin.imageCb->Bind();
}
else if( cin.image != NULL )
{
//Carl: A single RGB image works better with the FFMPEG BINK codec.
GL_SelectTexture( 0 );
cin.image->Bind();
renderProgManager.BindShader_TextureVertexColor();
}
else
{
globalImages->blackImage->Bind();
// because the shaders may have already been set - we need to make sure we are not using a bink shader which would
// display incorrectly. We may want to get rid of RB_BindVariableStageImage and inline the code so that the
// SWF GUI case is handled better, too
renderProgManager.BindShader_TextureVertexColor();
}
}
else
{
// FIXME: see why image is invalid
if( texture->image != NULL )
{
texture->image->Bind();
}
}
}
/*
================
RB_PrepareStageTexturing
================
*/
static void RB_PrepareStageTexturing( const shaderStage_t* pStage, const drawSurf_t* surf )
{
float useTexGenParm[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
// set the texture matrix if needed
RB_LoadShaderTextureMatrix( surf->shaderRegisters, &pStage->texture );
// texgens
if( pStage->texture.texgen == TG_REFLECT_CUBE )
{
// see if there is also a bump map specified
const shaderStage_t* bumpStage = surf->material->GetBumpStage();
if( bumpStage != NULL )
{
// per-pixel reflection mapping with bump mapping
GL_SelectTexture( 1 );
bumpStage->texture.image->Bind();
GL_SelectTexture( 0 );
RENDERLOG_PRINTF( "TexGen: TG_REFLECT_CUBE: Bumpy Environment\n" );
if( surf->jointCache )
{
renderProgManager.BindShader_BumpyEnvironmentSkinned();
}
else
{
renderProgManager.BindShader_BumpyEnvironment();
}
}
else
{
RENDERLOG_PRINTF( "TexGen: TG_REFLECT_CUBE: Environment\n" );
if( surf->jointCache )
{
renderProgManager.BindShader_EnvironmentSkinned();
}
else
{
renderProgManager.BindShader_Environment();
}
}
}
else if( pStage->texture.texgen == TG_SKYBOX_CUBE )
{
renderProgManager.BindShader_SkyBox();
}
else if( pStage->texture.texgen == TG_WOBBLESKY_CUBE )
{
const int* parms = surf->material->GetTexGenRegisters();
float wobbleDegrees = surf->shaderRegisters[ parms[0] ] * ( idMath::PI / 180.0f );
float wobbleSpeed = surf->shaderRegisters[ parms[1] ] * ( 2.0f * idMath::PI / 60.0f );
float rotateSpeed = surf->shaderRegisters[ parms[2] ] * ( 2.0f * idMath::PI / 60.0f );
idVec3 axis[3];
{
// very ad-hoc "wobble" transform
float s, c;
idMath::SinCos( wobbleSpeed * backEnd.viewDef->renderView.time[0] * 0.001f, s, c );
float ws, wc;
idMath::SinCos( wobbleDegrees, ws, wc );
axis[2][0] = ws * c;
axis[2][1] = ws * s;
axis[2][2] = wc;
axis[1][0] = -s * s * ws;
axis[1][2] = -s * ws * ws;
axis[1][1] = idMath::Sqrt( idMath::Fabs( 1.0f - ( axis[1][0] * axis[1][0] + axis[1][2] * axis[1][2] ) ) );
// make the second vector exactly perpendicular to the first
axis[1] -= ( axis[2] * axis[1] ) * axis[2];
axis[1].Normalize();
// construct the third with a cross
axis[0].Cross( axis[1], axis[2] );
}
// add the rotate
float rs, rc;
idMath::SinCos( rotateSpeed * backEnd.viewDef->renderView.time[0] * 0.001f, rs, rc );
float transform[12];
transform[0 * 4 + 0] = axis[0][0] * rc + axis[1][0] * rs;
transform[0 * 4 + 1] = axis[0][1] * rc + axis[1][1] * rs;
transform[0 * 4 + 2] = axis[0][2] * rc + axis[1][2] * rs;
transform[0 * 4 + 3] = 0.0f;
transform[1 * 4 + 0] = axis[1][0] * rc - axis[0][0] * rs;
transform[1 * 4 + 1] = axis[1][1] * rc - axis[0][1] * rs;
transform[1 * 4 + 2] = axis[1][2] * rc - axis[0][2] * rs;
transform[1 * 4 + 3] = 0.0f;
transform[2 * 4 + 0] = axis[2][0];
transform[2 * 4 + 1] = axis[2][1];
transform[2 * 4 + 2] = axis[2][2];
transform[2 * 4 + 3] = 0.0f;
SetVertexParms( RENDERPARM_WOBBLESKY_X, transform, 3 );
renderProgManager.BindShader_WobbleSky();
}
else if( ( pStage->texture.texgen == TG_SCREEN ) || ( pStage->texture.texgen == TG_SCREEN2 ) )
{
useTexGenParm[0] = 1.0f;
useTexGenParm[1] = 1.0f;
useTexGenParm[2] = 1.0f;
useTexGenParm[3] = 1.0f;
float mat[16];
R_MatrixMultiply( surf->space->modelViewMatrix, backEnd.viewDef->projectionMatrix, mat );
RENDERLOG_PRINTF( "TexGen : %s\n", ( pStage->texture.texgen == TG_SCREEN ) ? "TG_SCREEN" : "TG_SCREEN2" );
renderLog.Indent();
float plane[4];
plane[0] = mat[0 * 4 + 0];
plane[1] = mat[1 * 4 + 0];
plane[2] = mat[2 * 4 + 0];
plane[3] = mat[3 * 4 + 0];
SetVertexParm( RENDERPARM_TEXGEN_0_S, plane );
RENDERLOG_PRINTF( "TEXGEN_S = %4.3f, %4.3f, %4.3f, %4.3f\n", plane[0], plane[1], plane[2], plane[3] );
plane[0] = mat[0 * 4 + 1];
plane[1] = mat[1 * 4 + 1];
plane[2] = mat[2 * 4 + 1];
plane[3] = mat[3 * 4 + 1];
SetVertexParm( RENDERPARM_TEXGEN_0_T, plane );
RENDERLOG_PRINTF( "TEXGEN_T = %4.3f, %4.3f, %4.3f, %4.3f\n", plane[0], plane[1], plane[2], plane[3] );
plane[0] = mat[0 * 4 + 3];
plane[1] = mat[1 * 4 + 3];
plane[2] = mat[2 * 4 + 3];
plane[3] = mat[3 * 4 + 3];
SetVertexParm( RENDERPARM_TEXGEN_0_Q, plane );
RENDERLOG_PRINTF( "TEXGEN_Q = %4.3f, %4.3f, %4.3f, %4.3f\n", plane[0], plane[1], plane[2], plane[3] );
renderLog.Outdent();
}
else if( pStage->texture.texgen == TG_DIFFUSE_CUBE )
{
// As far as I can tell, this is never used
idLib::Warning( "Using Diffuse Cube! Please contact Brian!" );
}
else if( pStage->texture.texgen == TG_GLASSWARP )
{
// As far as I can tell, this is never used
idLib::Warning( "Using GlassWarp! Please contact Brian!" );
}
SetVertexParm( RENDERPARM_TEXGEN_0_ENABLED, useTexGenParm );
}
/*
================
RB_FinishStageTexturing
================
*/
static void RB_FinishStageTexturing( const shaderStage_t* pStage, const drawSurf_t* surf )
{
if( pStage->texture.cinematic )
{
// unbind the extra bink textures
GL_SelectTexture( 1 );
globalImages->BindNull();
GL_SelectTexture( 2 );
globalImages->BindNull();
GL_SelectTexture( 0 );
}
if( pStage->texture.texgen == TG_REFLECT_CUBE )
{
// see if there is also a bump map specified
const shaderStage_t* bumpStage = surf->material->GetBumpStage();
if( bumpStage != NULL )
{
// per-pixel reflection mapping with bump mapping
GL_SelectTexture( 1 );
globalImages->BindNull();
GL_SelectTexture( 0 );
}
else
{
// per-pixel reflection mapping without bump mapping
}
renderProgManager.Unbind();
}
}
// RB: moved this up because we need to call this several times for shadow mapping
static void RB_ResetViewportAndScissorToDefaultCamera( const viewDef_t* viewDef )
{
// set the window clipping
GL_Viewport( viewDef->viewport.x1,
viewDef->viewport.y1,
viewDef->viewport.x2 + 1 - viewDef->viewport.x1,
viewDef->viewport.y2 + 1 - viewDef->viewport.y1 );
// the scissor may be smaller than the viewport for subviews
GL_Scissor( backEnd.viewDef->viewport.x1 + viewDef->scissor.x1,
backEnd.viewDef->viewport.y1 + viewDef->scissor.y1,
viewDef->scissor.x2 + 1 - viewDef->scissor.x1,
viewDef->scissor.y2 + 1 - viewDef->scissor.y1 );
backEnd.currentScissor = viewDef->scissor;
}
// RB end
/*
=========================================================================================
DEPTH BUFFER RENDERING
=========================================================================================
*/
/*
==================
RB_FillDepthBufferGeneric
==================
*/
static void RB_FillDepthBufferGeneric( const drawSurf_t* const* drawSurfs, int numDrawSurfs )
{
for( int i = 0; i < numDrawSurfs; i++ )
{
const drawSurf_t* drawSurf = drawSurfs[i];
const idMaterial* shader = drawSurf->material;
// translucent surfaces don't put anything in the depth buffer and don't
// test against it, which makes them fail the mirror clip plane operation
if( shader->Coverage() == MC_TRANSLUCENT )
{
continue;
}
// get the expressions for conditionals / color / texcoords
const float* regs = drawSurf->shaderRegisters;
// if all stages of a material have been conditioned off, don't do anything
int stage = 0;
for( ; stage < shader->GetNumStages(); stage++ )
{
const shaderStage_t* pStage = shader->GetStage( stage );
// check the stage enable condition
if( regs[ pStage->conditionRegister ] != 0 )
{
break;
}
}
if( stage == shader->GetNumStages() )
{
continue;
}
// change the matrix if needed
if( drawSurf->space != backEnd.currentSpace )
{
RB_SetMVP( drawSurf->space->mvp );
backEnd.currentSpace = drawSurf->space;
}
uint64 surfGLState = 0;
// set polygon offset if necessary
if( shader->TestMaterialFlag( MF_POLYGONOFFSET ) )
{
surfGLState |= GLS_POLYGON_OFFSET;
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
}
// subviews will just down-modulate the color buffer
idVec4 color;
if( shader->GetSort() == SS_SUBVIEW )
{
surfGLState |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO | GLS_DEPTHFUNC_LESS;
color[0] = 1.0f;
color[1] = 1.0f;
color[2] = 1.0f;
color[3] = 1.0f;
}
else
{
// others just draw black
color[0] = 0.0f;
color[1] = 0.0f;
color[2] = 0.0f;
color[3] = 1.0f;
}
renderLog.OpenBlock( shader->GetName() );
bool drawSolid = false;
if( shader->Coverage() == MC_OPAQUE )
{
drawSolid = true;
}
else if( shader->Coverage() == MC_PERFORATED )
{
// we may have multiple alpha tested stages
// if the only alpha tested stages are condition register omitted,
// draw a normal opaque surface
bool didDraw = false;
// perforated surfaces may have multiple alpha tested stages
for( stage = 0; stage < shader->GetNumStages(); stage++ )
{
const shaderStage_t* pStage = shader->GetStage( stage );
if( !pStage->hasAlphaTest )
{
continue;
}
// check the stage enable condition
if( regs[ pStage->conditionRegister ] == 0 )
{
continue;
}
// if we at least tried to draw an alpha tested stage,
// we won't draw the opaque surface
didDraw = true;
// set the alpha modulate
color[3] = regs[ pStage->color.registers[3] ];
// skip the entire stage if alpha would be black
if( color[3] <= 0.0f )
{
continue;
}
uint64 stageGLState = surfGLState;
// set privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * pStage->privatePolygonOffset );
stageGLState |= GLS_POLYGON_OFFSET;
}
GL_Color( color );
#ifdef USE_CORE_PROFILE
GL_State( stageGLState );
idVec4 alphaTestValue( regs[ pStage->alphaTestRegister ] );
SetFragmentParm( RENDERPARM_ALPHA_TEST, alphaTestValue.ToFloatPtr() );
#else
GL_State( stageGLState | GLS_ALPHATEST_FUNC_GREATER | GLS_ALPHATEST_MAKE_REF( idMath::Ftob( 255.0f * regs[ pStage->alphaTestRegister ] ) ) );
#endif
if( drawSurf->jointCache )
{
renderProgManager.BindShader_TextureVertexColorSkinned();
}
else
{
renderProgManager.BindShader_TextureVertexColor();
}
RB_SetVertexColorParms( SVC_IGNORE );
// bind the texture
GL_SelectTexture( 0 );
pStage->texture.image->Bind();
// set texture matrix and texGens
RB_PrepareStageTexturing( pStage, drawSurf );
// must render with less-equal for Z-Cull to work properly
assert( ( GL_GetCurrentState() & GLS_DEPTHFUNC_BITS ) == GLS_DEPTHFUNC_LESS );
// draw it
RB_DrawElementsWithCounters( drawSurf );
// clean up
RB_FinishStageTexturing( pStage, drawSurf );
// unset privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
}
}
if( !didDraw )
{
drawSolid = true;
}
}
// draw the entire surface solid
if( drawSolid )
{
if( shader->GetSort() == SS_SUBVIEW )
{
renderProgManager.BindShader_Color();
GL_Color( color );
GL_State( surfGLState );
}
else
{
if( drawSurf->jointCache )
{
renderProgManager.BindShader_DepthSkinned();
}
else
{
renderProgManager.BindShader_Depth();
}
GL_State( surfGLState | GLS_ALPHAMASK );
}
// must render with less-equal for Z-Cull to work properly
assert( ( GL_GetCurrentState() & GLS_DEPTHFUNC_BITS ) == GLS_DEPTHFUNC_LESS );
// draw it
RB_DrawElementsWithCounters( drawSurf );
}
renderLog.CloseBlock();
}
#ifdef USE_CORE_PROFILE
SetFragmentParm( RENDERPARM_ALPHA_TEST, vec4_zero.ToFloatPtr() );
#endif
}
/*
=====================
RB_FillDepthBufferFast
Optimized fast path code.
If there are subview surfaces, they must be guarded in the depth buffer to allow
the mirror / subview to show through underneath the current view rendering.
Surfaces with perforated shaders need the full shader setup done, but should be
drawn after the opaque surfaces.
The bulk of the surfaces should be simple opaque geometry that can be drawn very rapidly.
If there are no subview surfaces, we could clear to black and use fast-Z rendering
on the 360.
=====================
*/
static void RB_FillDepthBufferFast( drawSurf_t** drawSurfs, int numDrawSurfs )
{
if( numDrawSurfs == 0 )
{
return;
}
// if we are just doing 2D rendering, no need to fill the depth buffer
if( backEnd.viewDef->viewEntitys == NULL )
{
return;
}
renderLog.OpenMainBlock( MRB_FILL_DEPTH_BUFFER );
renderLog.OpenBlock( "RB_FillDepthBufferFast" );
GL_StartDepthPass( backEnd.viewDef->scissor );
// force MVP change on first surface
backEnd.currentSpace = NULL;
// draw all the subview surfaces, which will already be at the start of the sorted list,
// with the general purpose path
GL_State( GLS_DEFAULT );
int surfNum;
for( surfNum = 0; surfNum < numDrawSurfs; surfNum++ )
{
if( drawSurfs[surfNum]->material->GetSort() != SS_SUBVIEW )
{
break;
}
RB_FillDepthBufferGeneric( &drawSurfs[surfNum], 1 );
}
const drawSurf_t** perforatedSurfaces = ( const drawSurf_t** )_alloca( numDrawSurfs * sizeof( drawSurf_t* ) );
int numPerforatedSurfaces = 0;
// draw all the opaque surfaces and build up a list of perforated surfaces that
// we will defer drawing until all opaque surfaces are done
GL_State( GLS_DEFAULT );
// continue checking past the subview surfaces
for( ; surfNum < numDrawSurfs; surfNum++ )
{
const drawSurf_t* surf = drawSurfs[ surfNum ];
const idMaterial* shader = surf->material;
// translucent surfaces don't put anything in the depth buffer
if( shader->Coverage() == MC_TRANSLUCENT )
{
continue;
}
if( shader->Coverage() == MC_PERFORATED )
{
// save for later drawing
perforatedSurfaces[ numPerforatedSurfaces ] = surf;
numPerforatedSurfaces++;
continue;
}
// set polygon offset?
// set mvp matrix
if( surf->space != backEnd.currentSpace )
{
RB_SetMVP( surf->space->mvp );
backEnd.currentSpace = surf->space;
}
renderLog.OpenBlock( shader->GetName() );
if( surf->jointCache )
{
renderProgManager.BindShader_DepthSkinned();
}
else
{
renderProgManager.BindShader_Depth();
}
// must render with less-equal for Z-Cull to work properly
assert( ( GL_GetCurrentState() & GLS_DEPTHFUNC_BITS ) == GLS_DEPTHFUNC_LESS );
// draw it solid
RB_DrawElementsWithCounters( surf );
renderLog.CloseBlock();
}
// draw all perforated surfaces with the general code path
if( numPerforatedSurfaces > 0 )
{
RB_FillDepthBufferGeneric( perforatedSurfaces, numPerforatedSurfaces );
}
// Allow platform specific data to be collected after the depth pass.
GL_FinishDepthPass();
renderLog.CloseBlock();
renderLog.CloseMainBlock();
}
/*
=========================================================================================
GENERAL INTERACTION RENDERING
=========================================================================================
*/
const int INTERACTION_TEXUNIT_BUMP = 0;
const int INTERACTION_TEXUNIT_FALLOFF = 1;
const int INTERACTION_TEXUNIT_PROJECTION = 2;
const int INTERACTION_TEXUNIT_DIFFUSE = 3;
const int INTERACTION_TEXUNIT_SPECULAR = 4;
const int INTERACTION_TEXUNIT_SHADOWMAPS = 5;
const int INTERACTION_TEXUNIT_JITTER = 6;
/*
==================
RB_SetupInteractionStage
==================
*/
static void RB_SetupInteractionStage( const shaderStage_t* surfaceStage, const float* surfaceRegs, const float lightColor[4],
idVec4 matrix[2], float color[4] )
{
if( surfaceStage->texture.hasMatrix )
{
matrix[0][0] = surfaceRegs[surfaceStage->texture.matrix[0][0]];
matrix[0][1] = surfaceRegs[surfaceStage->texture.matrix[0][1]];
matrix[0][2] = 0.0f;
matrix[0][3] = surfaceRegs[surfaceStage->texture.matrix[0][2]];
matrix[1][0] = surfaceRegs[surfaceStage->texture.matrix[1][0]];
matrix[1][1] = surfaceRegs[surfaceStage->texture.matrix[1][1]];
matrix[1][2] = 0.0f;
matrix[1][3] = surfaceRegs[surfaceStage->texture.matrix[1][2]];
// we attempt to keep scrolls from generating incredibly large texture values, but
// center rotations and center scales can still generate offsets that need to be > 1
if( matrix[0][3] < -40.0f || matrix[0][3] > 40.0f )
{
matrix[0][3] -= idMath::Ftoi( matrix[0][3] );
}
if( matrix[1][3] < -40.0f || matrix[1][3] > 40.0f )
{
matrix[1][3] -= idMath::Ftoi( matrix[1][3] );
}
}
else
{
matrix[0][0] = 1.0f;
matrix[0][1] = 0.0f;
matrix[0][2] = 0.0f;
matrix[0][3] = 0.0f;
matrix[1][0] = 0.0f;
matrix[1][1] = 1.0f;
matrix[1][2] = 0.0f;
matrix[1][3] = 0.0f;
}
if( color != NULL )
{
for( int i = 0; i < 4; i++ )
{
// clamp here, so cards with a greater range don't look different.
// we could perform overbrighting like we do for lights, but
// it doesn't currently look worth it.
color[i] = idMath::ClampFloat( 0.0f, 1.0f, surfaceRegs[surfaceStage->color.registers[i]] ) * lightColor[i];
}
}
}
/*
=================
RB_DrawSingleInteraction
=================
*/
static void RB_DrawSingleInteraction( drawInteraction_t* din )
{
if( din->bumpImage == NULL )
{
// stage wasn't actually an interaction
return;
}
if( din->diffuseImage == NULL || r_skipDiffuse.GetBool() )
{
// this isn't a YCoCg black, but it doesn't matter, because
// the diffuseColor will also be 0
din->diffuseImage = globalImages->blackImage;
}
if( din->specularImage == NULL || r_skipSpecular.GetBool() || din->ambientLight )
{
din->specularImage = globalImages->blackImage;
}
if( r_skipBump.GetBool() )
{
din->bumpImage = globalImages->flatNormalMap;
}
// if we wouldn't draw anything, don't call the Draw function
const bool diffuseIsBlack = ( din->diffuseImage == globalImages->blackImage )
|| ( ( din->diffuseColor[0] <= 0 ) && ( din->diffuseColor[1] <= 0 ) && ( din->diffuseColor[2] <= 0 ) );
const bool specularIsBlack = ( din->specularImage == globalImages->blackImage )
|| ( ( din->specularColor[0] <= 0 ) && ( din->specularColor[1] <= 0 ) && ( din->specularColor[2] <= 0 ) );
if( diffuseIsBlack && specularIsBlack )
{
return;
}
// bump matrix
SetVertexParm( RENDERPARM_BUMPMATRIX_S, din->bumpMatrix[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_BUMPMATRIX_T, din->bumpMatrix[1].ToFloatPtr() );
// diffuse matrix
SetVertexParm( RENDERPARM_DIFFUSEMATRIX_S, din->diffuseMatrix[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_DIFFUSEMATRIX_T, din->diffuseMatrix[1].ToFloatPtr() );
// specular matrix
SetVertexParm( RENDERPARM_SPECULARMATRIX_S, din->specularMatrix[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_SPECULARMATRIX_T, din->specularMatrix[1].ToFloatPtr() );
RB_SetVertexColorParms( din->vertexColor );
SetFragmentParm( RENDERPARM_DIFFUSEMODIFIER, din->diffuseColor.ToFloatPtr() );
SetFragmentParm( RENDERPARM_SPECULARMODIFIER, din->specularColor.ToFloatPtr() );
// texture 0 will be the per-surface bump map
GL_SelectTexture( INTERACTION_TEXUNIT_BUMP );
din->bumpImage->Bind();
// texture 3 is the per-surface diffuse map
GL_SelectTexture( INTERACTION_TEXUNIT_DIFFUSE );
din->diffuseImage->Bind();
// texture 4 is the per-surface specular map
GL_SelectTexture( INTERACTION_TEXUNIT_SPECULAR );
din->specularImage->Bind();
RB_DrawElementsWithCounters( din->surf );
}
/*
=================
RB_SetupForFastPathInteractions
These are common for all fast path surfaces
=================
*/
static void RB_SetupForFastPathInteractions( const idVec4& diffuseColor, const idVec4& specularColor )
{
const idVec4 sMatrix( 1, 0, 0, 0 );
const idVec4 tMatrix( 0, 1, 0, 0 );
// bump matrix
SetVertexParm( RENDERPARM_BUMPMATRIX_S, sMatrix.ToFloatPtr() );
SetVertexParm( RENDERPARM_BUMPMATRIX_T, tMatrix.ToFloatPtr() );
// diffuse matrix
SetVertexParm( RENDERPARM_DIFFUSEMATRIX_S, sMatrix.ToFloatPtr() );
SetVertexParm( RENDERPARM_DIFFUSEMATRIX_T, tMatrix.ToFloatPtr() );
// specular matrix
SetVertexParm( RENDERPARM_SPECULARMATRIX_S, sMatrix.ToFloatPtr() );
SetVertexParm( RENDERPARM_SPECULARMATRIX_T, tMatrix.ToFloatPtr() );
RB_SetVertexColorParms( SVC_IGNORE );
SetFragmentParm( RENDERPARM_DIFFUSEMODIFIER, diffuseColor.ToFloatPtr() );
SetFragmentParm( RENDERPARM_SPECULARMODIFIER, specularColor.ToFloatPtr() );
}
/*
=============
RB_RenderInteractions
With added sorting and trivial path work.
=============
*/
static void RB_RenderInteractions( const drawSurf_t* surfList, const viewLight_t* vLight, int depthFunc, bool performStencilTest, bool useLightDepthBounds )
{
if( surfList == NULL )
{
return;
}
// change the scissor if needed, it will be constant across all the surfaces lit by the light
if( !backEnd.currentScissor.Equals( vLight->scissorRect ) && r_useScissor.GetBool() )
{
GL_Scissor( backEnd.viewDef->viewport.x1 + vLight->scissorRect.x1,
backEnd.viewDef->viewport.y1 + vLight->scissorRect.y1,
vLight->scissorRect.x2 + 1 - vLight->scissorRect.x1,
vLight->scissorRect.y2 + 1 - vLight->scissorRect.y1 );
backEnd.currentScissor = vLight->scissorRect;
}
// perform setup here that will be constant for all interactions
if( performStencilTest )
{
GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | depthFunc | GLS_STENCIL_FUNC_EQUAL | GLS_STENCIL_MAKE_REF( STENCIL_SHADOW_TEST_VALUE ) | GLS_STENCIL_MAKE_MASK( STENCIL_SHADOW_MASK_VALUE ) );
}
else
{
GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | depthFunc | GLS_STENCIL_FUNC_ALWAYS );
}
// some rare lights have multiple animating stages, loop over them outside the surface list
const idMaterial* lightShader = vLight->lightShader;
const float* lightRegs = vLight->shaderRegisters;
drawInteraction_t inter = {};
inter.ambientLight = lightShader->IsAmbientLight();
//---------------------------------
// Split out the complex surfaces from the fast-path surfaces
// so we can do the fast path ones all in a row.
// The surfaces should already be sorted by space because they
// are added single-threaded, and there is only a negligable amount
// of benefit to trying to sort by materials.
//---------------------------------
static const int MAX_INTERACTIONS_PER_LIGHT = 1024;
static const int MAX_COMPLEX_INTERACTIONS_PER_LIGHT = 256;
idStaticList< const drawSurf_t*, MAX_INTERACTIONS_PER_LIGHT > allSurfaces;
idStaticList< const drawSurf_t*, MAX_COMPLEX_INTERACTIONS_PER_LIGHT > complexSurfaces;
for( const drawSurf_t* walk = surfList; walk != NULL; walk = walk->nextOnLight )
{
// make sure the triangle culling is done
if( walk->shadowVolumeState != SHADOWVOLUME_DONE )
{
assert( walk->shadowVolumeState == SHADOWVOLUME_UNFINISHED || walk->shadowVolumeState == SHADOWVOLUME_DONE );
uint64 start = Sys_Microseconds();
while( walk->shadowVolumeState == SHADOWVOLUME_UNFINISHED )
{
Sys_Yield();
}
uint64 end = Sys_Microseconds();
backEnd.pc.shadowMicroSec += end - start;
}
const idMaterial* surfaceShader = walk->material;
if( surfaceShader->GetFastPathBumpImage() )
{
allSurfaces.Append( walk );
}
else
{
complexSurfaces.Append( walk );
}
}
for( int i = 0; i < complexSurfaces.Num(); i++ )
{
allSurfaces.Append( complexSurfaces[i] );
}
bool lightDepthBoundsDisabled = false;
// RB begin
if( r_useShadowMapping.GetBool() )
{
const static int JITTER_SIZE = 128;
// default high quality
float jitterSampleScale = 1.0f;
float shadowMapSamples = r_shadowMapSamples.GetInteger();
// screen power of two correction factor
float screenCorrectionParm[4];
screenCorrectionParm[0] = 1.0f / ( JITTER_SIZE * shadowMapSamples ) ;
screenCorrectionParm[1] = 1.0f / JITTER_SIZE;
screenCorrectionParm[2] = 1.0f / shadowMapResolutions[vLight->shadowLOD];
screenCorrectionParm[3] = vLight->parallel ? r_shadowMapSunDepthBiasScale.GetFloat() : r_shadowMapRegularDepthBiasScale.GetFloat();
SetFragmentParm( RENDERPARM_SCREENCORRECTIONFACTOR, screenCorrectionParm ); // rpScreenCorrectionFactor
float jitterTexScale[4];
jitterTexScale[0] = r_shadowMapJitterScale.GetFloat() * jitterSampleScale; // TODO shadow buffer size fraction shadowMapSize / maxShadowMapSize
jitterTexScale[1] = r_shadowMapJitterScale.GetFloat() * jitterSampleScale;
jitterTexScale[2] = -r_shadowMapBiasScale.GetFloat();
jitterTexScale[3] = 0.0f;
SetFragmentParm( RENDERPARM_JITTERTEXSCALE, jitterTexScale ); // rpJitterTexScale
float jitterTexOffset[4];
if( r_shadowMapRandomizeJitter.GetBool() )
{
jitterTexOffset[0] = ( rand() & 255 ) / 255.0;
jitterTexOffset[1] = ( rand() & 255 ) / 255.0;
}
else
{
jitterTexOffset[0] = 0;
jitterTexOffset[1] = 0;
}
jitterTexOffset[2] = 0.0f;
jitterTexOffset[3] = 0.0f;
SetFragmentParm( RENDERPARM_JITTERTEXOFFSET, jitterTexOffset ); // rpJitterTexOffset
if( vLight->parallel )
{
float cascadeDistances[4];
cascadeDistances[0] = backEnd.viewDef->frustumSplitDistances[0];
cascadeDistances[1] = backEnd.viewDef->frustumSplitDistances[1];
cascadeDistances[2] = backEnd.viewDef->frustumSplitDistances[2];
cascadeDistances[3] = backEnd.viewDef->frustumSplitDistances[3];
SetFragmentParm( RENDERPARM_CASCADEDISTANCES, cascadeDistances ); // rpCascadeDistances
}
}
// RB end
for( int lightStageNum = 0; lightStageNum < lightShader->GetNumStages(); lightStageNum++ )
{
const shaderStage_t* lightStage = lightShader->GetStage( lightStageNum );
// ignore stages that fail the condition
if( !lightRegs[ lightStage->conditionRegister ] )
{
continue;
}
const float lightScale = r_lightScale.GetFloat();
const idVec4 lightColor(
lightScale * lightRegs[ lightStage->color.registers[0] ],
lightScale * lightRegs[ lightStage->color.registers[1] ],
lightScale * lightRegs[ lightStage->color.registers[2] ],
lightRegs[ lightStage->color.registers[3] ] );
// apply the world-global overbright and the 2x factor for specular
const idVec4 diffuseColor = lightColor;
const idVec4 specularColor = lightColor * 2.0f;
float lightTextureMatrix[16];
if( lightStage->texture.hasMatrix )
{
RB_GetShaderTextureMatrix( lightRegs, &lightStage->texture, lightTextureMatrix );
}
// texture 1 will be the light falloff texture
GL_SelectTexture( INTERACTION_TEXUNIT_FALLOFF );
vLight->falloffImage->Bind();
// texture 2 will be the light projection texture
GL_SelectTexture( INTERACTION_TEXUNIT_PROJECTION );
lightStage->texture.image->Bind();
if( r_useShadowMapping.GetBool() )
{
// texture 5 will be the shadow maps array
GL_SelectTexture( INTERACTION_TEXUNIT_SHADOWMAPS );
globalImages->shadowImage[vLight->shadowLOD]->Bind();
// texture 6 will be the jitter texture for soft shadowing
GL_SelectTexture( INTERACTION_TEXUNIT_JITTER );
if( r_shadowMapSamples.GetInteger() == 16 )
{
globalImages->jitterImage16->Bind();
}
else if( r_shadowMapSamples.GetInteger() == 4 )
{
globalImages->jitterImage4->Bind();
}
else
{
globalImages->jitterImage1->Bind();
}
}
// force the light textures to not use anisotropic filtering, which is wasted on them
// all of the texture sampler parms should be constant for all interactions, only
// the actual texture image bindings will change
//----------------------------------
// For all surfaces on this light list, generate an interaction for this light stage
//----------------------------------
// setup renderparms assuming we will be drawing trivial surfaces first
RB_SetupForFastPathInteractions( diffuseColor, specularColor );
// even if the space does not change between light stages, each light stage may need a different lightTextureMatrix baked in
backEnd.currentSpace = NULL;
for( int sortedSurfNum = 0; sortedSurfNum < allSurfaces.Num(); sortedSurfNum++ )
{
const drawSurf_t* const surf = allSurfaces[ sortedSurfNum ];
// select the render prog
if( lightShader->IsAmbientLight() )
{
if( surf->jointCache )
{
renderProgManager.BindShader_InteractionAmbientSkinned();
}
else
{
renderProgManager.BindShader_InteractionAmbient();
}
}
else
{
if( r_useShadowMapping.GetBool() && vLight->globalShadows )
{
// RB: we have shadow mapping enabled and shadow maps so do a shadow compare
if( vLight->parallel )
{
if( surf->jointCache )
{
renderProgManager.BindShader_Interaction_ShadowMapping_Parallel_Skinned();
}
else
{
renderProgManager.BindShader_Interaction_ShadowMapping_Parallel();
}
}
else if( vLight->pointLight )
{
if( surf->jointCache )
{
renderProgManager.BindShader_Interaction_ShadowMapping_Point_Skinned();
}
else
{
renderProgManager.BindShader_Interaction_ShadowMapping_Point();
}
}
else
{
if( surf->jointCache )
{
renderProgManager.BindShader_Interaction_ShadowMapping_Spot_Skinned();
}
else
{
renderProgManager.BindShader_Interaction_ShadowMapping_Spot();
}
}
}
else
{
if( surf->jointCache )
{
renderProgManager.BindShader_InteractionSkinned();
}
else
{
renderProgManager.BindShader_Interaction();
}
}
}
const idMaterial* surfaceShader = surf->material;
const float* surfaceRegs = surf->shaderRegisters;
inter.surf = surf;
// change the MVP matrix, view/light origin and light projection vectors if needed
if( surf->space != backEnd.currentSpace )
{
backEnd.currentSpace = surf->space;
// turn off the light depth bounds test if this model is rendered with a depth hack
if( useLightDepthBounds )
{
if( !surf->space->weaponDepthHack && surf->space->modelDepthHack == 0.0f )
{
if( lightDepthBoundsDisabled )
{
GL_DepthBoundsTest( vLight->scissorRect.zmin, vLight->scissorRect.zmax );
lightDepthBoundsDisabled = false;
}
}
else
{
if( !lightDepthBoundsDisabled )
{
GL_DepthBoundsTest( 0.0f, 0.0f );
lightDepthBoundsDisabled = true;
}
}
}
// model-view-projection
RB_SetMVP( surf->space->mvp );
// RB begin
idRenderMatrix modelMatrix;
idRenderMatrix::Transpose( *( idRenderMatrix* )surf->space->modelMatrix, modelMatrix );
SetVertexParms( RENDERPARM_MODELMATRIX_X, modelMatrix[0], 4 );
// for determining the shadow mapping cascades
idRenderMatrix modelViewMatrix, tmp;
idRenderMatrix::Transpose( *( idRenderMatrix* )surf->space->modelViewMatrix, modelViewMatrix );
SetVertexParms( RENDERPARM_MODELVIEWMATRIX_X, modelViewMatrix[0], 4 );
idVec4 globalLightOrigin( vLight->globalLightOrigin.x, vLight->globalLightOrigin.y, vLight->globalLightOrigin.z, 1.0f );
SetVertexParm( RENDERPARM_GLOBALLIGHTORIGIN, globalLightOrigin.ToFloatPtr() );
// RB end
// tranform the light/view origin into model local space
idVec4 localLightOrigin( 0.0f );
idVec4 localViewOrigin( 1.0f );
R_GlobalPointToLocal( surf->space->modelMatrix, vLight->globalLightOrigin, localLightOrigin.ToVec3() );
R_GlobalPointToLocal( surf->space->modelMatrix, backEnd.viewDef->renderView.vieworg, localViewOrigin.ToVec3() );
// set the local light/view origin
SetVertexParm( RENDERPARM_LOCALLIGHTORIGIN, localLightOrigin.ToFloatPtr() );
SetVertexParm( RENDERPARM_LOCALVIEWORIGIN, localViewOrigin.ToFloatPtr() );
// transform the light project into model local space
idPlane lightProjection[4];
for( int i = 0; i < 4; i++ )
{
R_GlobalPlaneToLocal( surf->space->modelMatrix, vLight->lightProject[i], lightProjection[i] );
}
// optionally multiply the local light projection by the light texture matrix
if( lightStage->texture.hasMatrix )
{
RB_BakeTextureMatrixIntoTexgen( lightProjection, lightTextureMatrix );
}
// set the light projection
SetVertexParm( RENDERPARM_LIGHTPROJECTION_S, lightProjection[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_LIGHTPROJECTION_T, lightProjection[1].ToFloatPtr() );
SetVertexParm( RENDERPARM_LIGHTPROJECTION_Q, lightProjection[2].ToFloatPtr() );
SetVertexParm( RENDERPARM_LIGHTFALLOFF_S, lightProjection[3].ToFloatPtr() );
// RB begin
if( r_useShadowMapping.GetBool() )
{
if( vLight->parallel )
{
for( int i = 0; i < ( r_shadowMapSplits.GetInteger() + 1 ); i++ )
{
idRenderMatrix modelToShadowMatrix;
idRenderMatrix::Multiply( backEnd.shadowV[i], modelMatrix, modelToShadowMatrix );
idRenderMatrix shadowClipMVP;
idRenderMatrix::Multiply( backEnd.shadowP[i], modelToShadowMatrix, shadowClipMVP );
idRenderMatrix shadowWindowMVP;
idRenderMatrix::Multiply( renderMatrix_clipSpaceToWindowSpace, shadowClipMVP, shadowWindowMVP );
SetVertexParms( ( renderParm_t )( RENDERPARM_SHADOW_MATRIX_0_X + i * 4 ), shadowWindowMVP[0], 4 );
}
}
else if( vLight->pointLight )
{
for( int i = 0; i < 6; i++ )
{
idRenderMatrix modelToShadowMatrix;
idRenderMatrix::Multiply( backEnd.shadowV[i], modelMatrix, modelToShadowMatrix );
idRenderMatrix shadowClipMVP;
idRenderMatrix::Multiply( backEnd.shadowP[i], modelToShadowMatrix, shadowClipMVP );
idRenderMatrix shadowWindowMVP;
idRenderMatrix::Multiply( renderMatrix_clipSpaceToWindowSpace, shadowClipMVP, shadowWindowMVP );
SetVertexParms( ( renderParm_t )( RENDERPARM_SHADOW_MATRIX_0_X + i * 4 ), shadowWindowMVP[0], 4 );
}
}
else
{
// spot light
idRenderMatrix modelToShadowMatrix;
idRenderMatrix::Multiply( backEnd.shadowV[0], modelMatrix, modelToShadowMatrix );
idRenderMatrix shadowClipMVP;
idRenderMatrix::Multiply( backEnd.shadowP[0], modelToShadowMatrix, shadowClipMVP );
SetVertexParms( ( renderParm_t )( RENDERPARM_SHADOW_MATRIX_0_X ), shadowClipMVP[0], 4 );
}
}
// RB end
}
// check for the fast path
if( surfaceShader->GetFastPathBumpImage() && !r_skipInteractionFastPath.GetBool() )
{
renderLog.OpenBlock( surf->material->GetName() );
// texture 0 will be the per-surface bump map
GL_SelectTexture( INTERACTION_TEXUNIT_BUMP );
surfaceShader->GetFastPathBumpImage()->Bind();
// texture 3 is the per-surface diffuse map
GL_SelectTexture( INTERACTION_TEXUNIT_DIFFUSE );
surfaceShader->GetFastPathDiffuseImage()->Bind();
// texture 4 is the per-surface specular map
GL_SelectTexture( INTERACTION_TEXUNIT_SPECULAR );
surfaceShader->GetFastPathSpecularImage()->Bind();
RB_DrawElementsWithCounters( surf );
renderLog.CloseBlock();
continue;
}
renderLog.OpenBlock( surf->material->GetName() );
inter.bumpImage = NULL;
inter.specularImage = NULL;
inter.diffuseImage = NULL;
inter.diffuseColor[0] = inter.diffuseColor[1] = inter.diffuseColor[2] = inter.diffuseColor[3] = 0;
inter.specularColor[0] = inter.specularColor[1] = inter.specularColor[2] = inter.specularColor[3] = 0;
// go through the individual surface stages
//
// This is somewhat arcane because of the old support for video cards that had to render
// interactions in multiple passes.
//
// We also have the very rare case of some materials that have conditional interactions
// for the "hell writing" that can be shined on them.
for( int surfaceStageNum = 0; surfaceStageNum < surfaceShader->GetNumStages(); surfaceStageNum++ )
{
const shaderStage_t* surfaceStage = surfaceShader->GetStage( surfaceStageNum );
switch( surfaceStage->lighting )
{
case SL_COVERAGE:
{
// ignore any coverage stages since they should only be used for the depth fill pass
// for diffuse stages that use alpha test.
break;
}
case SL_AMBIENT:
{
// ignore ambient stages while drawing interactions
break;
}
case SL_BUMP:
{
// ignore stage that fails the condition
if( !surfaceRegs[ surfaceStage->conditionRegister ] )
{
break;
}
// draw any previous interaction
if( inter.bumpImage != NULL )
{
RB_DrawSingleInteraction( &inter );
}
inter.bumpImage = surfaceStage->texture.image;
inter.diffuseImage = NULL;
inter.specularImage = NULL;
RB_SetupInteractionStage( surfaceStage, surfaceRegs, NULL,
inter.bumpMatrix, NULL );
break;
}
case SL_DIFFUSE:
{
// ignore stage that fails the condition
if( !surfaceRegs[ surfaceStage->conditionRegister ] )
{
break;
}
// draw any previous interaction
if( inter.diffuseImage != NULL )
{
RB_DrawSingleInteraction( &inter );
}
inter.diffuseImage = surfaceStage->texture.image;
inter.vertexColor = surfaceStage->vertexColor;
RB_SetupInteractionStage( surfaceStage, surfaceRegs, diffuseColor.ToFloatPtr(),
inter.diffuseMatrix, inter.diffuseColor.ToFloatPtr() );
break;
}
case SL_SPECULAR:
{
// ignore stage that fails the condition
if( !surfaceRegs[ surfaceStage->conditionRegister ] )
{
break;
}
// draw any previous interaction
if( inter.specularImage != NULL )
{
RB_DrawSingleInteraction( &inter );
}
inter.specularImage = surfaceStage->texture.image;
inter.vertexColor = surfaceStage->vertexColor;
RB_SetupInteractionStage( surfaceStage, surfaceRegs, specularColor.ToFloatPtr(),
inter.specularMatrix, inter.specularColor.ToFloatPtr() );
break;
}
}
}
// draw the final interaction
RB_DrawSingleInteraction( &inter );
renderLog.CloseBlock();
}
}
if( useLightDepthBounds && lightDepthBoundsDisabled )
{
GL_DepthBoundsTest( vLight->scissorRect.zmin, vLight->scissorRect.zmax );
}
renderProgManager.Unbind();
}
/*
==============================================================================================
STENCIL SHADOW RENDERING
==============================================================================================
*/
/*
=====================
RB_StencilShadowPass
The stencil buffer should have been set to 128 on any surfaces that might receive shadows.
=====================
*/
static void RB_StencilShadowPass( const drawSurf_t* drawSurfs, const viewLight_t* vLight )
{
if( r_skipShadows.GetBool() )
{
return;
}
if( drawSurfs == NULL )
{
return;
}
RENDERLOG_PRINTF( "---------- RB_StencilShadowPass ----------\n" );
renderProgManager.BindShader_Shadow();
GL_SelectTexture( 0 );
globalImages->BindNull();
uint64 glState = 0;
// for visualizing the shadows
if( r_showShadows.GetInteger() )
{
// set the debug shadow color
SetFragmentParm( RENDERPARM_COLOR, colorMagenta.ToFloatPtr() );
if( r_showShadows.GetInteger() == 2 )
{
// draw filled in
glState = GLS_DEPTHMASK | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_LESS;
}
else
{
// draw as lines, filling the depth buffer
glState = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO | GLS_POLYMODE_LINE | GLS_DEPTHFUNC_ALWAYS;
}
}
else
{
// don't write to the color or depth buffer, just the stencil buffer
glState = GLS_DEPTHMASK | GLS_COLORMASK | GLS_ALPHAMASK | GLS_DEPTHFUNC_LESS;
}
GL_PolygonOffset( r_shadowPolygonFactor.GetFloat(), -r_shadowPolygonOffset.GetFloat() );
// the actual stencil func will be set in the draw code, but we need to make sure it isn't
// disabled here, and that the value will get reset for the interactions without looking
// like a no-change-required
GL_State( glState | GLS_STENCIL_OP_FAIL_KEEP | GLS_STENCIL_OP_ZFAIL_KEEP | GLS_STENCIL_OP_PASS_INCR |
GLS_STENCIL_MAKE_REF( STENCIL_SHADOW_TEST_VALUE ) | GLS_STENCIL_MAKE_MASK( STENCIL_SHADOW_MASK_VALUE ) | GLS_POLYGON_OFFSET );
// Two Sided Stencil reduces two draw calls to one for slightly faster shadows
GL_Cull( CT_TWO_SIDED );
// process the chain of shadows with the current rendering state
backEnd.currentSpace = NULL;
for( const drawSurf_t* drawSurf = drawSurfs; drawSurf != NULL; drawSurf = drawSurf->nextOnLight )
{
if( drawSurf->scissorRect.IsEmpty() )
{
continue; // !@# FIXME: find out why this is sometimes being hit!
// temporarily jump over the scissor and draw so the gl error callback doesn't get hit
}
// make sure the shadow volume is done
if( drawSurf->shadowVolumeState != SHADOWVOLUME_DONE )
{
assert( drawSurf->shadowVolumeState == SHADOWVOLUME_UNFINISHED || drawSurf->shadowVolumeState == SHADOWVOLUME_DONE );
uint64 start = Sys_Microseconds();
while( drawSurf->shadowVolumeState == SHADOWVOLUME_UNFINISHED )
{
Sys_Yield();
}
uint64 end = Sys_Microseconds();
backEnd.pc.shadowMicroSec += end - start;
}
if( drawSurf->numIndexes == 0 )
{
continue; // a job may have created an empty shadow volume
}
if( !backEnd.currentScissor.Equals( drawSurf->scissorRect ) && r_useScissor.GetBool() )
{
// change the scissor
GL_Scissor( backEnd.viewDef->viewport.x1 + drawSurf->scissorRect.x1,
backEnd.viewDef->viewport.y1 + drawSurf->scissorRect.y1,
drawSurf->scissorRect.x2 + 1 - drawSurf->scissorRect.x1,
drawSurf->scissorRect.y2 + 1 - drawSurf->scissorRect.y1 );
backEnd.currentScissor = drawSurf->scissorRect;
}
if( drawSurf->space != backEnd.currentSpace )
{
// change the matrix
RB_SetMVP( drawSurf->space->mvp );
// set the local light position to allow the vertex program to project the shadow volume end cap to infinity
idVec4 localLight( 0.0f );
R_GlobalPointToLocal( drawSurf->space->modelMatrix, vLight->globalLightOrigin, localLight.ToVec3() );
SetVertexParm( RENDERPARM_LOCALLIGHTORIGIN, localLight.ToFloatPtr() );
backEnd.currentSpace = drawSurf->space;
}
if( r_showShadows.GetInteger() == 0 )
{
if( drawSurf->jointCache )
{
renderProgManager.BindShader_ShadowSkinned();
}
else
{
renderProgManager.BindShader_Shadow();
}
}
else
{
if( drawSurf->jointCache )
{
renderProgManager.BindShader_ShadowDebugSkinned();
}
else
{
renderProgManager.BindShader_ShadowDebug();
}
}
// set depth bounds per shadow
if( r_useShadowDepthBounds.GetBool() )
{
GL_DepthBoundsTest( drawSurf->scissorRect.zmin, drawSurf->scissorRect.zmax );
}
// Determine whether or not the shadow volume needs to be rendered with Z-pass or
// Z-fail. It is worthwhile to spend significant resources to reduce the number of
// cases where shadow volumes need to be rendered with Z-fail because Z-fail
// rendering can be significantly slower even on today's hardware. For instance,
// on NVIDIA hardware Z-fail rendering causes the Z-Cull to be used in reverse:
// Z-near becomes Z-far (trivial accept becomes trivial reject). Using the Z-Cull
// in reverse is far less efficient because the Z-Cull only stores Z-near per 16x16
// pixels while the Z-far is stored per 4x2 pixels. (The Z-near coallesce buffer
// which has 4x4 granularity is only used when updating the depth which is not the
// case for shadow volumes.) Note that it is also important to NOT use a Z-Cull
// reconstruct because that would clear the Z-near of the Z-Cull which results in
// no trivial rejection for Z-fail stencil shadow rendering.
const bool renderZPass = ( drawSurf->renderZFail == 0 ) || r_forceZPassStencilShadows.GetBool();
if( renderZPass )
{
// Z-pass
glStencilOpSeparate( GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR );
glStencilOpSeparate( GL_BACK, GL_KEEP, GL_KEEP, GL_DECR );
}
else if( r_useStencilShadowPreload.GetBool() )
{
// preload + Z-pass
glStencilOpSeparate( GL_FRONT, GL_KEEP, GL_DECR, GL_DECR );
glStencilOpSeparate( GL_BACK, GL_KEEP, GL_INCR, GL_INCR );
}
else
{
// Z-fail
// warning this procedure is patented in backwards places where software patents are valid
glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_DECR, GL_KEEP);
glStencilOpSeparate(GL_BACK, GL_KEEP, GL_INCR, GL_KEEP);
}
// get vertex buffer
const vertCacheHandle_t vbHandle = drawSurf->shadowCache;
idVertexBuffer* vertexBuffer;
if( vertexCache.CacheIsStatic( vbHandle ) )
{
vertexBuffer = &vertexCache.staticData.vertexBuffer;
}
else
{
const uint64 frameNum = ( int )( vbHandle >> VERTCACHE_FRAME_SHIFT ) & VERTCACHE_FRAME_MASK;
if( frameNum != ( ( vertexCache.currentFrame - 1 ) & VERTCACHE_FRAME_MASK ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, vertexBuffer == NULL" );
continue;
}
vertexBuffer = &vertexCache.frameData[vertexCache.drawListNum].vertexBuffer;
}
const int vertOffset = ( int )( vbHandle >> VERTCACHE_OFFSET_SHIFT ) & VERTCACHE_OFFSET_MASK;
// get index buffer
const vertCacheHandle_t ibHandle = drawSurf->indexCache;
idIndexBuffer* indexBuffer;
if( vertexCache.CacheIsStatic( ibHandle ) )
{
indexBuffer = &vertexCache.staticData.indexBuffer;
}
else
{
const uint64 frameNum = ( int )( ibHandle >> VERTCACHE_FRAME_SHIFT ) & VERTCACHE_FRAME_MASK;
if( frameNum != ( ( vertexCache.currentFrame - 1 ) & VERTCACHE_FRAME_MASK ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, indexBuffer == NULL" );
continue;
}
indexBuffer = &vertexCache.frameData[vertexCache.drawListNum].indexBuffer;
}
const uint64 indexOffset = ( int )( ibHandle >> VERTCACHE_OFFSET_SHIFT ) & VERTCACHE_OFFSET_MASK;
RENDERLOG_PRINTF( "Binding Buffers: %p %p\n", vertexBuffer, indexBuffer );
// RB: 64 bit fixes, changed GLuint to GLintptr
if( backEnd.glState.currentIndexBuffer != ( GLintptr )indexBuffer->GetAPIObject() || !r_useStateCaching.GetBool() )
{
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ( GLintptr )indexBuffer->GetAPIObject() );
backEnd.glState.currentIndexBuffer = ( GLintptr )indexBuffer->GetAPIObject();
}
if( drawSurf->jointCache )
{
assert( renderProgManager.ShaderUsesJoints() );
idJointBuffer jointBuffer;
if( !vertexCache.GetJointBuffer( drawSurf->jointCache, &jointBuffer ) )
{
idLib::Warning( "RB_DrawElementsWithCounters, jointBuffer == NULL" );
continue;
}
assert( ( jointBuffer.GetOffset() & ( glConfig.uniformBufferOffsetAlignment - 1 ) ) == 0 );
const GLintptr ubo = reinterpret_cast< GLintptr >( jointBuffer.GetAPIObject() );
glBindBufferRange( GL_UNIFORM_BUFFER, 0, ubo, jointBuffer.GetOffset(), jointBuffer.GetNumJoints() * sizeof( idJointMat ) );
if( ( backEnd.glState.vertexLayout != LAYOUT_DRAW_SHADOW_VERT_SKINNED ) || ( backEnd.glState.currentVertexBuffer != ( GLintptr )vertexBuffer->GetAPIObject() ) || !r_useStateCaching.GetBool() )
{
glBindBuffer( GL_ARRAY_BUFFER, ( GLintptr )vertexBuffer->GetAPIObject() );
backEnd.glState.currentVertexBuffer = ( GLintptr )vertexBuffer->GetAPIObject();
glEnableVertexAttribArray( PC_ATTRIB_INDEX_VERTEX );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_NORMAL );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_COLOR );
glEnableVertexAttribArray( PC_ATTRIB_INDEX_COLOR2 );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_ST );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_TANGENT );
#if defined(USE_GLES2) || defined(USE_GLES3)
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 4, GL_FLOAT, GL_FALSE, sizeof( idShadowVertSkinned ), ( void* )( vertOffset + SHADOWVERTSKINNED_XYZW_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idShadowVertSkinned ), ( void* )( vertOffset + SHADOWVERTSKINNED_COLOR_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idShadowVertSkinned ), ( void* )( vertOffset + SHADOWVERTSKINNED_COLOR2_OFFSET ) );
#else
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 4, GL_FLOAT, GL_FALSE, sizeof( idShadowVertSkinned ), ( void* )( SHADOWVERTSKINNED_XYZW_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idShadowVertSkinned ), ( void* )( SHADOWVERTSKINNED_COLOR_OFFSET ) );
glVertexAttribPointer( PC_ATTRIB_INDEX_COLOR2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( idShadowVertSkinned ), ( void* )( SHADOWVERTSKINNED_COLOR2_OFFSET ) );
#endif
backEnd.glState.vertexLayout = LAYOUT_DRAW_SHADOW_VERT_SKINNED;
}
}
else
{
if( ( backEnd.glState.vertexLayout != LAYOUT_DRAW_SHADOW_VERT ) || ( backEnd.glState.currentVertexBuffer != ( GLintptr )vertexBuffer->GetAPIObject() ) || !r_useStateCaching.GetBool() )
{
glBindBuffer( GL_ARRAY_BUFFER, ( GLintptr )vertexBuffer->GetAPIObject() );
backEnd.glState.currentVertexBuffer = ( GLintptr )vertexBuffer->GetAPIObject();
glEnableVertexAttribArray( PC_ATTRIB_INDEX_VERTEX );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_NORMAL );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_COLOR );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_COLOR2 );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_ST );
glDisableVertexAttribArray( PC_ATTRIB_INDEX_TANGENT );
#if defined(USE_GLES2) || defined(USE_GLES3)
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 4, GL_FLOAT, GL_FALSE, sizeof( idShadowVert ), ( void* )( vertOffset + SHADOWVERT_XYZW_OFFSET ) );
#else
glVertexAttribPointer( PC_ATTRIB_INDEX_VERTEX, 4, GL_FLOAT, GL_FALSE, sizeof( idShadowVert ), ( void* )( SHADOWVERT_XYZW_OFFSET ) );
#endif
backEnd.glState.vertexLayout = LAYOUT_DRAW_SHADOW_VERT;
}
}
// RB end
renderProgManager.CommitUniforms();
if( drawSurf->jointCache )
{
#if defined(USE_GLES3) //defined(USE_GLES2)
glDrawElements( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset );
#else
glDrawElementsBaseVertex( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset, vertOffset / sizeof( idShadowVertSkinned ) );
#endif
}
else
{
#if defined(USE_GLES3)
glDrawElements( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset );
#else
glDrawElementsBaseVertex( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset, vertOffset / sizeof( idShadowVert ) );
#endif
}
// RB: added stats
backEnd.pc.c_shadowElements++;
backEnd.pc.c_shadowIndexes += drawSurf->numIndexes;
// RB end
if( !renderZPass && r_useStencilShadowPreload.GetBool() )
{
// render again with Z-pass
glStencilOpSeparate( GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR );
glStencilOpSeparate( GL_BACK, GL_KEEP, GL_KEEP, GL_DECR );
if( drawSurf->jointCache )
{
#if defined(USE_GLES3)
glDrawElements( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset );
#else
glDrawElementsBaseVertex( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset, vertOffset / sizeof( idShadowVertSkinned ) );
#endif
}
else
{
#if defined(USE_GLES3)
glDrawElements( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset );
#else
glDrawElementsBaseVertex( GL_TRIANGLES, r_singleTriangle.GetBool() ? 3 : drawSurf->numIndexes, GL_INDEX_TYPE, ( triIndex_t* )indexOffset, vertOffset / sizeof( idShadowVert ) );
#endif
}
// RB: added stats
backEnd.pc.c_shadowElements++;
backEnd.pc.c_shadowIndexes += drawSurf->numIndexes;
// RB end
}
}
// cleanup the shadow specific rendering state
GL_Cull( CT_FRONT_SIDED );
// reset depth bounds
if( r_useShadowDepthBounds.GetBool() )
{
if( r_useLightDepthBounds.GetBool() )
{
GL_DepthBoundsTest( vLight->scissorRect.zmin, vLight->scissorRect.zmax );
}
else
{
GL_DepthBoundsTest( 0.0f, 0.0f );
}
}
}
/*
==================
RB_StencilSelectLight
Deform the zeroOneCubeModel to exactly cover the light volume. Render the deformed cube model to the stencil buffer in
such a way that only fragments that are directly visible and contained within the volume will be written creating a
mask to be used by the following stencil shadow and draw interaction passes.
==================
*/
static void RB_StencilSelectLight( const viewLight_t* vLight )
{
renderLog.OpenBlock( "Stencil Select" );
// enable the light scissor
if( !backEnd.currentScissor.Equals( vLight->scissorRect ) && r_useScissor.GetBool() )
{
GL_Scissor( backEnd.viewDef->viewport.x1 + vLight->scissorRect.x1,
backEnd.viewDef->viewport.y1 + vLight->scissorRect.y1,
vLight->scissorRect.x2 + 1 - vLight->scissorRect.x1,
vLight->scissorRect.y2 + 1 - vLight->scissorRect.y1 );
backEnd.currentScissor = vLight->scissorRect;
}
// clear stencil buffer to 0 (not drawable)
uint64 glStateMinusStencil = GL_GetCurrentStateMinusStencil();
GL_State( glStateMinusStencil | GLS_STENCIL_FUNC_ALWAYS | GLS_STENCIL_MAKE_REF( STENCIL_SHADOW_TEST_VALUE ) | GLS_STENCIL_MAKE_MASK( STENCIL_SHADOW_MASK_VALUE ) ); // make sure stencil mask passes for the clear
GL_Clear( false, false, true, 0, 0.0f, 0.0f, 0.0f, 0.0f ); // clear to 0 for stencil select
// set the depthbounds
GL_DepthBoundsTest( vLight->scissorRect.zmin, vLight->scissorRect.zmax );
GL_State( GLS_COLORMASK | GLS_ALPHAMASK | GLS_DEPTHMASK | GLS_DEPTHFUNC_LESS | GLS_STENCIL_FUNC_ALWAYS | GLS_STENCIL_MAKE_REF( STENCIL_SHADOW_TEST_VALUE ) | GLS_STENCIL_MAKE_MASK( STENCIL_SHADOW_MASK_VALUE ) );
GL_Cull( CT_TWO_SIDED );
renderProgManager.BindShader_Depth();
// set the matrix for deforming the 'zeroOneCubeModel' into the frustum to exactly cover the light volume
idRenderMatrix invProjectMVPMatrix;
idRenderMatrix::Multiply( backEnd.viewDef->worldSpace.mvp, vLight->inverseBaseLightProject, invProjectMVPMatrix );
RB_SetMVP( invProjectMVPMatrix );
// two-sided stencil test
glStencilOpSeparate( GL_FRONT, GL_KEEP, GL_REPLACE, GL_ZERO );
glStencilOpSeparate( GL_BACK, GL_KEEP, GL_ZERO, GL_REPLACE );
RB_DrawElementsWithCounters( &backEnd.zeroOneCubeSurface );
// reset stencil state
GL_Cull( CT_FRONT_SIDED );
renderProgManager.Unbind();
// unset the depthbounds
GL_DepthBoundsTest( 0.0f, 0.0f );
renderLog.CloseBlock();
}
/*
==============================================================================================
SHADOW MAPS RENDERING
==============================================================================================
*/
/*
same as D3DXMatrixOrthoOffCenterRH
http://msdn.microsoft.com/en-us/library/bb205348(VS.85).aspx
*/
static void MatrixOrthogonalProjectionRH( float m[16], float left, float right, float bottom, float top, float zNear, float zFar )
{
m[0] = 2 / ( right - left );
m[4] = 0;
m[8] = 0;
m[12] = ( left + right ) / ( left - right );
m[1] = 0;
m[5] = 2 / ( top - bottom );
m[9] = 0;
m[13] = ( top + bottom ) / ( bottom - top );
m[2] = 0;
m[6] = 0;
m[10] = 1 / ( zNear - zFar );
m[14] = zNear / ( zNear - zFar );
m[3] = 0;
m[7] = 0;
m[11] = 0;
m[15] = 1;
}
void MatrixCrop( float m[16], const idVec3 mins, const idVec3 maxs )
{
float scaleX, scaleY, scaleZ;
float offsetX, offsetY, offsetZ;
scaleX = 2.0f / ( maxs[0] - mins[0] );
scaleY = 2.0f / ( maxs[1] - mins[1] );
offsetX = -0.5f * ( maxs[0] + mins[0] ) * scaleX;
offsetY = -0.5f * ( maxs[1] + mins[1] ) * scaleY;
scaleZ = 1.0f / ( maxs[2] - mins[2] );
offsetZ = -mins[2] * scaleZ;
m[ 0] = scaleX;
m[ 4] = 0;
m[ 8] = 0;
m[12] = offsetX;
m[ 1] = 0;
m[ 5] = scaleY;
m[ 9] = 0;
m[13] = offsetY;
m[ 2] = 0;
m[ 6] = 0;
m[10] = scaleZ;
m[14] = offsetZ;
m[ 3] = 0;
m[ 7] = 0;
m[11] = 0;
m[15] = 1;
}
void MatrixLookAtRH( float m[16], const idVec3& eye, const idVec3& dir, const idVec3& up )
{
idVec3 dirN;
idVec3 upN;
idVec3 sideN;
sideN = dir.Cross( up );
sideN.Normalize();
upN = sideN.Cross( dir );
upN.Normalize();
dirN = dir;
dirN.Normalize();
m[ 0] = sideN[0];
m[ 4] = sideN[1];
m[ 8] = sideN[2];
m[12] = -( sideN * eye );
m[ 1] = upN[0];
m[ 5] = upN[1];
m[ 9] = upN[2];
m[13] = -( upN * eye );
m[ 2] = -dirN[0];
m[ 6] = -dirN[1];
m[10] = -dirN[2];
m[14] = ( dirN * eye );
m[ 3] = 0;
m[ 7] = 0;
m[11] = 0;
m[15] = 1;
}
/*
=====================
RB_ShadowMapPass
=====================
*/
static void RB_ShadowMapPass( const drawSurf_t* drawSurfs, const viewLight_t* vLight, int side )
{
if( r_skipShadows.GetBool() )
{
return;
}
if( drawSurfs == NULL )
{
return;
}
RENDERLOG_PRINTF( "---------- RB_ShadowMapPass( side = %i ) ----------\n", side );
renderProgManager.BindShader_Depth();
GL_SelectTexture( 0 );
globalImages->BindNull();
uint64 glState = 0;
// the actual stencil func will be set in the draw code, but we need to make sure it isn't
// disabled here, and that the value will get reset for the interactions without looking
// like a no-change-required
GL_State( glState | GLS_POLYGON_OFFSET );
switch( r_shadowMapOccluderFacing.GetInteger() )
{
case 0:
GL_Cull( CT_FRONT_SIDED );
GL_PolygonOffset( r_shadowMapPolygonFactor.GetFloat(), r_shadowMapPolygonOffset.GetFloat() );
break;
case 1:
GL_Cull( CT_BACK_SIDED );
GL_PolygonOffset( -r_shadowMapPolygonFactor.GetFloat(), -r_shadowMapPolygonOffset.GetFloat() );
break;
default:
GL_Cull( CT_TWO_SIDED );
GL_PolygonOffset( r_shadowMapPolygonFactor.GetFloat(), r_shadowMapPolygonOffset.GetFloat() );
break;
}
idRenderMatrix lightProjectionRenderMatrix;
idRenderMatrix lightViewRenderMatrix;
if( vLight->parallel && side >= 0 )
{
assert( side >= 0 && side < 6 );
// original light direction is from surface to light origin
idVec3 lightDir = -vLight->lightCenter;
if( lightDir.Normalize() == 0.0f )
{
lightDir[2] = -1.0f;
}
idMat3 rotation = lightDir.ToMat3();
//idAngles angles = lightDir.ToAngles();
//idMat3 rotation = angles.ToMat3();
const idVec3 viewDir = backEnd.viewDef->renderView.viewaxis[0];
const idVec3 viewPos = backEnd.viewDef->renderView.vieworg;
#if 1
idRenderMatrix::CreateViewMatrix( backEnd.viewDef->renderView.vieworg, rotation, lightViewRenderMatrix );
#else
float lightViewMatrix[16];
MatrixLookAtRH( lightViewMatrix, viewPos, lightDir, viewDir );
idRenderMatrix::Transpose( *( idRenderMatrix* )lightViewMatrix, lightViewRenderMatrix );
#endif
idBounds lightBounds;
lightBounds.Clear();
ALIGNTYPE16 frustumCorners_t corners;
idRenderMatrix::GetFrustumCorners( corners, vLight->inverseBaseLightProject, bounds_zeroOneCube );
idVec4 point, transf;
for( int j = 0; j < 8; j++ )
{
point[0] = corners.x[j];
point[1] = corners.y[j];
point[2] = corners.z[j];
point[3] = 1;
lightViewRenderMatrix.TransformPoint( point, transf );
transf[0] /= transf[3];
transf[1] /= transf[3];
transf[2] /= transf[3];
lightBounds.AddPoint( transf.ToVec3() );
}
float lightProjectionMatrix[16];
MatrixOrthogonalProjectionRH( lightProjectionMatrix, lightBounds[0][0], lightBounds[1][0], lightBounds[0][1], lightBounds[1][1], -lightBounds[1][2], -lightBounds[0][2] );
idRenderMatrix::Transpose( *( idRenderMatrix* )lightProjectionMatrix, lightProjectionRenderMatrix );
// 'frustumMVP' goes from global space -> camera local space -> camera projective space
// invert the MVP projection so we can deform zero-to-one cubes into the frustum pyramid shape and calculate global bounds
idRenderMatrix splitFrustumInverse;
if( !idRenderMatrix::Inverse( backEnd.viewDef->frustumMVPs[FRUSTUM_CASCADE1 + side], splitFrustumInverse ) )
{
idLib::Warning( "splitFrustumMVP invert failed" );
}
// splitFrustumCorners in global space
ALIGNTYPE16 frustumCorners_t splitFrustumCorners;
idRenderMatrix::GetFrustumCorners( splitFrustumCorners, splitFrustumInverse, bounds_unitCube );
#if 0
idBounds splitFrustumBounds;
splitFrustumBounds.Clear();
for( int j = 0; j < 8; j++ )
{
point[0] = splitFrustumCorners.x[j];
point[1] = splitFrustumCorners.y[j];
point[2] = splitFrustumCorners.z[j];
splitFrustumBounds.AddPoint( point.ToVec3() );
}
idVec3 center = splitFrustumBounds.GetCenter();
float radius = splitFrustumBounds.GetRadius( center );
//ALIGNTYPE16 frustumCorners_t splitFrustumCorners;
splitFrustumBounds[0] = idVec3( -radius, -radius, -radius );
splitFrustumBounds[1] = idVec3( radius, radius, radius );
splitFrustumBounds.TranslateSelf( viewPos );
idVec3 splitFrustumCorners2[8];
splitFrustumBounds.ToPoints( splitFrustumCorners2 );
for( int j = 0; j < 8; j++ )
{
splitFrustumCorners.x[j] = splitFrustumCorners2[j].x;
splitFrustumCorners.y[j] = splitFrustumCorners2[j].y;
splitFrustumCorners.z[j] = splitFrustumCorners2[j].z;
}
#endif
idRenderMatrix lightViewProjectionRenderMatrix;
idRenderMatrix::Multiply( lightProjectionRenderMatrix, lightViewRenderMatrix, lightViewProjectionRenderMatrix );
// find the bounding box of the current split in the light's clip space
idBounds cropBounds;
cropBounds.Clear();
for( int j = 0; j < 8; j++ )
{
point[0] = splitFrustumCorners.x[j];
point[1] = splitFrustumCorners.y[j];
point[2] = splitFrustumCorners.z[j];
point[3] = 1;
lightViewRenderMatrix.TransformPoint( point, transf );
transf[0] /= transf[3];
transf[1] /= transf[3];
transf[2] /= transf[3];
cropBounds.AddPoint( transf.ToVec3() );
}
// don't let the frustum AABB be bigger than the light AABB
if( cropBounds[0][0] < lightBounds[0][0] )
{
cropBounds[0][0] = lightBounds[0][0];
}
if( cropBounds[0][1] < lightBounds[0][1] )
{
cropBounds[0][1] = lightBounds[0][1];
}
if( cropBounds[1][0] > lightBounds[1][0] )
{
cropBounds[1][0] = lightBounds[1][0];
}
if( cropBounds[1][1] > lightBounds[1][1] )
{
cropBounds[1][1] = lightBounds[1][1];
}
cropBounds[0][2] = lightBounds[0][2];
cropBounds[1][2] = lightBounds[1][2];
//float cropMatrix[16];
//MatrixCrop(cropMatrix, cropBounds[0], cropBounds[1]);
//idRenderMatrix cropRenderMatrix;
//idRenderMatrix::Transpose( *( idRenderMatrix* )cropMatrix, cropRenderMatrix );
//idRenderMatrix tmp = lightProjectionRenderMatrix;
//idRenderMatrix::Multiply( cropRenderMatrix, tmp, lightProjectionRenderMatrix );
MatrixOrthogonalProjectionRH( lightProjectionMatrix, cropBounds[0][0], cropBounds[1][0], cropBounds[0][1], cropBounds[1][1], -cropBounds[1][2], -cropBounds[0][2] );
idRenderMatrix::Transpose( *( idRenderMatrix* )lightProjectionMatrix, lightProjectionRenderMatrix );
backEnd.shadowV[side] = lightViewRenderMatrix;
backEnd.shadowP[side] = lightProjectionRenderMatrix;
}
else if( vLight->pointLight && side >= 0 )
{
assert( side >= 0 && side < 6 );
// FIXME OPTIMIZE no memset
float viewMatrix[16];
idVec3 vec;
idVec3 origin = vLight->globalLightOrigin;
// side of a point light
memset( viewMatrix, 0, sizeof( viewMatrix ) );
switch( side )
{
case 0:
viewMatrix[0] = 1;
viewMatrix[9] = 1;
viewMatrix[6] = -1;
break;
case 1:
viewMatrix[0] = -1;
viewMatrix[9] = -1;
viewMatrix[6] = -1;
break;
case 2:
viewMatrix[4] = 1;
viewMatrix[1] = -1;
viewMatrix[10] = 1;
break;
case 3:
viewMatrix[4] = -1;
viewMatrix[1] = -1;
viewMatrix[10] = -1;
break;
case 4:
viewMatrix[8] = 1;
viewMatrix[1] = -1;
viewMatrix[6] = -1;
break;
case 5:
viewMatrix[8] = -1;
viewMatrix[1] = 1;
viewMatrix[6] = -1;
break;
}
viewMatrix[12] = -origin[0] * viewMatrix[0] + -origin[1] * viewMatrix[4] + -origin[2] * viewMatrix[8];
viewMatrix[13] = -origin[0] * viewMatrix[1] + -origin[1] * viewMatrix[5] + -origin[2] * viewMatrix[9];
viewMatrix[14] = -origin[0] * viewMatrix[2] + -origin[1] * viewMatrix[6] + -origin[2] * viewMatrix[10];
viewMatrix[3] = 0;
viewMatrix[7] = 0;
viewMatrix[11] = 0;
viewMatrix[15] = 1;
// from world space to light origin, looking down the X axis
float unflippedLightViewMatrix[16];
// from world space to OpenGL view space, looking down the negative Z axis
float lightViewMatrix[16];
static float s_flipMatrix[16] =
{
// convert from our coordinate system (looking down X)
// to OpenGL's coordinate system (looking down -Z)
0, 0, -1, 0,
-1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0, 1
};
memcpy( unflippedLightViewMatrix, viewMatrix, sizeof( unflippedLightViewMatrix ) );
R_MatrixMultiply( viewMatrix, s_flipMatrix, lightViewMatrix );
idRenderMatrix::Transpose( *( idRenderMatrix* )lightViewMatrix, lightViewRenderMatrix );
// set up 90 degree projection matrix
const float zNear = 4;
const float fov = r_shadowMapFrustumFOV.GetFloat();
float ymax = zNear * tan( fov * idMath::PI / 360.0f );
float ymin = -ymax;
float xmax = zNear * tan( fov * idMath::PI / 360.0f );
float xmin = -xmax;
const float width = xmax - xmin;
const float height = ymax - ymin;
// from OpenGL view space to OpenGL NDC ( -1 : 1 in XYZ )
float lightProjectionMatrix[16];
lightProjectionMatrix[0 * 4 + 0] = 2.0f * zNear / width;
lightProjectionMatrix[1 * 4 + 0] = 0.0f;
lightProjectionMatrix[2 * 4 + 0] = ( xmax + xmin ) / width; // normally 0
lightProjectionMatrix[3 * 4 + 0] = 0.0f;
lightProjectionMatrix[0 * 4 + 1] = 0.0f;
lightProjectionMatrix[1 * 4 + 1] = 2.0f * zNear / height;
lightProjectionMatrix[2 * 4 + 1] = ( ymax + ymin ) / height; // normally 0
lightProjectionMatrix[3 * 4 + 1] = 0.0f;
// this is the far-plane-at-infinity formulation, and
// crunches the Z range slightly so w=0 vertexes do not
// rasterize right at the wraparound point
lightProjectionMatrix[0 * 4 + 2] = 0.0f;
lightProjectionMatrix[1 * 4 + 2] = 0.0f;
lightProjectionMatrix[2 * 4 + 2] = -0.999f; // adjust value to prevent imprecision issues
lightProjectionMatrix[3 * 4 + 2] = -2.0f * zNear;
lightProjectionMatrix[0 * 4 + 3] = 0.0f;
lightProjectionMatrix[1 * 4 + 3] = 0.0f;
lightProjectionMatrix[2 * 4 + 3] = -1.0f;
lightProjectionMatrix[3 * 4 + 3] = 0.0f;
idRenderMatrix::Transpose( *( idRenderMatrix* )lightProjectionMatrix, lightProjectionRenderMatrix );
backEnd.shadowV[side] = lightViewRenderMatrix;
backEnd.shadowP[side] = lightProjectionRenderMatrix;
}
else
{
lightViewRenderMatrix.Identity();
lightProjectionRenderMatrix = vLight->baseLightProject;
backEnd.shadowV[0] = lightViewRenderMatrix;
backEnd.shadowP[0] = lightProjectionRenderMatrix;
}
globalFramebuffers.shadowFBO[vLight->shadowLOD]->Bind();
if( side < 0 )
{
globalFramebuffers.shadowFBO[vLight->shadowLOD]->AttachImageDepthLayer( globalImages->shadowImage[vLight->shadowLOD], 0 );
}
else
{
globalFramebuffers.shadowFBO[vLight->shadowLOD]->AttachImageDepthLayer( globalImages->shadowImage[vLight->shadowLOD], side );
}
globalFramebuffers.shadowFBO[vLight->shadowLOD]->Check();
GL_ViewportAndScissor( 0, 0, shadowMapResolutions[vLight->shadowLOD], shadowMapResolutions[vLight->shadowLOD] );
glClear( GL_DEPTH_BUFFER_BIT );
// process the chain of shadows with the current rendering state
backEnd.currentSpace = NULL;
for( const drawSurf_t* drawSurf = drawSurfs; drawSurf != NULL; drawSurf = drawSurf->nextOnLight )
{
#if 1
// make sure the shadow occluder geometry is done
if( drawSurf->shadowVolumeState != SHADOWVOLUME_DONE )
{
assert( drawSurf->shadowVolumeState == SHADOWVOLUME_UNFINISHED || drawSurf->shadowVolumeState == SHADOWVOLUME_DONE );
uint64 start = Sys_Microseconds();
while( drawSurf->shadowVolumeState == SHADOWVOLUME_UNFINISHED )
{
Sys_Yield();
}
uint64 end = Sys_Microseconds();
backEnd.pc.shadowMicroSec += end - start;
}
#endif
if( drawSurf->numIndexes == 0 )
{
continue; // a job may have created an empty shadow geometry
}
if( drawSurf->space != backEnd.currentSpace )
{
idRenderMatrix modelRenderMatrix;
idRenderMatrix::Transpose( *( idRenderMatrix* )drawSurf->space->modelMatrix, modelRenderMatrix );
idRenderMatrix modelToLightRenderMatrix;
idRenderMatrix::Multiply( lightViewRenderMatrix, modelRenderMatrix, modelToLightRenderMatrix );
idRenderMatrix clipMVP;
idRenderMatrix::Multiply( lightProjectionRenderMatrix, modelToLightRenderMatrix, clipMVP );
if( vLight->parallel )
{
idRenderMatrix MVP;
idRenderMatrix::Multiply( renderMatrix_clipSpaceToWindowSpace, clipMVP, MVP );
RB_SetMVP( clipMVP );
}
else if( side < 0 )
{
// from OpenGL view space to OpenGL NDC ( -1 : 1 in XYZ )
idRenderMatrix MVP;
idRenderMatrix::Multiply( renderMatrix_windowSpaceToClipSpace, clipMVP, MVP );
RB_SetMVP( MVP );
}
else
{
RB_SetMVP( clipMVP );
}
// set the local light position to allow the vertex program to project the shadow volume end cap to infinity
/*
idVec4 localLight( 0.0f );
R_GlobalPointToLocal( drawSurf->space->modelMatrix, vLight->globalLightOrigin, localLight.ToVec3() );
SetVertexParm( RENDERPARM_LOCALLIGHTORIGIN, localLight.ToFloatPtr() );
*/
backEnd.currentSpace = drawSurf->space;
}
bool didDraw = false;
const idMaterial* shader = drawSurf->material;
// get the expressions for conditionals / color / texcoords
const float* regs = drawSurf->shaderRegisters;
idVec4 color( 0, 0, 0, 1 );
uint64 surfGLState = 0;
// set polygon offset if necessary
if( shader && shader->TestMaterialFlag( MF_POLYGONOFFSET ) )
{
surfGLState |= GLS_POLYGON_OFFSET;
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
}
#if 1
if( shader && shader->Coverage() == MC_PERFORATED )
{
// perforated surfaces may have multiple alpha tested stages
for( int stage = 0; stage < shader->GetNumStages(); stage++ )
{
const shaderStage_t* pStage = shader->GetStage( stage );
if( !pStage->hasAlphaTest )
{
continue;
}
// check the stage enable condition
if( regs[ pStage->conditionRegister ] == 0 )
{
continue;
}
// if we at least tried to draw an alpha tested stage,
// we won't draw the opaque surface
didDraw = true;
// set the alpha modulate
color[3] = regs[ pStage->color.registers[3] ];
// skip the entire stage if alpha would be black
if( color[3] <= 0.0f )
{
continue;
}
uint64 stageGLState = surfGLState;
// set privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * pStage->privatePolygonOffset );
stageGLState |= GLS_POLYGON_OFFSET;
}
GL_Color( color );
#ifdef USE_CORE_PROFILE
GL_State( stageGLState );
idVec4 alphaTestValue( regs[ pStage->alphaTestRegister ] );
SetFragmentParm( RENDERPARM_ALPHA_TEST, alphaTestValue.ToFloatPtr() );
#else
GL_State( stageGLState | GLS_ALPHATEST_FUNC_GREATER | GLS_ALPHATEST_MAKE_REF( idMath::Ftob( 255.0f * regs[ pStage->alphaTestRegister ] ) ) );
#endif
if( drawSurf->jointCache )
{
renderProgManager.BindShader_TextureVertexColorSkinned();
}
else
{
renderProgManager.BindShader_TextureVertexColor();
}
RB_SetVertexColorParms( SVC_IGNORE );
// bind the texture
GL_SelectTexture( 0 );
pStage->texture.image->Bind();
// set texture matrix and texGens
RB_PrepareStageTexturing( pStage, drawSurf );
// must render with less-equal for Z-Cull to work properly
assert( ( GL_GetCurrentState() & GLS_DEPTHFUNC_BITS ) == GLS_DEPTHFUNC_LESS );
// draw it
RB_DrawElementsWithCounters( drawSurf );
// clean up
RB_FinishStageTexturing( pStage, drawSurf );
// unset privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
}
}
}
#endif
if( !didDraw )
{
if( drawSurf->jointCache )
{
renderProgManager.BindShader_DepthSkinned();
}
else
{
renderProgManager.BindShader_Depth();
}
RB_DrawElementsWithCounters( drawSurf );
}
}
// cleanup the shadow specific rendering state
Framebuffer::BindNull();
renderProgManager.Unbind();
GL_State( GLS_DEFAULT );
GL_Cull( CT_FRONT_SIDED );
#ifdef USE_CORE_PROFILE
SetFragmentParm( RENDERPARM_ALPHA_TEST, vec4_zero.ToFloatPtr() );
#endif
}
/*
==============================================================================================
DRAW INTERACTIONS
==============================================================================================
*/
/*
==================
RB_DrawInteractions
==================
*/
static void RB_DrawInteractions( const viewDef_t* viewDef )
{
if( r_skipInteractions.GetBool() )
{
return;
}
renderLog.OpenMainBlock( MRB_DRAW_INTERACTIONS );
renderLog.OpenBlock( "RB_DrawInteractions" );
GL_SelectTexture( 0 );
const bool useLightDepthBounds = r_useLightDepthBounds.GetBool() && !r_useShadowMapping.GetBool();
//
// for each light, perform shadowing and adding
//
for( const viewLight_t* vLight = backEnd.viewDef->viewLights; vLight != NULL; vLight = vLight->next )
{
// do fogging later
if( vLight->lightShader->IsFogLight() )
{
continue;
}
if( vLight->lightShader->IsBlendLight() )
{
continue;
}
if( vLight->localInteractions == NULL && vLight->globalInteractions == NULL && vLight->translucentInteractions == NULL )
{
continue;
}
const idMaterial* lightShader = vLight->lightShader;
renderLog.OpenBlock( lightShader->GetName() );
// set the depth bounds for the whole light
if( useLightDepthBounds )
{
GL_DepthBoundsTest( vLight->scissorRect.zmin, vLight->scissorRect.zmax );
}
// RB: shadow mapping
if( r_useShadowMapping.GetBool() )
{
int side, sideStop;
if( vLight->parallel )
{
side = 0;
sideStop = r_shadowMapSplits.GetInteger() + 1;
}
else if( vLight->pointLight )
{
if( r_shadowMapSingleSide.GetInteger() != -1 )
{
side = r_shadowMapSingleSide.GetInteger();
sideStop = side + 1;
}
else
{
side = 0;
sideStop = 6;
}
}
else
{
side = -1;
sideStop = 0;
}
for( ; side < sideStop ; side++ )
{
RB_ShadowMapPass( vLight->globalShadows, vLight, side );
}
// go back from light view to default camera view
RB_ResetViewportAndScissorToDefaultCamera( viewDef );
if( vLight->localInteractions != NULL )
{
renderLog.OpenBlock( "Local Light Interactions" );
RB_RenderInteractions( vLight->localInteractions, vLight, GLS_DEPTHFUNC_EQUAL, false, useLightDepthBounds );
renderLog.CloseBlock();
}
if( vLight->globalInteractions != NULL )
{
renderLog.OpenBlock( "Global Light Interactions" );
RB_RenderInteractions( vLight->globalInteractions, vLight, GLS_DEPTHFUNC_EQUAL, false, useLightDepthBounds );
renderLog.CloseBlock();
}
}
else
{
// only need to clear the stencil buffer and perform stencil testing if there are shadows
const bool performStencilTest = ( vLight->globalShadows != NULL || vLight->localShadows != NULL ) && !r_useShadowMapping.GetBool();
// mirror flips the sense of the stencil select, and I don't want to risk accidentally breaking it
// in the normal case, so simply disable the stencil select in the mirror case
const bool useLightStencilSelect = ( r_useLightStencilSelect.GetBool() && backEnd.viewDef->isMirror == false );
if( performStencilTest )
{
if( useLightStencilSelect )
{
// write a stencil mask for the visible light bounds to hi-stencil
RB_StencilSelectLight( vLight );
}
else
{
// always clear whole S-Cull tiles
idScreenRect rect;
rect.x1 = ( vLight->scissorRect.x1 + 0 ) & ~15;
rect.y1 = ( vLight->scissorRect.y1 + 0 ) & ~15;
rect.x2 = ( vLight->scissorRect.x2 + 15 ) & ~15;
rect.y2 = ( vLight->scissorRect.y2 + 15 ) & ~15;
if( !backEnd.currentScissor.Equals( rect ) && r_useScissor.GetBool() )
{
GL_Scissor( backEnd.viewDef->viewport.x1 + rect.x1,
backEnd.viewDef->viewport.y1 + rect.y1,
rect.x2 + 1 - rect.x1,
rect.y2 + 1 - rect.y1 );
backEnd.currentScissor = rect;
}
GL_State( GLS_DEFAULT ); // make sure stencil mask passes for the clear
GL_Clear( false, false, true, STENCIL_SHADOW_TEST_VALUE, 0.0f, 0.0f, 0.0f, 0.0f );
}
}
if( vLight->globalShadows != NULL )
{
renderLog.OpenBlock( "Global Light Shadows" );
RB_StencilShadowPass( vLight->globalShadows, vLight );
renderLog.CloseBlock();
}
if( vLight->localInteractions != NULL )
{
renderLog.OpenBlock( "Local Light Interactions" );
RB_RenderInteractions( vLight->localInteractions, vLight, GLS_DEPTHFUNC_EQUAL, performStencilTest, useLightDepthBounds );
renderLog.CloseBlock();
}
if( vLight->localShadows != NULL )
{
renderLog.OpenBlock( "Local Light Shadows" );
RB_StencilShadowPass( vLight->localShadows, vLight );
renderLog.CloseBlock();
}
if( vLight->globalInteractions != NULL )
{
renderLog.OpenBlock( "Global Light Interactions" );
RB_RenderInteractions( vLight->globalInteractions, vLight, GLS_DEPTHFUNC_EQUAL, performStencilTest, useLightDepthBounds );
renderLog.CloseBlock();
}
}
// RB end
if( vLight->translucentInteractions != NULL && !r_skipTranslucent.GetBool() )
{
renderLog.OpenBlock( "Translucent Interactions" );
// Disable the depth bounds test because translucent surfaces don't work with
// the depth bounds tests since they did not write depth during the depth pass.
if( useLightDepthBounds )
{
GL_DepthBoundsTest( 0.0f, 0.0f );
}
// The depth buffer wasn't filled in for translucent surfaces, so they
// can never be constrained to perforated surfaces with the depthfunc equal.
// Translucent surfaces do not receive shadows. This is a case where a
// shadow buffer solution would work but stencil shadows do not because
// stencil shadows only affect surfaces that contribute to the view depth
// buffer and translucent surfaces do not contribute to the view depth buffer.
RB_RenderInteractions( vLight->translucentInteractions, vLight, GLS_DEPTHFUNC_LESS, false, false );
renderLog.CloseBlock();
}
renderLog.CloseBlock();
}
// disable stencil shadow test
GL_State( GLS_DEFAULT );
// unbind texture units
for( int i = 0; i < 5; i++ )
{
GL_SelectTexture( i );
globalImages->BindNull();
}
GL_SelectTexture( 0 );
// reset depth bounds
if( useLightDepthBounds )
{
GL_DepthBoundsTest( 0.0f, 0.0f );
}
renderLog.CloseBlock();
renderLog.CloseMainBlock();
}
/*
=============================================================================================
NON-INTERACTION SHADER PASSES
=============================================================================================
*/
/*
=====================
RB_DrawShaderPasses
Draw non-light dependent passes
If we are rendering Guis, the drawSurf_t::sort value is a depth offset that can
be multiplied by guiEye for polarity and screenSeparation for scale.
=====================
*/
static int RB_DrawShaderPasses( const drawSurf_t* const* const drawSurfs, const int numDrawSurfs,
const float guiStereoScreenOffset, const int stereoEye )
{
// only obey skipAmbient if we are rendering a view
if( backEnd.viewDef->viewEntitys && r_skipAmbient.GetBool() )
{
return numDrawSurfs;
}
renderLog.OpenBlock( "RB_DrawShaderPasses" );
GL_SelectTexture( 1 );
globalImages->BindNull();
GL_SelectTexture( 0 );
backEnd.currentSpace = ( const viewEntity_t* )1; // using NULL makes /analyze think surf->space needs to be checked...
float currentGuiStereoOffset = 0.0f;
int i = 0;
for( ; i < numDrawSurfs; i++ )
{
const drawSurf_t* surf = drawSurfs[i];
const idMaterial* shader = surf->material;
if( !shader->HasAmbient() )
{
continue;
}
if( shader->IsPortalSky() )
{
continue;
}
// some deforms may disable themselves by setting numIndexes = 0
if( surf->numIndexes == 0 )
{
continue;
}
if( shader->SuppressInSubview() )
{
continue;
}
if( backEnd.viewDef->isXraySubview && surf->space->entityDef )
{
if( surf->space->entityDef->parms.xrayIndex != 2 )
{
continue;
}
}
// we need to draw the post process shaders after we have drawn the fog lights
if( shader->GetSort() >= SS_POST_PROCESS && !backEnd.currentRenderCopied )
{
break;
}
// if we are rendering a 3D view and the surface's eye index doesn't match
// the current view's eye index then we skip the surface
// if the stereoEye value of a surface is 0 then we need to draw it for both eyes.
const int shaderStereoEye = shader->GetStereoEye();
const bool isEyeValid = stereoRender_swapEyes.GetBool() ? ( shaderStereoEye == stereoEye ) : ( shaderStereoEye != stereoEye );
if( ( stereoEye != 0 ) && ( shaderStereoEye != 0 ) && ( isEyeValid ) )
{
continue;
}
renderLog.OpenBlock( shader->GetName() );
// determine the stereoDepth offset
// guiStereoScreenOffset will always be zero for 3D views, so the !=
// check will never force an update due to the current sort value.
const float thisGuiStereoOffset = guiStereoScreenOffset * surf->sort;
// change the matrix and other space related vars if needed
if( surf->space != backEnd.currentSpace || thisGuiStereoOffset != currentGuiStereoOffset )
{
backEnd.currentSpace = surf->space;
currentGuiStereoOffset = thisGuiStereoOffset;
const viewEntity_t* space = backEnd.currentSpace;
if( guiStereoScreenOffset != 0.0f )
{
RB_SetMVPWithStereoOffset( space->mvp, currentGuiStereoOffset );
}
else
{
RB_SetMVP( space->mvp );
}
// set eye position in local space
idVec4 localViewOrigin( 1.0f );
R_GlobalPointToLocal( space->modelMatrix, backEnd.viewDef->renderView.vieworg, localViewOrigin.ToVec3() );
SetVertexParm( RENDERPARM_LOCALVIEWORIGIN, localViewOrigin.ToFloatPtr() );
// set model Matrix
float modelMatrixTranspose[16];
R_MatrixTranspose( space->modelMatrix, modelMatrixTranspose );
SetVertexParms( RENDERPARM_MODELMATRIX_X, modelMatrixTranspose, 4 );
// Set ModelView Matrix
float modelViewMatrixTranspose[16];
R_MatrixTranspose( space->modelViewMatrix, modelViewMatrixTranspose );
SetVertexParms( RENDERPARM_MODELVIEWMATRIX_X, modelViewMatrixTranspose, 4 );
}
// change the scissor if needed
if( !backEnd.currentScissor.Equals( surf->scissorRect ) && r_useScissor.GetBool() )
{
GL_Scissor( backEnd.viewDef->viewport.x1 + surf->scissorRect.x1,
backEnd.viewDef->viewport.y1 + surf->scissorRect.y1,
surf->scissorRect.x2 + 1 - surf->scissorRect.x1,
surf->scissorRect.y2 + 1 - surf->scissorRect.y1 );
backEnd.currentScissor = surf->scissorRect;
}
// get the expressions for conditionals / color / texcoords
const float* regs = surf->shaderRegisters;
// set face culling appropriately
if( surf->space->isGuiSurface )
{
GL_Cull( CT_TWO_SIDED );
}
else
{
GL_Cull( shader->GetCullType() );
}
uint64 surfGLState = surf->extraGLState;
// set polygon offset if necessary
if( shader->TestMaterialFlag( MF_POLYGONOFFSET ) )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
surfGLState = GLS_POLYGON_OFFSET;
}
for( int stage = 0; stage < shader->GetNumStages(); stage++ )
{
const shaderStage_t* pStage = shader->GetStage( stage );
// check the enable condition
if( regs[ pStage->conditionRegister ] == 0 )
{
continue;
}
// skip the stages involved in lighting
if( pStage->lighting != SL_AMBIENT )
{
continue;
}
uint64 stageGLState = surfGLState;
if( ( surfGLState & GLS_OVERRIDE ) == 0 )
{
stageGLState |= pStage->drawStateBits;
}
// skip if the stage is ( GL_ZERO, GL_ONE ), which is used for some alpha masks
if( ( stageGLState & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) == ( GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE ) )
{
continue;
}
// see if we are a new-style stage
newShaderStage_t* newStage = pStage->newStage;
if( newStage != NULL )
{
//--------------------------
//
// new style stages
//
//--------------------------
if( r_skipNewAmbient.GetBool() )
{
continue;
}
renderLog.OpenBlock( "New Shader Stage" );
GL_State( stageGLState );
// RB: CRITICAL BUGFIX: changed newStage->glslProgram to vertexProgram and fragmentProgram
// otherwise it will result in an out of bounds crash in RB_DrawElementsWithCounters
renderProgManager.BindShader( newStage->glslProgram, newStage->vertexProgram, newStage->fragmentProgram, false );
// RB end
for( int j = 0; j < newStage->numVertexParms; j++ )
{
float parm[4];
parm[0] = regs[ newStage->vertexParms[j][0] ];
parm[1] = regs[ newStage->vertexParms[j][1] ];
parm[2] = regs[ newStage->vertexParms[j][2] ];
parm[3] = regs[ newStage->vertexParms[j][3] ];
SetVertexParm( ( renderParm_t )( RENDERPARM_USER + j ), parm );
}
// set rpEnableSkinning if the shader has optional support for skinning
if( surf->jointCache && renderProgManager.ShaderHasOptionalSkinning() )
{
const idVec4 skinningParm( 1.0f );
SetVertexParm( RENDERPARM_ENABLE_SKINNING, skinningParm.ToFloatPtr() );
}
// bind texture units
for( int j = 0; j < newStage->numFragmentProgramImages; j++ )
{
idImage* image = newStage->fragmentProgramImages[j];
if( image != NULL )
{
GL_SelectTexture( j );
image->Bind();
}
}
// draw it
RB_DrawElementsWithCounters( surf );
// unbind texture units
for( int j = 0; j < newStage->numFragmentProgramImages; j++ )
{
idImage* image = newStage->fragmentProgramImages[j];
if( image != NULL )
{
GL_SelectTexture( j );
globalImages->BindNull();
}
}
// clear rpEnableSkinning if it was set
if( surf->jointCache && renderProgManager.ShaderHasOptionalSkinning() )
{
const idVec4 skinningParm( 0.0f );
SetVertexParm( RENDERPARM_ENABLE_SKINNING, skinningParm.ToFloatPtr() );
}
GL_SelectTexture( 0 );
renderProgManager.Unbind();
renderLog.CloseBlock();
continue;
}
//--------------------------
//
// old style stages
//
//--------------------------
// set the color
idVec4 color;
color[0] = regs[ pStage->color.registers[0] ];
color[1] = regs[ pStage->color.registers[1] ];
color[2] = regs[ pStage->color.registers[2] ];
color[3] = regs[ pStage->color.registers[3] ];
// skip the entire stage if an add would be black
if( ( stageGLState & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) == ( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE )
&& color[0] <= 0 && color[1] <= 0 && color[2] <= 0 )
{
continue;
}
// skip the entire stage if a blend would be completely transparent
if( ( stageGLState & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) == ( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA )
&& color[3] <= 0 )
{
continue;
}
stageVertexColor_t svc = pStage->vertexColor;
renderLog.OpenBlock( "Old Shader Stage" );
GL_Color( color );
if( surf->space->isGuiSurface )
{
// Force gui surfaces to always be SVC_MODULATE
svc = SVC_MODULATE;
// use special shaders for bink cinematics
if( pStage->texture.cinematic )
{
if( ( stageGLState & GLS_OVERRIDE ) != 0 )
{
// This is a hack... Only SWF Guis set GLS_OVERRIDE
// Old style guis do not, and we don't want them to use the new GUI renederProg
renderProgManager.BindShader_BinkGUI();
}
else
{
renderProgManager.BindShader_Bink();
}
}
else
{
if( ( stageGLState & GLS_OVERRIDE ) != 0 )
{
// This is a hack... Only SWF Guis set GLS_OVERRIDE
// Old style guis do not, and we don't want them to use the new GUI renderProg
renderProgManager.BindShader_GUI();
}
else
{
if( surf->jointCache )
{
renderProgManager.BindShader_TextureVertexColorSkinned();
}
else
{
renderProgManager.BindShader_TextureVertexColor();
}
}
}
}
else if( ( pStage->texture.texgen == TG_SCREEN ) || ( pStage->texture.texgen == TG_SCREEN2 ) )
{
renderProgManager.BindShader_TextureTexGenVertexColor();
}
else if( pStage->texture.cinematic )
{
renderProgManager.BindShader_Bink();
}
else
{
if( surf->jointCache )
{
renderProgManager.BindShader_TextureVertexColorSkinned();
}
else
{
renderProgManager.BindShader_TextureVertexColor();
}
}
RB_SetVertexColorParms( svc );
// bind the texture
RB_BindVariableStageImage( &pStage->texture, regs );
// set privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * pStage->privatePolygonOffset );
stageGLState |= GLS_POLYGON_OFFSET;
}
// set the state
GL_State( stageGLState );
RB_PrepareStageTexturing( pStage, surf );
// draw it
RB_DrawElementsWithCounters( surf );
RB_FinishStageTexturing( pStage, surf );
// unset privatePolygonOffset if necessary
if( pStage->privatePolygonOffset )
{
GL_PolygonOffset( r_offsetFactor.GetFloat(), r_offsetUnits.GetFloat() * shader->GetPolygonOffset() );
}
renderLog.CloseBlock();
}
renderLog.CloseBlock();
}
GL_Cull( CT_FRONT_SIDED );
GL_Color( 1.0f, 1.0f, 1.0f );
renderLog.CloseBlock();
return i;
}
/*
=============================================================================================
BLEND LIGHT PROJECTION
=============================================================================================
*/
/*
=====================
RB_T_BlendLight
=====================
*/
static void RB_T_BlendLight( const drawSurf_t* drawSurfs, const viewLight_t* vLight )
{
backEnd.currentSpace = NULL;
for( const drawSurf_t* drawSurf = drawSurfs; drawSurf != NULL; drawSurf = drawSurf->nextOnLight )
{
if( drawSurf->scissorRect.IsEmpty() )
{
continue; // !@# FIXME: find out why this is sometimes being hit!
// temporarily jump over the scissor and draw so the gl error callback doesn't get hit
}
if( !backEnd.currentScissor.Equals( drawSurf->scissorRect ) && r_useScissor.GetBool() )
{
// change the scissor
GL_Scissor( backEnd.viewDef->viewport.x1 + drawSurf->scissorRect.x1,
backEnd.viewDef->viewport.y1 + drawSurf->scissorRect.y1,
drawSurf->scissorRect.x2 + 1 - drawSurf->scissorRect.x1,
drawSurf->scissorRect.y2 + 1 - drawSurf->scissorRect.y1 );
backEnd.currentScissor = drawSurf->scissorRect;
}
if( drawSurf->space != backEnd.currentSpace )
{
// change the matrix
RB_SetMVP( drawSurf->space->mvp );
// change the light projection matrix
idPlane lightProjectInCurrentSpace[4];
for( int i = 0; i < 4; i++ )
{
R_GlobalPlaneToLocal( drawSurf->space->modelMatrix, vLight->lightProject[i], lightProjectInCurrentSpace[i] );
}
SetVertexParm( RENDERPARM_TEXGEN_0_S, lightProjectInCurrentSpace[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_0_T, lightProjectInCurrentSpace[1].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_0_Q, lightProjectInCurrentSpace[2].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_1_S, lightProjectInCurrentSpace[3].ToFloatPtr() ); // falloff
backEnd.currentSpace = drawSurf->space;
}
RB_DrawElementsWithCounters( drawSurf );
}
}
/*
=====================
RB_BlendLight
Dual texture together the falloff and projection texture with a blend
mode to the framebuffer, instead of interacting with the surface texture
=====================
*/
static void RB_BlendLight( const drawSurf_t* drawSurfs, const drawSurf_t* drawSurfs2, const viewLight_t* vLight )
{
if( drawSurfs == NULL )
{
return;
}
if( r_skipBlendLights.GetBool() )
{
return;
}
renderLog.OpenBlock( vLight->lightShader->GetName() );
const idMaterial* lightShader = vLight->lightShader;
const float* regs = vLight->shaderRegisters;
// texture 1 will get the falloff texture
GL_SelectTexture( 1 );
vLight->falloffImage->Bind();
// texture 0 will get the projected texture
GL_SelectTexture( 0 );
renderProgManager.BindShader_BlendLight();
for( int i = 0; i < lightShader->GetNumStages(); i++ )
{
const shaderStage_t* stage = lightShader->GetStage( i );
if( !regs[ stage->conditionRegister ] )
{
continue;
}
GL_State( GLS_DEPTHMASK | stage->drawStateBits | GLS_DEPTHFUNC_EQUAL );
GL_SelectTexture( 0 );
stage->texture.image->Bind();
if( stage->texture.hasMatrix )
{
RB_LoadShaderTextureMatrix( regs, &stage->texture );
}
// get the modulate values from the light, including alpha, unlike normal lights
idVec4 lightColor;
lightColor[0] = regs[ stage->color.registers[0] ];
lightColor[1] = regs[ stage->color.registers[1] ];
lightColor[2] = regs[ stage->color.registers[2] ];
lightColor[3] = regs[ stage->color.registers[3] ];
GL_Color( lightColor );
RB_T_BlendLight( drawSurfs, vLight );
RB_T_BlendLight( drawSurfs2, vLight );
}
GL_SelectTexture( 1 );
globalImages->BindNull();
GL_SelectTexture( 0 );
renderProgManager.Unbind();
renderLog.CloseBlock();
}
/*
=========================================================================================================
FOG LIGHTS
=========================================================================================================
*/
/*
=====================
RB_T_BasicFog
=====================
*/
static void RB_T_BasicFog( const drawSurf_t* drawSurfs, const idPlane fogPlanes[4], const idRenderMatrix* inverseBaseLightProject )
{
backEnd.currentSpace = NULL;
for( const drawSurf_t* drawSurf = drawSurfs; drawSurf != NULL; drawSurf = drawSurf->nextOnLight )
{
if( drawSurf->scissorRect.IsEmpty() )
{
continue; // !@# FIXME: find out why this is sometimes being hit!
// temporarily jump over the scissor and draw so the gl error callback doesn't get hit
}
if( !backEnd.currentScissor.Equals( drawSurf->scissorRect ) && r_useScissor.GetBool() )
{
// change the scissor
GL_Scissor( backEnd.viewDef->viewport.x1 + drawSurf->scissorRect.x1,
backEnd.viewDef->viewport.y1 + drawSurf->scissorRect.y1,
drawSurf->scissorRect.x2 + 1 - drawSurf->scissorRect.x1,
drawSurf->scissorRect.y2 + 1 - drawSurf->scissorRect.y1 );
backEnd.currentScissor = drawSurf->scissorRect;
}
if( drawSurf->space != backEnd.currentSpace )
{
idPlane localFogPlanes[4];
if( inverseBaseLightProject == NULL )
{
RB_SetMVP( drawSurf->space->mvp );
for( int i = 0; i < 4; i++ )
{
R_GlobalPlaneToLocal( drawSurf->space->modelMatrix, fogPlanes[i], localFogPlanes[i] );
}
}
else
{
idRenderMatrix invProjectMVPMatrix;
idRenderMatrix::Multiply( backEnd.viewDef->worldSpace.mvp, *inverseBaseLightProject, invProjectMVPMatrix );
RB_SetMVP( invProjectMVPMatrix );
for( int i = 0; i < 4; i++ )
{
inverseBaseLightProject->InverseTransformPlane( fogPlanes[i], localFogPlanes[i], false );
}
}
SetVertexParm( RENDERPARM_TEXGEN_0_S, localFogPlanes[0].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_0_T, localFogPlanes[1].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_1_T, localFogPlanes[2].ToFloatPtr() );
SetVertexParm( RENDERPARM_TEXGEN_1_S, localFogPlanes[3].ToFloatPtr() );
backEnd.currentSpace = ( inverseBaseLightProject == NULL ) ? drawSurf->space : NULL;
}
if( drawSurf->jointCache )
{
renderProgManager.BindShader_FogSkinned();
}
else
{
renderProgManager.BindShader_Fog();
}
RB_DrawElementsWithCounters( drawSurf );
}
}
/*
==================
RB_FogPass
==================
*/
static void RB_FogPass( const drawSurf_t* drawSurfs, const drawSurf_t* drawSurfs2, const viewLight_t* vLight )
{
renderLog.OpenBlock( vLight->lightShader->GetName() );
// find the current color and density of the fog
const idMaterial* lightShader = vLight->lightShader;
const float* regs = vLight->shaderRegisters;
// assume fog shaders have only a single stage
const shaderStage_t* stage = lightShader->GetStage( 0 );
idVec4 lightColor;
lightColor[0] = regs[ stage->color.registers[0] ];
lightColor[1] = regs[ stage->color.registers[1] ];
lightColor[2] = regs[ stage->color.registers[2] ];
lightColor[3] = regs[ stage->color.registers[3] ];
GL_Color( lightColor );
// calculate the falloff planes
float a;
// if they left the default value on, set a fog distance of 500
if( lightColor[3] <= 1.0f )
{
a = -0.5f / DEFAULT_FOG_DISTANCE;
}
else
{
// otherwise, distance = alpha color
a = -0.5f / lightColor[3];
}
// texture 0 is the falloff image
GL_SelectTexture( 0 );
globalImages->fogImage->Bind();
// texture 1 is the entering plane fade correction
GL_SelectTexture( 1 );
globalImages->fogEnterImage->Bind();
// S is based on the view origin
const float s = vLight->fogPlane.Distance( backEnd.viewDef->renderView.vieworg );
const float FOG_SCALE = 0.001f;
idPlane fogPlanes[4];
// S-0
fogPlanes[0][0] = a * backEnd.viewDef->worldSpace.modelViewMatrix[0 * 4 + 2];
fogPlanes[0][1] = a * backEnd.viewDef->worldSpace.modelViewMatrix[1 * 4 + 2];
fogPlanes[0][2] = a * backEnd.viewDef->worldSpace.modelViewMatrix[2 * 4 + 2];
fogPlanes[0][3] = a * backEnd.viewDef->worldSpace.modelViewMatrix[3 * 4 + 2] + 0.5f;
// T-0
fogPlanes[1][0] = 0.0f;//a * backEnd.viewDef->worldSpace.modelViewMatrix[0*4+0];
fogPlanes[1][1] = 0.0f;//a * backEnd.viewDef->worldSpace.modelViewMatrix[1*4+0];
fogPlanes[1][2] = 0.0f;//a * backEnd.viewDef->worldSpace.modelViewMatrix[2*4+0];
fogPlanes[1][3] = 0.5f;//a * backEnd.viewDef->worldSpace.modelViewMatrix[3*4+0] + 0.5f;
// T-1 will get a texgen for the fade plane, which is always the "top" plane on unrotated lights
fogPlanes[2][0] = FOG_SCALE * vLight->fogPlane[0];
fogPlanes[2][1] = FOG_SCALE * vLight->fogPlane[1];
fogPlanes[2][2] = FOG_SCALE * vLight->fogPlane[2];
fogPlanes[2][3] = FOG_SCALE * vLight->fogPlane[3] + FOG_ENTER;
// S-1
fogPlanes[3][0] = 0.0f;
fogPlanes[3][1] = 0.0f;
fogPlanes[3][2] = 0.0f;
fogPlanes[3][3] = FOG_SCALE * s + FOG_ENTER;
// draw it
GL_State( GLS_DEPTHMASK | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL );
RB_T_BasicFog( drawSurfs, fogPlanes, NULL );
RB_T_BasicFog( drawSurfs2, fogPlanes, NULL );
// the light frustum bounding planes aren't in the depth buffer, so use depthfunc_less instead
// of depthfunc_equal
GL_State( GLS_DEPTHMASK | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_LESS );
GL_Cull( CT_BACK_SIDED );
backEnd.zeroOneCubeSurface.space = &backEnd.viewDef->worldSpace;
backEnd.zeroOneCubeSurface.scissorRect = backEnd.viewDef->scissor;
RB_T_BasicFog( &backEnd.zeroOneCubeSurface, fogPlanes, &vLight->inverseBaseLightProject );
GL_Cull( CT_FRONT_SIDED );
GL_SelectTexture( 1 );
globalImages->BindNull();
GL_SelectTexture( 0 );
renderProgManager.Unbind();
renderLog.CloseBlock();
}
/*
==================
RB_FogAllLights
==================
*/
static void RB_FogAllLights()
{
if( r_skipFogLights.GetBool() || r_showOverDraw.GetInteger() != 0
|| backEnd.viewDef->isXraySubview /* don't fog in xray mode*/ )
{
return;
}
renderLog.OpenMainBlock( MRB_FOG_ALL_LIGHTS );
renderLog.OpenBlock( "RB_FogAllLights" );
// force fog plane to recalculate
backEnd.currentSpace = NULL;
for( viewLight_t* vLight = backEnd.viewDef->viewLights; vLight != NULL; vLight = vLight->next )
{
if( vLight->lightShader->IsFogLight() )
{
RB_FogPass( vLight->globalInteractions, vLight->localInteractions, vLight );
}
else if( vLight->lightShader->IsBlendLight() )
{
RB_BlendLight( vLight->globalInteractions, vLight->localInteractions, vLight );
}
}
renderLog.CloseBlock();
renderLog.CloseMainBlock();
}
/*
=========================================================================================================
BACKEND COMMANDS
=========================================================================================================
*/
/*
==================
RB_DrawViewInternal
==================
*/
void RB_DrawViewInternal( const viewDef_t* viewDef, const int stereoEye )
{
renderLog.OpenBlock( "RB_DrawViewInternal" );
//-------------------------------------------------
// guis can wind up referencing purged images that need to be loaded.
// this used to be in the gui emit code, but now that it can be running
// in a separate thread, it must not try to load images, so do it here.
//-------------------------------------------------
drawSurf_t** drawSurfs = ( drawSurf_t** )&viewDef->drawSurfs[0];
const int numDrawSurfs = viewDef->numDrawSurfs;
for( int i = 0; i < numDrawSurfs; i++ )
{
const drawSurf_t* ds = viewDef->drawSurfs[ i ];
if( ds->material != NULL )
{
const_cast<idMaterial*>( ds->material )->EnsureNotPurged();
}
}
//-------------------------------------------------
// RB_BeginDrawingView
//
// Any mirrored or portaled views have already been drawn, so prepare
// to actually render the visible surfaces for this view
//
// clear the z buffer, set the projection matrix, etc
//-------------------------------------------------
RB_ResetViewportAndScissorToDefaultCamera( viewDef );
backEnd.glState.faceCulling = -1; // force face culling to set next time
// ensures that depth writes are enabled for the depth clear
GL_State( GLS_DEFAULT );
// Clear the depth buffer and clear the stencil to 128 for stencil shadows as well as gui masking
GL_Clear( false, true, true, STENCIL_SHADOW_TEST_VALUE, 0.0f, 0.0f, 0.0f, 0.0f );
// normal face culling
GL_Cull( CT_FRONT_SIDED );
#if defined(USE_CORE_PROFILE) && !defined(USE_GLES2) && !defined(USE_GLES3)
// bind one global Vertex Array Object (VAO)
glBindVertexArray( glConfig.global_vao );
#endif
//------------------------------------
// sets variables that can be used by all programs
//------------------------------------
{
//
// set eye position in global space
//
float parm[4];
parm[0] = backEnd.viewDef->renderView.vieworg[0];
parm[1] = backEnd.viewDef->renderView.vieworg[1];
parm[2] = backEnd.viewDef->renderView.vieworg[2];
parm[3] = 1.0f;
SetVertexParm( RENDERPARM_GLOBALEYEPOS, parm ); // rpGlobalEyePos
// sets overbright to make world brighter
// This value is baked into the specularScale and diffuseScale values so
// the interaction programs don't need to perform the extra multiply,
// but any other renderprogs that want to obey the brightness value
// can reference this.
float overbright = r_lightScale.GetFloat() * 0.5f;
parm[0] = overbright;
parm[1] = overbright;
parm[2] = overbright;
parm[3] = overbright;
SetFragmentParm( RENDERPARM_OVERBRIGHT, parm );
// Set Projection Matrix
float projMatrixTranspose[16];
R_MatrixTranspose( backEnd.viewDef->projectionMatrix, projMatrixTranspose );
SetVertexParms( RENDERPARM_PROJMATRIX_X, projMatrixTranspose, 4 );
}
//-------------------------------------------------
// fill the depth buffer and clear color buffer to black except on subviews
//-------------------------------------------------
RB_FillDepthBufferFast( drawSurfs, numDrawSurfs );
//-------------------------------------------------
// main light renderer
//-------------------------------------------------
RB_DrawInteractions( viewDef );
//-------------------------------------------------
// now draw any non-light dependent shading passes
//-------------------------------------------------
int processed = 0;
if( !r_skipShaderPasses.GetBool() )
{
renderLog.OpenMainBlock( MRB_DRAW_SHADER_PASSES );
float guiScreenOffset;
if( viewDef->viewEntitys != NULL )
{
// guiScreenOffset will be 0 in non-gui views
guiScreenOffset = 0.0f;
}
else
{
guiScreenOffset = stereoEye * viewDef->renderView.stereoScreenSeparation;
}
processed = RB_DrawShaderPasses( drawSurfs, numDrawSurfs, guiScreenOffset, stereoEye );
renderLog.CloseMainBlock();
}
//-------------------------------------------------
// fog and blend lights, drawn after emissive surfaces
// so they are properly dimmed down
//-------------------------------------------------
RB_FogAllLights();
//-------------------------------------------------
// capture the depth for the motion blur before rendering any post process surfaces that may contribute to the depth
//-------------------------------------------------
if( r_motionBlur.GetInteger() > 0 )
{
const idScreenRect& viewport = backEnd.viewDef->viewport;
globalImages->currentDepthImage->CopyDepthbuffer( viewport.x1, viewport.y1, viewport.GetWidth(), viewport.GetHeight() );
}
//-------------------------------------------------
// now draw any screen warping post-process effects using _currentRender
//-------------------------------------------------
if( processed < numDrawSurfs && !r_skipPostProcess.GetBool() )
{
int x = backEnd.viewDef->viewport.x1;
int y = backEnd.viewDef->viewport.y1;
int w = backEnd.viewDef->viewport.x2 - backEnd.viewDef->viewport.x1 + 1;
int h = backEnd.viewDef->viewport.y2 - backEnd.viewDef->viewport.y1 + 1;
RENDERLOG_PRINTF( "Resolve to %i x %i buffer\n", w, h );
GL_SelectTexture( 0 );
// resolve the screen
globalImages->currentRenderImage->CopyFramebuffer( x, y, w, h );
backEnd.currentRenderCopied = true;
// RENDERPARM_SCREENCORRECTIONFACTOR amd RENDERPARM_WINDOWCOORD overlap
// diffuseScale and specularScale
// screen power of two correction factor (no longer relevant now)
float screenCorrectionParm[4];
screenCorrectionParm[0] = 1.0f;
screenCorrectionParm[1] = 1.0f;
screenCorrectionParm[2] = 0.0f;
screenCorrectionParm[3] = 1.0f;
SetFragmentParm( RENDERPARM_SCREENCORRECTIONFACTOR, screenCorrectionParm ); // rpScreenCorrectionFactor
// window coord to 0.0 to 1.0 conversion
float windowCoordParm[4];
windowCoordParm[0] = 1.0f / w;
windowCoordParm[1] = 1.0f / h;
windowCoordParm[2] = 0.0f;
windowCoordParm[3] = 1.0f;
SetFragmentParm( RENDERPARM_WINDOWCOORD, windowCoordParm ); // rpWindowCoord
// render the remaining surfaces
renderLog.OpenMainBlock( MRB_DRAW_SHADER_PASSES_POST );
RB_DrawShaderPasses( drawSurfs + processed, numDrawSurfs - processed, 0.0f /* definitely not a gui */, stereoEye );
renderLog.CloseMainBlock();
}
//-------------------------------------------------
// render debug tools
//-------------------------------------------------
RB_RenderDebugTools( drawSurfs, numDrawSurfs );
renderLog.CloseBlock();
}
/*
==================
RB_MotionBlur
Experimental feature
==================
*/
void RB_MotionBlur()
{
if( !backEnd.viewDef->viewEntitys )
{
// 3D views only
return;
}
if( r_motionBlur.GetInteger() <= 0 )
{
return;
}
if( backEnd.viewDef->isSubview )
{
return;
}
GL_CheckErrors();
// clear the alpha buffer and draw only the hands + weapon into it so
// we can avoid blurring them
glClearColor( 0, 0, 0, 1 );
GL_State( GLS_COLORMASK | GLS_DEPTHMASK );
glClear( GL_COLOR_BUFFER_BIT );
GL_Color( 0, 0, 0, 0 );
GL_SelectTexture( 0 );
globalImages->blackImage->Bind();
backEnd.currentSpace = NULL;
drawSurf_t** drawSurfs = ( drawSurf_t** )&backEnd.viewDef->drawSurfs[0];
for( int surfNum = 0; surfNum < backEnd.viewDef->numDrawSurfs; surfNum++ )
{
const drawSurf_t* surf = drawSurfs[ surfNum ];
if( !surf->space->weaponDepthHack && !surf->space->skipMotionBlur && !surf->material->HasSubview() )
{
// Apply motion blur to this object
continue;
}
const idMaterial* shader = surf->material;
if( shader->Coverage() == MC_TRANSLUCENT )
{
// muzzle flash, etc
continue;
}
// set mvp matrix
if( surf->space != backEnd.currentSpace )
{
RB_SetMVP( surf->space->mvp );
backEnd.currentSpace = surf->space;
}
// this could just be a color, but we don't have a skinned color-only prog
if( surf->jointCache )
{
renderProgManager.BindShader_TextureVertexColorSkinned();
}
else
{
renderProgManager.BindShader_TextureVertexColor();
}
// draw it solid
RB_DrawElementsWithCounters( surf );
}
GL_State( GLS_DEPTHFUNC_ALWAYS );
// copy off the color buffer and the depth buffer for the motion blur prog
// we use the viewport dimensions for copying the buffers in case resolution scaling is enabled.
const idScreenRect& viewport = backEnd.viewDef->viewport;
globalImages->currentRenderImage->CopyFramebuffer( viewport.x1, viewport.y1, viewport.GetWidth(), viewport.GetHeight() );
// in stereo rendering, each eye needs to get a separate previous frame mvp
int mvpIndex = ( backEnd.viewDef->renderView.viewEyeBuffer == 1 ) ? 1 : 0;
// derive the matrix to go from current pixels to previous frame pixels
idRenderMatrix inverseMVP;
idRenderMatrix::Inverse( backEnd.viewDef->worldSpace.mvp, inverseMVP );
idRenderMatrix motionMatrix;
idRenderMatrix::Multiply( backEnd.prevMVP[mvpIndex], inverseMVP, motionMatrix );
backEnd.prevMVP[mvpIndex] = backEnd.viewDef->worldSpace.mvp;
RB_SetMVP( motionMatrix );
GL_State( GLS_DEPTHFUNC_ALWAYS );
GL_Cull( CT_TWO_SIDED );
renderProgManager.BindShader_MotionBlur();
// let the fragment program know how many samples we are going to use
idVec4 samples( ( float )( 1 << r_motionBlur.GetInteger() ) );
SetFragmentParm( RENDERPARM_OVERBRIGHT, samples.ToFloatPtr() );
GL_SelectTexture( 0 );
globalImages->currentRenderImage->Bind();
GL_SelectTexture( 1 );
globalImages->currentDepthImage->Bind();
RB_DrawElementsWithCounters( &backEnd.unitSquareSurface );
GL_CheckErrors();
}
/*
==================
RB_DrawView
StereoEye will always be 0 in mono modes, or -1 / 1 in stereo modes.
If the view is a GUI view that is repeated for both eyes, the viewDef.stereoEye value
is 0, so the stereoEye parameter is not always the same as that.
==================
*/
void RB_DrawView( const void* data, const int stereoEye )
{
const drawSurfsCommand_t* cmd = ( const drawSurfsCommand_t* )data;
backEnd.viewDef = cmd->viewDef;
// we will need to do a new copyTexSubImage of the screen
// when a SS_POST_PROCESS material is used
backEnd.currentRenderCopied = false;
// if there aren't any drawsurfs, do nothing
if( !backEnd.viewDef->numDrawSurfs )
{
return;
}
// skip render bypasses everything that has models, assuming
// them to be 3D views, but leaves 2D rendering visible
if( r_skipRender.GetBool() && backEnd.viewDef->viewEntitys )
{
return;
}
// skip render context sets the wgl context to NULL,
// which should factor out the API cost, under the assumption
// that all gl calls just return if the context isn't valid
// RB: not really needed
//if( r_skipRenderContext.GetBool() && backEnd.viewDef->viewEntitys )
//{
// GLimp_DeactivateContext();
//}
// RB end
backEnd.pc.c_surfaces += backEnd.viewDef->numDrawSurfs;
RB_ShowOverdraw();
// render the scene
RB_DrawViewInternal( cmd->viewDef, stereoEye );
RB_MotionBlur();
// restore the context for 2D drawing if we were stubbing it out
// RB: not really needed
//if( r_skipRenderContext.GetBool() && backEnd.viewDef->viewEntitys )
//{
// GLimp_ActivateContext();
// GL_SetDefaultState();
//}
// RB end
// optionally draw a box colored based on the eye number
if( r_drawEyeColor.GetBool() )
{
const idScreenRect& r = backEnd.viewDef->viewport;
GL_Scissor( ( r.x1 + r.x2 ) / 2, ( r.y1 + r.y2 ) / 2, 32, 32 );
switch( stereoEye )
{
case -1:
GL_Clear( true, false, false, 0, 1.0f, 0.0f, 0.0f, 1.0f );
break;
case 1:
GL_Clear( true, false, false, 0, 0.0f, 1.0f, 0.0f, 1.0f );
break;
default:
GL_Clear( true, false, false, 0, 0.5f, 0.5f, 0.5f, 1.0f );
break;
}
}
}
/*
==================
RB_CopyRender
Copy part of the current framebuffer to an image
==================
*/
void RB_CopyRender( const void* data )
{
const copyRenderCommand_t* cmd = ( const copyRenderCommand_t* )data;
if( r_skipCopyTexture.GetBool() )
{
return;
}
RENDERLOG_PRINTF( "***************** RB_CopyRender *****************\n" );
if( cmd->image )
{
cmd->image->CopyFramebuffer( cmd->x, cmd->y, cmd->imageWidth, cmd->imageHeight );
}
if( cmd->clearColorAfterCopy )
{
GL_Clear( true, false, false, STENCIL_SHADOW_TEST_VALUE, 0, 0, 0, 0 );
}
}
/*
==================
RB_PostProcess
==================
*/
extern idCVar rs_enable;
void RB_PostProcess( const void* data )
{
// only do the post process step if resolution scaling is enabled. Prevents the unnecessary copying of the framebuffer and
// corresponding full screen quad pass.
if( rs_enable.GetInteger() == 0 )
{
return;
}
// resolve the scaled rendering to a temporary texture
postProcessCommand_t* cmd = ( postProcessCommand_t* )data;
const idScreenRect& viewport = cmd->viewDef->viewport;
globalImages->currentRenderImage->CopyFramebuffer( viewport.x1, viewport.y1, viewport.GetWidth(), viewport.GetHeight() );
GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO | GLS_DEPTHMASK | GLS_DEPTHFUNC_ALWAYS );
GL_Cull( CT_TWO_SIDED );
int screenWidth = renderSystem->GetWidth();
int screenHeight = renderSystem->GetHeight();
// set the window clipping
GL_Viewport( 0, 0, screenWidth, screenHeight );
GL_Scissor( 0, 0, screenWidth, screenHeight );
GL_SelectTexture( 0 );
globalImages->currentRenderImage->Bind();
renderProgManager.BindShader_PostProcess();
// Draw
RB_DrawElementsWithCounters( &backEnd.unitSquareSurface );
renderLog.CloseBlock();
}
| davidfoerster/RBDOOM-3-BFG | neo/renderer/tr_backend_draw.cpp | C++ | gpl-3.0 | 131,540 |
/**
* The package contains all kinds of date object groupers for JIDE Common Layer.
*/
package com.jidesoft.grouper.date; | clementvillanueva/SimpleHDR | src/com/jidesoft/grouper/date/package-info.java | Java | gpl-3.0 | 123 |
package org.defascat.presentation.basic;
import java.util.Arrays;
import java.util.List;
/*
javap -c ../demo/target/classes/org/defascat/presentation/unsorted/IntCache.class
*/
public class IntCache {
public static void main(String[] args) {
List<Integer> a = Arrays.asList(22);
System.out.println(a);
}
}
| defascat/presentation-tool | demo/src/main/java/org/defascat/presentation/basic/IntCache.java | Java | gpl-3.0 | 332 |
<?php
/**
* Shop breadcrumb
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.3.0
* @see woocommerce_breadcrumb()
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} ?>
<div class="container">
<?php if ( ! empty( $breadcrumb ) ) {
echo $wrap_before;
foreach ( $breadcrumb as $key => $crumb ) {
echo $before;
if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
echo '<a href="' . esc_url( $crumb[1] ) . '">' . esc_html( $crumb[0] ) . '</a>';
} else {
echo esc_html( $crumb[0] );
}
echo $after;
if ( sizeof( $breadcrumb ) !== $key + 1 ) {
echo $delimiter;
}
}
echo $wrap_after;
} ?>
</div> <!--container-->
| andrezsegovia/wordpressproject | wp-content/themes/motors/woocommerce/global/breadcrumb.php | PHP | gpl-3.0 | 707 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Product.date_added'
db.add_column(u'clone_product', 'date_added',
self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, default=datetime.datetime(2014, 8, 3, 0, 0), blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Product.date_added'
db.delete_column(u'clone_product', 'date_added')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'clone.product': {
'Meta': {'object_name': 'Product'},
'base_price': ('django.db.models.fields.FloatField', [], {}),
'currency': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'username': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['clone'] | indradhanush/Instamojo-Clone | clone/migrations/0002_auto__add_field_product_date_added.py | Python | gpl-3.0 | 4,593 |
# -*- encoding : utf-8 -*-
class Student < ActiveRecord::Base
has_one :machine
end
| fermuch/CINC | app/models/student.rb | Ruby | gpl-3.0 | 85 |
class Video(object):
def __init__(self, json):
self.id = json['id']
self.slug = json['slug']
self.title = json['title']
self.presenters = json['presenters']
self.host = json['host']
self.embed_code = json['embed_code']
def presenter_names(self):
return ', '.join(map(lambda p: p['first_name'] + ' ' + p['last_name'], self.presenters))
def url(self):
return 'plugin://plugin.video.%s/?action=play_video&videoid=%s' % (self.host, self.embed_code)
def is_available(self):
return True if self.embed_code else False
| watsonbox/xbmc-confreaks | api/video.py | Python | gpl-3.0 | 558 |
package ihl.processing.metallurgy;
import ic2.core.ContainerBase;
import ic2.core.slot.SlotInvSlot;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
public class DetonationSprayingMachineContainer extends ContainerBase<DetonationSprayingMachineTileEntity> {
protected DetonationSprayingMachineTileEntity tileEntity;
public int lastFluidAmount = -1;
public short lastProgress = -1;
private final static int height=166;
public DetonationSprayingMachineContainer(EntityPlayer entityPlayer, DetonationSprayingMachineTileEntity detonationSprayingMachineTileEntity){
super(detonationSprayingMachineTileEntity);
this.tileEntity = detonationSprayingMachineTileEntity;
int col;
for (col = 0; col < 3; ++col)
{
for (int col1 = 0; col1 < 9; ++col1)
{
this.addSlotToContainer(new Slot(entityPlayer.inventory, col1 + col * 9 + 9, 8 + col1 * 18, height + -82 + col * 18));
}
}
for (col = 0; col < 9; ++col)
{
this.addSlotToContainer(new Slot(entityPlayer.inventory, col, 8 + col * 18, height + -24));
}
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 0, 10, 17));
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 1, 98, 17));
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 2, 117, 17));
}
@Override
public boolean canInteractWith(EntityPlayer var1) {
return tileEntity.isUseableByPlayer(var1);
}
}
| Foghrye4/ihl | src/main/java/ihl/processing/metallurgy/DetonationSprayingMachineContainer.java | Java | gpl-3.0 | 1,679 |
// Package parameters parses json into parameters object
// usage:
// 1) parse json to parameters:
// parameters.MakeParsedReq(fn http.HandlerFunc)
// 2) get the parameters:
// params := parameters.GetParams(req)
// val := params.GetXXX("key")
package parameters
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"log"
"math"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/julienschmidt/httprouter"
"github.com/ugorji/go/codec"
)
const (
ParamsKey = "params"
)
type Params struct {
isBinary bool
Values map[string]interface{}
}
func (p *Params) Get(key string) (interface{}, bool) {
keys := strings.Split(key, ".")
root := p.Values
var ok bool
var val interface{}
count := len(keys)
for i := 0; i < count; i++ {
val, ok = root[keys[i]]
if ok && i < count-1 {
root = val.(map[string]interface{})
}
}
return val, ok
}
func (p *Params) GetFloatOk(key string) (float64, bool) {
val, ok := p.Get(key)
if sval, sok := val.(string); sok {
var err error
val, err = strconv.ParseFloat(sval, 64)
ok = err == nil
}
if ok {
return val.(float64), true
}
return 0, false
}
func (p *Params) GetFloat(key string) float64 {
f, _ := p.GetFloatOk(key)
return f
}
func (p *Params) GetFloatSliceOk(key string) ([]float64, bool) {
val, ok := p.Get(key)
if ok {
switch val.(type) {
case []float64:
return val.([]float64), true
case string:
raw := strings.Split(val.(string), ",")
slice := make([]float64, len(raw))
for i, k := range raw {
if num, err := strconv.ParseFloat(k, 64); err == nil {
slice[i] = num
}
}
return slice, true
case []interface{}:
raw := val.([]interface{})
slice := make([]float64, len(raw))
for i, k := range raw {
if num, ok := k.(float64); ok {
slice[i] = num
} else if num, ok := k.(string); ok {
if parsed, err := strconv.ParseFloat(num, 64); err == nil {
slice[i] = parsed
}
}
}
return slice, true
}
}
return []float64{}, false
}
func (p *Params) GetFloatSlice(key string) []float64 {
slice, _ := p.GetFloatSliceOk(key)
return slice
}
func (p *Params) GetBoolOk(key string) (bool, bool) {
val, ok := p.Get(key)
if ok {
if b, ib := val.(bool); ib {
return b, true
} else if i, ik := p.GetIntOk(key); ik {
if i == 0 {
return false, true
} else {
return true, true
}
}
}
return false, false
}
func (p *Params) GetBool(key string) bool {
f, _ := p.GetBoolOk(key)
return f
}
func (p *Params) GetIntOk(key string) (int, bool) {
val, ok := p.Get(key)
if sval, sok := val.(string); sok {
var err error
val, err = strconv.ParseFloat(sval, 64)
ok = err == nil
}
if ok {
if ival, ok := val.(int64); ok {
return int(ival), true
} else if fval, ok := val.(float64); ok {
return int(fval), true
}
}
return 0, false
}
func (p *Params) GetInt(key string) int {
f, _ := p.GetIntOk(key)
return f
}
func (p *Params) GetInt8Ok(key string) (int8, bool) {
val, ok := p.GetIntOk(key)
if !ok || val < math.MinInt8 || val > math.MaxInt8 {
return 0, false
}
return int8(val), true
}
func (p *Params) GetInt8(key string) int8 {
f, _ := p.GetInt8Ok(key)
return f
}
func (p *Params) GetInt16Ok(key string) (int16, bool) {
val, ok := p.GetIntOk(key)
if !ok || val < math.MinInt16 || val > math.MaxInt16 {
return 0, false
}
return int16(val), true
}
func (p *Params) GetInt16(key string) int16 {
f, _ := p.GetInt16Ok(key)
return f
}
func (p *Params) GetInt32Ok(key string) (int32, bool) {
val, ok := p.GetIntOk(key)
if !ok || val < math.MinInt32 || val > math.MaxInt32 {
return 0, false
}
return int32(val), true
}
func (p *Params) GetInt32(key string) int32 {
f, _ := p.GetInt32Ok(key)
return f
}
func (p *Params) GetInt64Ok(key string) (int64, bool) {
val, ok := p.GetIntOk(key)
if !ok {
return 0, false
}
return int64(val), true
}
func (p *Params) GetInt64(key string) int64 {
f, _ := p.GetIntOk(key)
return int64(f)
}
func (p *Params) GetIntSliceOk(key string) ([]int, bool) {
val, ok := p.Get(key)
if ok {
switch val.(type) {
case []int:
return val.([]int), true
case []byte:
val = string(val.([]byte))
raw := strings.Split(val.(string), ",")
slice := make([]int, len(raw))
for i, k := range raw {
if num, err := strconv.ParseInt(k, 10, 64); err == nil {
slice[i] = int(num)
} else {
return slice, false
}
}
return slice, true
case string:
if len(val.(string)) > 0 {
raw := strings.Split(val.(string), ",")
slice := make([]int, len(raw))
for i, k := range raw {
if num, err := strconv.ParseInt(k, 10, 64); err == nil {
slice[i] = int(num)
} else {
return slice, false
}
}
return slice, true
}
case []interface{}:
raw := val.([]interface{})
slice := make([]int, len(raw))
for i, k := range raw {
if num, ok := k.(int); ok {
slice[i] = num
} else if num, ok := k.(float64); ok {
slice[i] = int(num)
} else if num, ok := k.(string); ok {
if parsed, err := strconv.ParseInt(num, 10, 64); err == nil {
slice[i] = int(parsed)
} else {
return slice, false
}
}
}
return slice, true
}
}
return []int{}, false
}
func (p *Params) GetIntSlice(key string) []int {
slice, _ := p.GetIntSliceOk(key)
return slice
}
func (p *Params) GetUint64Ok(key string) (uint64, bool) {
val, ok := p.Get(key)
if sval, sok := val.(string); sok {
var err error
val, err = strconv.ParseFloat(sval, 64)
ok = err == nil && val.(float64) >= 0
}
if ok {
if valInt, ok := val.(int64); ok {
val = uint64(valInt)
}
if valUint, ok := val.(uint64); ok {
return valUint, true
} else if valUint, ok := val.(uint); ok {
return uint64(valUint), true
} else if valUint, ok := val.(uint8); ok {
return uint64(valUint), true
} else if valUint, ok := val.(uint16); ok {
return uint64(valUint), true
} else if valUint, ok := val.(uint32); ok {
return uint64(valUint), true
} else if valfloat, ok := val.(float64); valfloat >= 0 && ok {
return uint64(valfloat), true
} else if valbyte, ok := val.([]byte); ok {
var err error
valfloat, err = strconv.ParseFloat(string(valbyte), 64)
ok = err == nil && valfloat >= 0
return uint64(valfloat), ok
}
}
return 0, false
}
func (p *Params) GetUint64(key string) uint64 {
f, _ := p.GetUint64Ok(key)
return f
}
func (p *Params) GetUint64SliceOk(key string) ([]uint64, bool) {
if raw, ok := p.GetIntSliceOk(key); ok {
slice := make([]uint64, len(raw))
for i, num := range raw {
slice[i] = uint64(num)
}
return slice, true
}
return []uint64{}, false
}
func (p *Params) GetUint64Slice(key string) []uint64 {
slice, _ := p.GetUint64SliceOk(key)
return slice
}
func (p *Params) GetStringOk(key string) (string, bool) {
val, ok := p.Get(key)
if ok {
if s, is := val.(string); is {
return s, true
} else if s, is := val.([]byte); is {
return string(s), true
}
}
return "", false
}
func (p *Params) GetString(key string) string {
//Get the string if found
str, _ := p.GetStringOk(key)
//Return the string, trim spaces
return strings.Trim(str, " ")
}
func (p *Params) GetStringSliceOk(key string) ([]string, bool) {
val, ok := p.Get(key)
if ok {
switch val.(type) {
case []string:
return val.([]string), true
case string:
return strings.Split(val.(string), ","), true
case []interface{}:
raw := val.([]interface{})
slice := make([]string, len(raw))
for i, k := range raw {
slice[i] = k.(string)
}
return slice, true
}
}
return []string{}, false
}
func (p *Params) GetStringSlice(key string) []string {
slice, _ := p.GetStringSliceOk(key)
return slice
}
func (p *Params) GetBytesOk(key string) ([]byte, bool) {
if dataStr, ok := p.Get(key); ok {
var dataByte []byte
var ok bool
if dataByte, ok = dataStr.([]byte); !ok {
var err error
dataByte, err = base64.StdEncoding.DecodeString(dataStr.(string))
if err != nil {
log.Println("Error decoding data:", key, err)
return nil, false
}
p.Values[key] = dataByte
}
return dataByte, true
}
return nil, false
}
func (p *Params) GetBytes(key string) []byte {
bytes, _ := p.GetBytesOk(key)
return bytes
}
const (
DateOnly = "2006-01-02"
//DateTime is not recommended, rather use time.RFC3339
DateTime = "2006-01-02 15:04:05"
// HTMLDateTimeLocal is the format used by the input type datetime-local
HTMLDateTimeLocal = "2006-01-02T15:04"
)
func (p *Params) GetTimeOk(key string) (time.Time, bool) {
return p.GetTimeInLocationOk(key, time.UTC)
}
func (p *Params) GetTime(key string) time.Time {
t, _ := p.GetTimeOk(key)
return t
}
func (p *Params) GetTimeInLocationOk(key string, loc *time.Location) (time.Time, bool) {
val, ok := p.Get(key)
if !ok {
return time.Time{}, false
}
if t, ok := val.(time.Time); ok {
return t, true
}
if str, ok := val.(string); ok {
if t, err := time.ParseInLocation(time.RFC3339, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(DateOnly, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(DateTime, str, loc); err == nil {
return t, true
}
if t, err := time.ParseInLocation(HTMLDateTimeLocal, str, loc); err == nil {
return t, true
}
}
return time.Time{}, false
}
func (p *Params) GetTimeInLocation(key string, loc *time.Location) time.Time {
t, _ := p.GetTimeInLocationOk(key, loc)
return t
}
func (p *Params) GetFileOk(key string) (*multipart.FileHeader, bool) {
val, ok := p.Get(key)
if !ok {
return nil, false
}
if fh, ok := val.(*multipart.FileHeader); ok {
return fh, true
}
return nil, false
}
func (p *Params) GetJSONOk(key string) (map[string]interface{}, bool) {
if v, ok := p.Get(key); ok {
if d, ok := v.(map[string]interface{}); ok {
return d, true
}
}
val, ok := p.GetStringOk(key)
var jsonData map[string]interface{}
if !ok {
return jsonData, false
}
err := json.NewDecoder(strings.NewReader(val)).Decode(&jsonData)
if err != nil {
return jsonData, false
}
return jsonData, true
}
func (p *Params) GetJSON(key string) map[string]interface{} {
data, _ := p.GetJSONOk(key)
return data
}
func MakeParsedReq(fn http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), ParamsKey, ParseParams(r)))
fn(rw, r)
}
}
func MakeHTTPRouterParsedReq(fn httprouter.Handle) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
r = r.WithContext(context.WithValue(r.Context(), ParamsKey, ParseParams(r)))
params := GetParams(r)
for _, param := range p {
const ID = "id"
if strings.Contains(param.Key, ID) {
id, perr := strconv.ParseUint(param.Value, 10, 64)
if perr != nil {
params.Values[param.Key] = param.Value
} else {
params.Values[param.Key] = id
}
} else {
params.Values[param.Key] = param.Value
}
}
fn(rw, r, p)
}
}
func GetParams(req *http.Request) *Params {
params := req.Context().Value(ParamsKey).(*Params)
return params
}
type CustomTypeHandler func(field *reflect.Value, value interface{}) error
// CustomTypeSetter is used when Imbue is called on an object to handle unknown
// types
var CustomTypeSetter CustomTypeHandler
var (
typeOfTime reflect.Type = reflect.TypeOf(time.Time{})
typeOfPtrToTime reflect.Type = reflect.PtrTo(typeOfTime)
)
// Clone makes a copy of this params object
func (p *Params) Clone() *Params {
values := make(map[string]interface{}, len(p.Values))
for k, v := range p.Values {
values[k] = v
}
return &Params{
isBinary: p.isBinary,
Values: values,
}
}
//Sets the parameters to the object by type; does not handle nested parameters
func (p *Params) Imbue(obj interface{}) {
//Get the type of the object
typeOfObject := reflect.TypeOf(obj).Elem()
//Get the object
objectValue := reflect.ValueOf(obj).Elem()
//Loop our parameters
for k, _ := range p.Values {
//Make the incoming key_name into KeyName
key := SnakeToCamelCase(k, true)
//Get the type and bool if found
fieldType, found := typeOfObject.FieldByName(key)
//Skip parameter if not found on struct
if !found {
continue
}
//Get the field of the key
field := objectValue.FieldByName(key)
//Check our types and set accordingly
if fieldType.Type.Kind() == reflect.String {
//Set string
field.Set(reflect.ValueOf(p.GetString(k)))
} else if fieldType.Type.Kind() == reflect.Uint64 {
//Set Uint64
field.Set(reflect.ValueOf(p.GetUint64(k)))
} else if fieldType.Type.Kind() == reflect.Int {
//Set Int
field.Set(reflect.ValueOf(p.GetInt(k)))
} else if fieldType.Type.Kind() == reflect.Bool {
//Set bool
field.Set(reflect.ValueOf(p.GetBool(k)))
} else if fieldType.Type.Kind() == reflect.Float32 {
//Set float32
field.Set(reflect.ValueOf(float32(p.GetFloat(k))))
} else if fieldType.Type.Kind() == reflect.Float64 {
//Set float64
field.Set(reflect.ValueOf(p.GetFloat(k)))
} else if fieldType.Type == reflect.SliceOf(reflect.TypeOf("")) {
//Set []string
field.Set(reflect.ValueOf(p.GetStringSlice(k)))
} else if fieldType.Type == reflect.SliceOf(reflect.TypeOf(int(0))) {
//Set []int
field.Set(reflect.ValueOf(p.GetIntSlice(k)))
} else if fieldType.Type == reflect.SliceOf(reflect.TypeOf(uint64(0))) {
//Set []uint64
field.Set(reflect.ValueOf(p.GetUint64Slice(k)))
} else if fieldType.Type == reflect.SliceOf(reflect.TypeOf(float64(0))) {
//Set []float64
field.Set(reflect.ValueOf(p.GetFloatSlice(k)))
} else if fieldType.Type == typeOfTime {
//Set time.Time
field.Set(reflect.ValueOf(p.GetTime(k)))
} else if fieldType.Type == typeOfPtrToTime {
//Set *time.Time
t := p.GetTime(k)
field.Set(reflect.ValueOf(&t))
} else {
val, _ := p.Get(k)
if CustomTypeSetter != nil && CustomTypeSetter(&field, val) == nil {
continue
}
if subVals, ok := p.GetJSONOk(k); ok {
fieldValue := reflect.Indirect(objectValue).FieldByName(key)
if reflect.ValueOf(fieldValue).IsZero() {
continue
}
typeOfP := reflect.TypeOf(fieldValue.Interface())
newObj := reflect.New(typeOfP).Interface()
subParam := &Params{
Values: subVals,
}
subParam.Imbue(newObj)
field.Set(reflect.ValueOf(newObj).Elem())
}
}
}
}
// HasAll will return if all specified keys are found in the params object
func (p *Params) HasAll(keys ...string) (bool, []string) {
missing := make([]string, 0)
for _, key := range keys {
if _, exists := p.Values[key]; !exists {
missing = append(missing, key)
}
}
return len(missing) == 0, missing
}
//Permits only the allowed fields given by allowedKeys
func (p *Params) Permit(allowedKeys []string) {
for key, _ := range p.Values {
if !contains(allowedKeys, key) {
delete(p.Values, key)
}
}
}
func contains(haystack []string, needle string) bool {
needle = strings.ToLower(needle)
for _, straw := range haystack {
if strings.ToLower(straw) == needle {
return true
}
}
return false
}
func ParseParams(req *http.Request) *Params {
var p Params
if params, exists := req.Context().Value(ParamsKey).(*Params); exists {
return params
}
ct := req.Header.Get("Content-Type")
ct = strings.Split(ct, ";")[0]
if ct == "multipart/form-data" {
if err := req.ParseMultipartForm(10000000); err != nil {
log.Println("Request.ParseMultipartForm Error", err)
}
} else {
if err := req.ParseForm(); err != nil {
log.Println("Request.ParseForm Error", err)
}
}
tmap := make(map[string]interface{}, len(req.Form))
for k, v := range req.Form {
if strings.ToLower(v[0]) == "true" {
tmap[k] = true
} else if strings.ToLower(v[0]) == "false" {
tmap[k] = false
} else {
tmap[k] = v[0]
}
}
if req.MultipartForm != nil {
for k, v := range req.MultipartForm.File {
tmap[k] = v[0]
}
}
if ct == "application/json" && req.ContentLength > 0 {
err := json.NewDecoder(req.Body).Decode(&p.Values)
if err != nil {
log.Println("Content-Type is \"application/json\" but no valid json data received", err)
p.Values = tmap
}
for k, v := range tmap {
if _, pres := p.Values[k]; !pres {
p.Values[k] = v
}
}
} else if ct == "application/x-msgpack" {
var mh codec.MsgpackHandle
p.isBinary = true
mh.MapType = reflect.TypeOf(p.Values)
body, _ := ioutil.ReadAll(req.Body)
if len(body) > 0 {
buff := bytes.NewBuffer(body)
first := body[0]
if (first >= 0x80 && first <= 0x8f) || (first == 0xde || first == 0xdf) {
err := codec.NewDecoder(buff, &mh).Decode(&p.Values)
if err != nil && err != io.EOF {
log.Println("Failed decoding msgpack", err)
}
} else {
if p.Values == nil {
p.Values = make(map[string]interface{}, 0)
}
var err error
for err == nil {
vals := make([]interface{}, 0)
err = codec.NewDecoder(buff, &mh).Decode(&vals)
if err != nil && err != io.EOF {
log.Println("Failed decoding msgpack", err)
} else {
for i := len(vals) - 1; i >= 1; i -= 2 {
p.Values[string(vals[i-1].([]byte))] = vals[i]
}
}
}
}
} else {
p.Values = make(map[string]interface{}, 0)
}
for k, v := range tmap {
if _, pres := p.Values[k]; !pres {
p.Values[k] = v
}
}
} else {
p.Values = tmap
}
for k, v := range mux.Vars(req) {
const ID = "id"
if strings.Contains(k, ID) {
id, perr := strconv.ParseUint(v, 10, 64)
if perr != nil {
p.Values[k] = v
} else {
p.Values[k] = id
}
} else {
p.Values[k] = v
}
}
return &p
}
| BakedSoftware/go-parameters | params.go | GO | gpl-3.0 | 17,740 |
<?php
/*** COPYRIGHT NOTICE *********************************************************
*
* Copyright 2009-2014 Pascal BERNARD - support@projeqtor.org
* Contributors : -
*
* This file is part of ProjeQtOr.
*
* ProjeQtOr is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* ProjeQtOr is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* ProjeQtOr. If not, see <http://www.gnu.org/licenses/>.
*
* You can get complete code of ProjeQtOr, other resource, help and information
* about contributors at http://www.projeqtor.org
*
*** DO NOT REMOVE THIS NOTICE ************************************************/
/* ============================================================================
* ActionType defines the type of an issue.
*/
require_once('_securityCheck.php');
class IndividualExpenseType extends ShortType {
// Define the layout that will be used for lists
private static $_databaseCriteria = array('scope'=>'IndividualExpense');
/** ==========================================================================
* Constructor
* @param $id the id of the object in the database (null if not stored yet)
* @return void
*/
function __construct($id = NULL) {
parent::__construct($id);
}
/** ==========================================================================
* Destructor
* @return void
*/
function __destruct() {
parent::__destruct();
}
// ============================================================================**********
// GET STATIC DATA FUNCTIONS
// ============================================================================**********
/** ========================================================================
* Return the specific database criteria
* @return the databaseTableName
*/
protected function getStaticDatabaseCriteria() {
return self::$_databaseCriteria;
}
}
?> | nikochan2k/projeqtor-ja | model/IndividualExpenseType.php | PHP | gpl-3.0 | 2,362 |
/******************************************************************************
*
* $Id: $
*
*
* Copyright (C) 1997-2012 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
#include <qfileinfo.h>
#include "latexdocvisitor.h"
#include "docparser.h"
#include "language.h"
#include "doxygen.h"
#include "outputgen.h"
#include "dot.h"
#include "util.h"
#include "message.h"
#include "parserintf.h"
#include "msc.h"
#include "htmlattrib.h"
#include "cite.h"
static QCString escapeLabelName(const char *s)
{
QCString result;
const char *p=s;
char c;
while ((c=*p++))
{
switch (c)
{
case '%': result+="\\%"; break;
case '|': result+="\\texttt{\"|}"; break;
case '!': result+="\"!"; break;
default: result+=c;
}
}
return result;
}
const int maxLevels=5;
static const char *secLabels[maxLevels] =
{ "section","subsection","subsubsection","paragraph","subparagraph" };
static const char *getSectionName(int level)
{
static bool compactLatex = Config_getBool("COMPACT_LATEX");
int l = level;
if (compactLatex) l++;
if (Doxygen::insideMainPage) l--;
return secLabels[QMIN(maxLevels-1,l)];
}
QCString LatexDocVisitor::escapeMakeIndexChars(const char *s)
{
QCString result;
const char *p=s;
char str[2]; str[1]=0;
char c;
while ((c=*p++))
{
switch (c)
{
case '!': m_t << "\"!"; break;
case '"': m_t << "\"\""; break;
case '@': m_t << "\"@"; break;
case '|': m_t << "\\texttt{\"|}"; break;
case '[': m_t << "["; break;
case ']': m_t << "]"; break;
default: str[0]=c; filter(str); break;
}
}
return result;
}
LatexDocVisitor::LatexDocVisitor(FTextStream &t,CodeOutputInterface &ci,
const char *langExt,bool insideTabbing)
: DocVisitor(DocVisitor_Latex), m_t(t), m_ci(ci), m_insidePre(FALSE),
m_insideItem(FALSE), m_hide(FALSE), m_insideTabbing(insideTabbing),
m_insideTable(FALSE), m_langExt(langExt), m_currentColumn(0),
m_inRowspan(FALSE), m_inColspan(FALSE)
{
m_rowSpans.setAutoDelete(TRUE);
}
//--------------------------------------
// visitor functions for leaf nodes
//--------------------------------------
void LatexDocVisitor::visit(DocWord *w)
{
if (m_hide) return;
filter(w->word());
}
void LatexDocVisitor::visit(DocLinkedWord *w)
{
if (m_hide) return;
startLink(w->ref(),w->file(),w->anchor());
filter(w->word());
endLink(w->ref(),w->file(),w->anchor());
}
void LatexDocVisitor::visit(DocWhiteSpace *w)
{
if (m_hide) return;
if (m_insidePre)
{
m_t << w->chars();
}
else
{
m_t << " ";
}
}
void LatexDocVisitor::visit(DocSymbol *s)
{
if (m_hide) return;
switch(s->symbol())
{
case DocSymbol::BSlash: m_t << "\\textbackslash{}"; break;
case DocSymbol::At: m_t << "@"; break;
case DocSymbol::Less: if (m_insidePre) m_t << "<"; else m_t << "$<$";
break;
case DocSymbol::Greater: if (m_insidePre) m_t << ">"; else m_t << "$>$"; break;
case DocSymbol::Amp: m_t << "\\&"; break;
case DocSymbol::Dollar: m_t << "\\$"; break;
case DocSymbol::Hash: m_t << "\\#"; break;
case DocSymbol::DoubleColon: m_t << "::"; break;
case DocSymbol::Percent: m_t << "\\%"; break;
case DocSymbol::Pipe: m_t << "$|$"; break;
case DocSymbol::Copy: m_t << "\\copyright"; break;
case DocSymbol::Tm: m_t << "\\texttrademark"; break;
case DocSymbol::Reg: m_t << "\\textregistered"; break;
case DocSymbol::Apos: m_t << "'"; break;
case DocSymbol::Quot: m_t << "\""; break;
case DocSymbol::Lsquo: m_t << "`"; break;
case DocSymbol::Rsquo: m_t << "'"; break;
case DocSymbol::Ldquo: m_t << "``"; break;
case DocSymbol::Rdquo: m_t << "''"; break;
case DocSymbol::Ndash: m_t << "--"; break;
case DocSymbol::Mdash: m_t << "---"; break;
case DocSymbol::Uml:
if (s->letter()=='i')
m_t << "\\\"{\\i}";
else
m_t << "\\\"{" << s->letter() << "}";
break;
case DocSymbol::Acute:
if (s->letter()=='i')
m_t << "\\'{\\i}";
else
m_t << "\\'{" << s->letter() << "}";
break;
case DocSymbol::Grave:
if (s->letter()=='i')
m_t << "\\`{\\i}";
else
m_t << "\\`{" << s->letter() << "}";
break;
case DocSymbol::Circ:
if (s->letter()=='i')
m_t << "\\^{\\i}";
else
m_t << "\\^{" << s->letter() << "}";
break;
case DocSymbol::Slash: if (tolower(s->letter())=='o')
m_t << "{\\" << s->letter() << "}";
else
m_t << s->letter();
break;
case DocSymbol::Tilde: m_t << "\\~{" << s->letter() << "}"; break;
case DocSymbol::Szlig: m_t << "{\\ss}"; break;
case DocSymbol::Cedil: m_t << "\\c{" << s->letter() << "}"; break;
case DocSymbol::Ring: m_t << "\\" << s->letter() << s->letter(); break;
case DocSymbol::Nbsp: m_t << "~"; break;
case DocSymbol::AElig: m_t << "{\\AE}"; break;
case DocSymbol::Aelig: m_t << "{\\ae}"; break;
case DocSymbol::GrkGamma: m_t << "{$\\Gamma$}"; break;
case DocSymbol::GrkDelta: m_t << "{$\\Delta$}"; break;
case DocSymbol::GrkTheta: m_t << "{$\\Theta$}"; break;
case DocSymbol::GrkLambda: m_t << "{$\\Lambda$}"; break;
case DocSymbol::GrkXi: m_t << "{$\\Xi$}"; break;
case DocSymbol::GrkPi: m_t << "{$\\Pi$}"; break;
case DocSymbol::GrkSigma: m_t << "{$\\Sigma$}"; break;
case DocSymbol::GrkUpsilon: m_t << "{$\\Upsilon$}"; break;
case DocSymbol::GrkPhi: m_t << "{$\\Phi$}"; break;
case DocSymbol::GrkPsi: m_t << "{$\\Psi$}"; break;
case DocSymbol::GrkOmega: m_t << "{$\\Omega$}"; break;
case DocSymbol::Grkalpha: m_t << "{$\\alpha$}"; break;
case DocSymbol::Grkbeta: m_t << "{$\\beta$}"; break;
case DocSymbol::Grkgamma: m_t << "{$\\gamma$}"; break;
case DocSymbol::Grkdelta: m_t << "{$\\delta$}"; break;
case DocSymbol::Grkepsilon: m_t << "{$\\varepsilon$}"; break;
case DocSymbol::Grkzeta: m_t << "{$\\zeta$}"; break;
case DocSymbol::Grketa: m_t << "{$\\eta$}"; break;
case DocSymbol::Grktheta: m_t << "{$\\theta$}"; break;
case DocSymbol::Grkiota: m_t << "{$\\iota$}"; break;
case DocSymbol::Grkkappa: m_t << "{$\\kappa$}"; break;
case DocSymbol::Grklambda: m_t << "{$\\lambda$}"; break;
case DocSymbol::Grkmu: m_t << "{$\\mu$}"; break;
case DocSymbol::Grknu: m_t << "{$\\nu$}"; break;
case DocSymbol::Grkxi: m_t << "{$\\xi$}"; break;
case DocSymbol::Grkpi: m_t << "{$\\pi$}"; break;
case DocSymbol::Grkrho: m_t << "{$\\rho$}"; break;
case DocSymbol::Grksigma: m_t << "{$\\sigma$}"; break;
case DocSymbol::Grktau: m_t << "{$\\tau$}"; break;
case DocSymbol::Grkupsilon: m_t << "{$\\upsilon$}"; break;
case DocSymbol::Grkphi: m_t << "{$\\varphi$}"; break;
case DocSymbol::Grkchi: m_t << "{$\\chi$}"; break;
case DocSymbol::Grkpsi: m_t << "{$\\psi$}"; break;
case DocSymbol::Grkomega: m_t << "{$\\omega$}"; break;
case DocSymbol::Grkvarsigma: m_t << "{$\\varsigma$}"; break;
case DocSymbol::Section: m_t << "{$\\S$}"; break;
case DocSymbol::Degree: m_t << "\\textdegree"; break;
case DocSymbol::Prime: m_t << "'"; break;
case DocSymbol::DoublePrime: m_t << "''"; break;
case DocSymbol::Infinity: m_t << "{$\\infty$}"; break;
case DocSymbol::EmptySet: m_t << "{$\\emptyset$}"; break;
case DocSymbol::PlusMinus: m_t << "{$\\pm$}"; break;
case DocSymbol::Times: m_t << "{$\\times$}"; break;
case DocSymbol::Minus: m_t << "-"; break;
case DocSymbol::CenterDot: m_t << "{$\\cdot$}"; break;
case DocSymbol::Partial: m_t << "{$\\partial$}"; break;
case DocSymbol::Nabla: m_t << "{$\\nabla$}"; break;
case DocSymbol::SquareRoot: m_t << "{$\\surd$}"; break;
case DocSymbol::Perpendicular: m_t << "{$\\perp$}"; break;
case DocSymbol::Sum: m_t << "{$\\sum$}"; break;
case DocSymbol::Integral: m_t << "{$\\int$}"; break;
case DocSymbol::Product: m_t << "{$\\prod$}"; break;
case DocSymbol::Similar: m_t << "{$\\sim$}"; break;
case DocSymbol::Approx: m_t << "{$\\approx$}"; break;
case DocSymbol::NotEqual: m_t << "{$\\ne$}"; break;
case DocSymbol::Equivalent: m_t << "{$\\equiv$}"; break;
case DocSymbol::Proportional: m_t << "{$\\propto$}"; break;
case DocSymbol::LessEqual: m_t << "{$\\le$}"; break;
case DocSymbol::GreaterEqual: m_t << "{$\\ge$}"; break;
case DocSymbol::LeftArrow: m_t << "{$\\leftarrow$}"; break;
case DocSymbol::RightArrow: m_t << "{$\\rightarrow$}"; break;
case DocSymbol::SetIn: m_t << "{$\\in$}"; break;
case DocSymbol::SetNotIn: m_t << "{$\\notin$}"; break;
case DocSymbol::LeftCeil: m_t << "{$\\lceil$}"; break;
case DocSymbol::RightCeil: m_t << "{$\\rceil$}"; break;
case DocSymbol::LeftFloor: m_t << "{$\\lfloor$}"; break;
case DocSymbol::RightFloor: m_t << "{$\\rfloor$}"; break;
default:
err("error: unknown symbol found\n");
}
}
void LatexDocVisitor::visit(DocURL *u)
{
if (m_hide) return;
if (Config_getBool("PDF_HYPERLINKS"))
{
m_t << "\\href{";
if (u->isEmail()) m_t << "mailto:";
m_t << u->url() << "}";
}
m_t << "{\\tt ";
filter(u->url());
m_t << "}";
}
void LatexDocVisitor::visit(DocLineBreak *)
{
if (m_hide) return;
if (m_insideTable) m_t << "\\newline\n";
else m_t << "\\par\n";
}
void LatexDocVisitor::visit(DocHorRuler *)
{
if (m_hide) return;
m_t << "\n\n";
}
void LatexDocVisitor::visit(DocStyleChange *s)
{
if (m_hide) return;
switch (s->style())
{
case DocStyleChange::Bold:
if (s->enable()) m_t << "{\\bfseries "; else m_t << "}";
break;
case DocStyleChange::Italic:
if (s->enable()) m_t << "{\\itshape "; else m_t << "}";
break;
case DocStyleChange::Code:
if (s->enable()) m_t << "{\\ttfamily "; else m_t << "}";
break;
case DocStyleChange::Subscript:
if (s->enable()) m_t << "$_{\\mbox{"; else m_t << "}}$ ";
break;
case DocStyleChange::Superscript:
if (s->enable()) m_t << "$^{\\mbox{"; else m_t << "}}$ ";
break;
case DocStyleChange::Center:
if (s->enable()) m_t << "\\begin{center}"; else m_t << "\\end{center} ";
break;
case DocStyleChange::Small:
if (s->enable()) m_t << "\n\\footnotesize "; else m_t << "\n\\normalsize ";
break;
case DocStyleChange::Preformatted:
if (s->enable())
{
m_t << "\n\\begin{DoxyPre}";
m_insidePre=TRUE;
}
else
{
m_insidePre=FALSE;
m_t << "\\end{DoxyPre}\n";
}
break;
case DocStyleChange::Div: /* HTML only */ break;
case DocStyleChange::Span: /* HTML only */ break;
}
}
void LatexDocVisitor::visit(DocVerbatim *s)
{
if (m_hide) return;
QCString lang = m_langExt;
if (!s->language().isEmpty()) // explicit language setting
{
lang = s->language();
}
switch(s->type())
{
case DocVerbatim::Code:
{
m_t << "\n\\begin{DoxyCode}\n";
Doxygen::parserManager->getParser(lang)
->parseCode(m_ci,s->context(),s->text(),
s->isExample(),s->exampleFile());
m_t << "\\end{DoxyCode}\n";
}
break;
case DocVerbatim::Verbatim:
m_t << "\\begin{DoxyVerb}";
m_t << s->text();
m_t << "\\end{DoxyVerb}\n";
break;
case DocVerbatim::HtmlOnly:
case DocVerbatim::XmlOnly:
case DocVerbatim::ManOnly:
case DocVerbatim::RtfOnly:
/* nothing */
break;
case DocVerbatim::LatexOnly:
m_t << s->text();
break;
case DocVerbatim::Dot:
{
static int dotindex = 1;
QCString fileName(4096);
fileName.sprintf("%s%d%s",
(Config_getString("LATEX_OUTPUT")+"/inline_dotgraph_").data(),
dotindex++,
".dot"
);
QFile file(fileName);
if (!file.open(IO_WriteOnly))
{
err("Could not open file %s for writing\n",fileName.data());
}
file.writeBlock( s->text(), s->text().length() );
file.close();
m_t << "\\begin{center}\n";
startDotFile(fileName,"","",FALSE);
endDotFile(FALSE);
m_t << "\\end{center}\n";
if (Config_getBool("DOT_CLEANUP")) file.remove();
}
break;
case DocVerbatim::Msc:
{
static int mscindex = 1;
QCString baseName(4096);
baseName.sprintf("%s%d",
(Config_getString("LATEX_OUTPUT")+"/inline_mscgraph_").data(),
mscindex++
);
QFile file(baseName+".msc");
if (!file.open(IO_WriteOnly))
{
err("Could not open file %s.msc for writing\n",baseName.data());
}
QCString text = "msc {";
text+=s->text();
text+="}";
file.writeBlock( text, text.length() );
file.close();
m_t << "\\begin{center}\n";
writeMscFile(baseName);
m_t << "\\end{center}\n";
if (Config_getBool("DOT_CLEANUP")) file.remove();
}
break;
}
}
void LatexDocVisitor::visit(DocAnchor *anc)
{
if (m_hide) return;
m_t << "\\label{" << anc->file() << "_" << anc->anchor() << "}%" << endl;
if (!anc->file().isEmpty() && Config_getBool("PDF_HYPERLINKS"))
{
m_t << "\\hypertarget{" << anc->file() << "_" << anc->anchor()
<< "}{}%" << endl;
}
}
void LatexDocVisitor::visit(DocInclude *inc)
{
if (m_hide) return;
switch(inc->type())
{
case DocInclude::IncWithLines:
{
m_t << "\n\\begin{DoxyCodeInclude}\n";
QFileInfo cfi( inc->file() );
FileDef fd( cfi.dirPath().utf8(), cfi.fileName().utf8() );
Doxygen::parserManager->getParser(inc->extension())
->parseCode(m_ci,inc->context(),
inc->text(),
inc->isExample(),
inc->exampleFile(), &fd);
m_t << "\\end{DoxyCodeInclude}" << endl;
}
break;
case DocInclude::Include:
m_t << "\n\\begin{DoxyCodeInclude}\n";
Doxygen::parserManager->getParser(inc->extension())
->parseCode(m_ci,inc->context(),
inc->text(),inc->isExample(),
inc->exampleFile());
m_t << "\\end{DoxyCodeInclude}\n";
break;
case DocInclude::DontInclude:
break;
case DocInclude::HtmlInclude:
break;
case DocInclude::VerbInclude:
m_t << "\n\\begin{DoxyVerbInclude}\n";
m_t << inc->text();
m_t << "\\end{DoxyVerbInclude}\n";
break;
case DocInclude::Snippet:
{
m_t << "\n\\begin{DoxyCodeInclude}\n";
Doxygen::parserManager->getParser(inc->extension())
->parseCode(m_ci,
inc->context(),
extractBlock(inc->text(),inc->blockId()),
inc->isExample(),
inc->exampleFile()
);
m_t << "\\end{DoxyCodeInclude}" << endl;
}
break;
}
}
void LatexDocVisitor::visit(DocIncOperator *op)
{
//printf("DocIncOperator: type=%d first=%d, last=%d text=`%s'\n",
// op->type(),op->isFirst(),op->isLast(),op->text().data());
if (op->isFirst())
{
if (!m_hide) m_t << "\n\\begin{DoxyCodeInclude}\n";
pushEnabled();
m_hide = TRUE;
}
if (op->type()!=DocIncOperator::Skip)
{
popEnabled();
if (!m_hide)
{
Doxygen::parserManager->getParser(m_langExt)
->parseCode(m_ci,op->context(),op->text(),
op->isExample(),op->exampleFile());
}
pushEnabled();
m_hide=TRUE;
}
if (op->isLast())
{
popEnabled();
if (!m_hide) m_t << "\n\\end{DoxyCodeInclude}\n";
}
else
{
if (!m_hide) m_t << endl;
}
}
void LatexDocVisitor::visit(DocFormula *f)
{
if (m_hide) return;
m_t << f->text();
}
void LatexDocVisitor::visit(DocIndexEntry *i)
{
if (m_hide) return;
m_t << "\\index{" << escapeLabelName(i->entry()) << "@{";
escapeMakeIndexChars(i->entry());
m_t << "}}";
}
void LatexDocVisitor::visit(DocSimpleSectSep *)
{
}
void LatexDocVisitor::visit(DocCite *cite)
{
if (m_hide) return;
if (!cite->file().isEmpty())
{
//startLink(cite->ref(),cite->file(),cite->anchor());
QCString anchor = cite->anchor();
anchor = anchor.mid(CiteConsts::anchorPrefix.length()); // strip prefix
m_t << "\\cite{" << anchor << "}";
}
else
{
m_t << "{\\bfseries [";
filter(cite->text());
m_t << "]}";
}
}
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void LatexDocVisitor::visitPre(DocAutoList *l)
{
if (m_hide) return;
if (l->isEnumList())
{
m_t << "\n\\begin{DoxyEnumerate}";
}
else
{
m_t << "\n\\begin{DoxyItemize}";
}
}
void LatexDocVisitor::visitPost(DocAutoList *l)
{
if (m_hide) return;
if (l->isEnumList())
{
m_t << "\n\\end{DoxyEnumerate}";
}
else
{
m_t << "\n\\end{DoxyItemize}";
}
}
void LatexDocVisitor::visitPre(DocAutoListItem *)
{
if (m_hide) return;
m_t << "\n\\item ";
}
void LatexDocVisitor::visitPost(DocAutoListItem *)
{
}
void LatexDocVisitor::visitPre(DocPara *)
{
}
void LatexDocVisitor::visitPost(DocPara *p)
{
if (m_hide) return;
if (!p->isLast() && // omit <p> for last paragraph
!(p->parent() && // and for parameter sections
p->parent()->kind()==DocNode::Kind_ParamSect
)
) m_t << endl << endl;
}
void LatexDocVisitor::visitPre(DocRoot *)
{
}
void LatexDocVisitor::visitPost(DocRoot *)
{
}
void LatexDocVisitor::visitPre(DocSimpleSect *s)
{
if (m_hide) return;
switch(s->type())
{
case DocSimpleSect::See:
m_t << "\\begin{DoxySeeAlso}{";
filter(theTranslator->trSeeAlso());
break;
case DocSimpleSect::Return:
m_t << "\\begin{DoxyReturn}{";
filter(theTranslator->trReturns());
break;
case DocSimpleSect::Author:
m_t << "\\begin{DoxyAuthor}{";
filter(theTranslator->trAuthor(TRUE,TRUE));
break;
case DocSimpleSect::Authors:
m_t << "\\begin{DoxyAuthor}{";
filter(theTranslator->trAuthor(TRUE,FALSE));
break;
case DocSimpleSect::Version:
m_t << "\\begin{DoxyVersion}{";
filter(theTranslator->trVersion());
break;
case DocSimpleSect::Since:
m_t << "\\begin{DoxySince}{";
filter(theTranslator->trSince());
break;
case DocSimpleSect::Date:
m_t << "\\begin{DoxyDate}{";
filter(theTranslator->trDate());
break;
case DocSimpleSect::Note:
m_t << "\\begin{DoxyNote}{";
filter(theTranslator->trNote());
break;
case DocSimpleSect::Warning:
m_t << "\\begin{DoxyWarning}{";
filter(theTranslator->trWarning());
break;
case DocSimpleSect::Pre:
m_t << "\\begin{DoxyPrecond}{";
filter(theTranslator->trPrecondition());
break;
case DocSimpleSect::Post:
m_t << "\\begin{DoxyPostcond}{";
filter(theTranslator->trPostcondition());
break;
case DocSimpleSect::Copyright:
m_t << "\\begin{DoxyCopyright}{";
filter(theTranslator->trCopyright());
break;
case DocSimpleSect::Invar:
m_t << "\\begin{DoxyInvariant}{";
filter(theTranslator->trInvariant());
break;
case DocSimpleSect::Remark:
m_t << "\\begin{DoxyRemark}{";
filter(theTranslator->trRemarks());
break;
case DocSimpleSect::Attention:
m_t << "\\begin{DoxyAttention}{";
filter(theTranslator->trAttention());
break;
case DocSimpleSect::User:
m_t << "\\begin{DoxyParagraph}{";
break;
case DocSimpleSect::Rcs:
m_t << "\\begin{DoxyParagraph}{";
break;
case DocSimpleSect::Unknown: break;
}
// special case 1: user defined title
if (s->type()!=DocSimpleSect::User && s->type()!=DocSimpleSect::Rcs)
{
m_t << "}\n";
}
else
{
m_insideItem=TRUE;
}
}
void LatexDocVisitor::visitPost(DocSimpleSect *s)
{
if (m_hide) return;
switch(s->type())
{
case DocSimpleSect::See:
m_t << "\n\\end{DoxySeeAlso}\n";
break;
case DocSimpleSect::Return:
m_t << "\n\\end{DoxyReturn}\n";
break;
case DocSimpleSect::Author:
m_t << "\n\\end{DoxyAuthor}\n";
break;
case DocSimpleSect::Authors:
m_t << "\n\\end{DoxyAuthor}\n";
break;
case DocSimpleSect::Version:
m_t << "\n\\end{DoxyVersion}\n";
break;
case DocSimpleSect::Since:
m_t << "\n\\end{DoxySince}\n";
break;
case DocSimpleSect::Date:
m_t << "\n\\end{DoxyDate}\n";
break;
case DocSimpleSect::Note:
m_t << "\n\\end{DoxyNote}\n";
break;
case DocSimpleSect::Warning:
m_t << "\n\\end{DoxyWarning}\n";
break;
case DocSimpleSect::Pre:
m_t << "\n\\end{DoxyPrecond}\n";
break;
case DocSimpleSect::Post:
m_t << "\n\\end{DoxyPostcond}\n";
break;
case DocSimpleSect::Copyright:
m_t << "\n\\end{DoxyCopyright}\n";
break;
case DocSimpleSect::Invar:
m_t << "\n\\end{DoxyInvariant}\n";
break;
case DocSimpleSect::Remark:
m_t << "\n\\end{DoxyRemark}\n";
break;
case DocSimpleSect::Attention:
m_t << "\n\\end{DoxyAttention}\n";
break;
case DocSimpleSect::User:
m_t << "\n\\end{DoxyParagraph}\n";
break;
case DocSimpleSect::Rcs:
m_t << "\n\\end{DoxyParagraph}\n";
break;
default:
break;
}
}
void LatexDocVisitor::visitPre(DocTitle *)
{
}
void LatexDocVisitor::visitPost(DocTitle *)
{
if (m_hide) return;
m_insideItem=FALSE;
m_t << "}\n";
}
void LatexDocVisitor::visitPre(DocSimpleList *)
{
if (m_hide) return;
m_t << "\\begin{DoxyItemize}" << endl;
}
void LatexDocVisitor::visitPost(DocSimpleList *)
{
if (m_hide) return;
m_t << "\\end{DoxyItemize}" << endl;
}
void LatexDocVisitor::visitPre(DocSimpleListItem *)
{
if (m_hide) return;
m_t << "\\item ";
}
void LatexDocVisitor::visitPost(DocSimpleListItem *)
{
}
void LatexDocVisitor::visitPre(DocSection *s)
{
if (m_hide) return;
if (Config_getBool("PDF_HYPERLINKS"))
{
m_t << "\\hypertarget{" << s->file() << "_" << s->anchor() << "}{}";
}
m_t << "\\" << getSectionName(s->level()) << "{";
filter(convertCharEntitiesToUTF8(s->title().data()));
m_t << "}\\label{" << s->file() << "_" << s->anchor() << "}" << endl;
}
void LatexDocVisitor::visitPost(DocSection *)
{
}
void LatexDocVisitor::visitPre(DocHtmlList *s)
{
if (m_hide) return;
if (s->type()==DocHtmlList::Ordered)
m_t << "\n\\begin{DoxyEnumerate}";
else
m_t << "\n\\begin{DoxyItemize}";
}
void LatexDocVisitor::visitPost(DocHtmlList *s)
{
if (m_hide) return;
if (s->type()==DocHtmlList::Ordered)
m_t << "\n\\end{DoxyEnumerate}";
else
m_t << "\n\\end{DoxyItemize}";
}
void LatexDocVisitor::visitPre(DocHtmlListItem *)
{
if (m_hide) return;
m_t << "\n\\item ";
}
void LatexDocVisitor::visitPost(DocHtmlListItem *)
{
}
//void LatexDocVisitor::visitPre(DocHtmlPre *)
//{
// m_t << "\\small\\begin{alltt}";
// m_insidePre=TRUE;
//}
//void LatexDocVisitor::visitPost(DocHtmlPre *)
//{
// m_insidePre=FALSE;
// m_t << "\\end{alltt}\\normalsize " << endl;
//}
void LatexDocVisitor::visitPre(DocHtmlDescList *dl)
{
if (m_hide) return;
QCString val = dl->attribs().find("class");
if (val=="reflist")
{
m_t << "\n\\begin{DoxyRefList}";
}
else
{
m_t << "\n\\begin{DoxyDescription}";
}
}
void LatexDocVisitor::visitPost(DocHtmlDescList *dl)
{
if (m_hide) return;
QCString val = dl->attribs().find("class");
if (val=="reflist")
{
m_t << "\n\\end{DoxyRefList}";
}
else
{
m_t << "\n\\end{DoxyDescription}";
}
}
void LatexDocVisitor::visitPre(DocHtmlDescTitle *)
{
if (m_hide) return;
m_t << "\n\\item[";
m_insideItem=TRUE;
}
void LatexDocVisitor::visitPost(DocHtmlDescTitle *)
{
if (m_hide) return;
m_insideItem=FALSE;
m_t << "]";
}
void LatexDocVisitor::visitPre(DocHtmlDescData *)
{
}
void LatexDocVisitor::visitPost(DocHtmlDescData *)
{
}
void LatexDocVisitor::visitPre(DocHtmlTable *t)
{
m_rowSpans.clear();
m_insideTable=TRUE;
if (m_hide) return;
if (t->hasCaption())
{
m_t << "\\begin{table}[h]";
}
m_t << "\\begin{TabularC}{" << t->numColumns() << "}\n";
m_numCols = t->numColumns();
m_t << "\\hline\n";
}
void LatexDocVisitor::visitPost(DocHtmlTable *t)
{
m_insideTable=FALSE;
if (m_hide) return;
if (t->hasCaption())
{
m_t << "\\end{table}\n";
}
else
{
m_t << "\\end{TabularC}\n";
}
}
void LatexDocVisitor::visitPre(DocHtmlCaption *)
{
if (m_hide) return;
m_t << "\\end{TabularC}\n\\centering\n\\caption{";
}
void LatexDocVisitor::visitPost(DocHtmlCaption *)
{
if (m_hide) return;
m_t << "}\n";
}
void LatexDocVisitor::visitPre(DocHtmlRow *r)
{
m_currentColumn = 0;
if (r->isHeading()) m_t << "\\rowcolor{lightgray}";
}
void LatexDocVisitor::visitPost(DocHtmlRow *row)
{
if (m_hide) return;
int c=m_currentColumn;
while (c<=m_numCols) // end of row while inside a row span?
{
uint i;
for (i=0;i<m_rowSpans.count();i++)
{
ActiveRowSpan *span = m_rowSpans.at(i);
//printf(" founc row span: column=%d rs=%d cs=%d rowIdx=%d cell->rowIdx=%d\n",
// span->column, span->rowSpan,span->colSpan,row->rowIndex(),span->cell->rowIndex());
if (span->rowSpan>0 && span->column==c && // we are at a cell in a row span
row->rowIndex()>span->cell->rowIndex() // but not the row that started the span
)
{
m_t << "&";
if (span->colSpan>1) // row span is also part of a column span
{
m_t << "\\multicolumn{" << span->colSpan << "}{";
m_t << "p{(\\linewidth-\\tabcolsep*"
<< m_numCols << "-\\arrayrulewidth*"
<< row->visibleCells() << ")*"
<< span->colSpan <<"/"<< m_numCols << "}|}{}";
}
else // solitary row span
{
m_t << "\\multicolumn{1}{c|}{}";
}
}
}
c++;
}
m_t << "\\\\";
int col = 1;
uint i;
for (i=0;i<m_rowSpans.count();i++)
{
ActiveRowSpan *span = m_rowSpans.at(i);
if (span->rowSpan>0) span->rowSpan--;
if (span->rowSpan<=0)
{
// inactive span
}
else if (span->column>col)
{
m_t << "\\cline{" << col << "-" << (span->column-1) << "}";
col = span->column+span->colSpan;
}
else
{
col = span->column+span->colSpan;
}
}
if (col <= m_numCols)
{
m_t << "\\cline{" << col << "-" << m_numCols << "}";
}
m_t << "\n";
}
void LatexDocVisitor::visitPre(DocHtmlCell *c)
{
if (m_hide) return;
DocHtmlRow *row = 0;
if (c->parent() && c->parent()->kind()==DocNode::Kind_HtmlRow)
{
row = (DocHtmlRow*)c->parent();
}
m_currentColumn++;
//Skip columns that span from above.
uint i;
for (i=0;i<m_rowSpans.count();i++)
{
ActiveRowSpan *span = m_rowSpans.at(i);
if (span->rowSpan>0 && span->column==m_currentColumn)
{
if (row && span->colSpan>1)
{
m_t << "\\multicolumn{" << span->colSpan << "}{";
if (m_currentColumn /*c->columnIndex()*/==1) // add extra | for first column
{
m_t << "|";
}
m_t << "p{(\\linewidth-\\tabcolsep*"
<< m_numCols << "-\\arrayrulewidth*"
<< row->visibleCells() << ")*"
<< span->colSpan <<"/"<< m_numCols << "}|}{}";
m_currentColumn+=span->colSpan;
}
else
{
m_currentColumn++;
}
m_t << "&";
}
}
#if 0
QMap<int, int>::Iterator it = m_rowspanIndices.find(m_currentColumn);
if (it!=m_rowspanIndices.end() && it.data()>0)
{
m_t << "&";
m_currentColumn++;
it++;
}
#endif
int cs = c->colSpan();
if (cs>1 && row)
{
m_inColspan = TRUE;
m_t << "\\multicolumn{" << cs << "}{";
if (c->columnIndex()==1) // add extra | for first column
{
m_t << "|";
}
m_t << "p{(\\linewidth-\\tabcolsep*"
<< m_numCols << "-\\arrayrulewidth*"
<< row->visibleCells() << ")*"
<< cs <<"/"<< m_numCols << "}|}{";
if (c->isHeading()) m_t << "\\cellcolor{lightgray}";
}
int rs = c->rowSpan();
if (rs>0)
{
m_inRowspan = TRUE;
//m_rowspanIndices[m_currentColumn] = rs;
m_rowSpans.append(new ActiveRowSpan(c,rs,cs,m_currentColumn));
m_t << "\\multirow{" << rs << "}{\\linewidth}{";
}
int a = c->alignment();
if (a==DocHtmlCell::Center)
{
m_t << "\\PBS\\centering ";
}
else if (a==DocHtmlCell::Right)
{
m_t << "\\PBS\\raggedleft ";
}
if (c->isHeading())
{
m_t << "{\\bf ";
}
if (cs>1)
{
m_currentColumn+=cs-1;
}
}
void LatexDocVisitor::visitPost(DocHtmlCell *c)
{
if (m_hide) return;
if (c->isHeading())
{
m_t << "}";
}
if (m_inRowspan)
{
m_inRowspan = FALSE;
m_t << "}";
}
if (m_inColspan)
{
m_inColspan = FALSE;
m_t << "}";
}
if (!c->isLast()) m_t << "&";
}
void LatexDocVisitor::visitPre(DocInternal *)
{
if (m_hide) return;
//m_t << "\\begin{DoxyInternal}{";
//filter(theTranslator->trForInternalUseOnly());
//m_t << "}\n";
}
void LatexDocVisitor::visitPost(DocInternal *)
{
if (m_hide) return;
//m_t << "\\end{DoxyInternal}" << endl;
}
void LatexDocVisitor::visitPre(DocHRef *href)
{
if (m_hide) return;
if (Config_getBool("PDF_HYPERLINKS"))
{
m_t << "\\href{";
m_t << href->url();
m_t << "}";
}
m_t << "{\\tt ";
}
void LatexDocVisitor::visitPost(DocHRef *)
{
if (m_hide) return;
m_t << "}";
}
void LatexDocVisitor::visitPre(DocHtmlHeader *header)
{
if (m_hide) return;
m_t << "\\" << getSectionName(header->level()) << "*{";
}
void LatexDocVisitor::visitPost(DocHtmlHeader *)
{
if (m_hide) return;
m_t << "}";
}
void LatexDocVisitor::visitPre(DocImage *img)
{
if (img->type()==DocImage::Latex)
{
if (m_hide) return;
if (img->hasCaption())
{
m_t << "\n\\begin{DoxyImage}\n";
}
else
{
m_t << "\n\\begin{DoxyImageNoCaption}\n"
" \\mbox{";
}
QCString gfxName = img->name();
if (gfxName.right(4)==".eps" || gfxName.right(4)==".pdf")
{
gfxName=gfxName.left(gfxName.length()-4);
}
m_t << "\\includegraphics";
if (!img->width().isEmpty())
{
m_t << "[width=" << img->width() << "]";
}
else if (!img->height().isEmpty())
{
m_t << "[height=" << img->height() << "]";
}
m_t << "{" << gfxName << "}";
if (img->hasCaption())
{
m_t << "\n\\caption{";
}
}
else // other format -> skip
{
pushEnabled();
m_hide=TRUE;
}
}
void LatexDocVisitor::visitPost(DocImage *img)
{
if (img->type()==DocImage::Latex)
{
if (m_hide) return;
m_t << "}\n"; // end mbox or caption
if (img->hasCaption())
{
m_t << "\\end{DoxyImage}\n";
}
else{
m_t << "\\end{DoxyImageNoCaption}\n";
}
}
else // other format
{
popEnabled();
}
}
void LatexDocVisitor::visitPre(DocDotFile *df)
{
if (m_hide) return;
startDotFile(df->file(),df->width(),df->height(),df->hasCaption());
}
void LatexDocVisitor::visitPost(DocDotFile *df)
{
if (m_hide) return;
endDotFile(df->hasCaption());
}
void LatexDocVisitor::visitPre(DocMscFile *df)
{
if (m_hide) return;
startMscFile(df->file(),df->width(),df->height(),df->hasCaption());
}
void LatexDocVisitor::visitPost(DocMscFile *df)
{
if (m_hide) return;
endMscFile(df->hasCaption());
}
void LatexDocVisitor::visitPre(DocLink *lnk)
{
if (m_hide) return;
startLink(lnk->ref(),lnk->file(),lnk->anchor());
}
void LatexDocVisitor::visitPost(DocLink *lnk)
{
if (m_hide) return;
endLink(lnk->ref(),lnk->file(),lnk->anchor());
}
void LatexDocVisitor::visitPre(DocRef *ref)
{
if (m_hide) return;
// when ref->isSubPage()==TRUE we use ref->file() for HTML and
// ref->anchor() for LaTeX/RTF
if (ref->isSubPage())
{
startLink(ref->ref(),0,ref->anchor());
}
else
{
if (!ref->file().isEmpty()) startLink(ref->ref(),ref->file(),ref->anchor());
}
if (!ref->hasLinkText()) filter(ref->targetTitle());
}
void LatexDocVisitor::visitPost(DocRef *ref)
{
if (m_hide) return;
if (ref->isSubPage())
{
endLink(ref->ref(),0,ref->anchor());
}
else
{
if (!ref->file().isEmpty()) endLink(ref->ref(),ref->file(),ref->anchor());
}
}
void LatexDocVisitor::visitPre(DocSecRefItem *)
{
if (m_hide) return;
m_t << "\\item \\contentsline{section}{";
}
void LatexDocVisitor::visitPost(DocSecRefItem *ref)
{
if (m_hide) return;
m_t << "}{\\ref{" << ref->file() << "_" << ref->anchor() << "}}{}" << endl;
}
void LatexDocVisitor::visitPre(DocSecRefList *)
{
if (m_hide) return;
m_t << "\\footnotesize" << endl;
m_t << "\\begin{multicols}{2}" << endl;
m_t << "\\begin{DoxyCompactList}" << endl;
}
void LatexDocVisitor::visitPost(DocSecRefList *)
{
if (m_hide) return;
m_t << "\\end{DoxyCompactList}" << endl;
m_t << "\\end{multicols}" << endl;
m_t << "\\normalsize" << endl;
}
void LatexDocVisitor::visitPre(DocParamSect *s)
{
if (m_hide) return;
bool hasInOutSpecs = s->hasInOutSpecifier();
bool hasTypeSpecs = s->hasTypeSpecifier();
switch(s->type())
{
case DocParamSect::Param:
m_t << "\n\\begin{DoxyParams}";
if (hasInOutSpecs && hasTypeSpecs) m_t << "[2]"; // 2 extra cols
else if (hasInOutSpecs || hasTypeSpecs) m_t << "[1]"; // 1 extra col
m_t << "{";
filter(theTranslator->trParameters());
break;
case DocParamSect::RetVal:
m_t << "\n\\begin{DoxyRetVals}{";
filter(theTranslator->trReturnValues());
break;
case DocParamSect::Exception:
m_t << "\n\\begin{DoxyExceptions}{";
filter(theTranslator->trExceptions());
break;
case DocParamSect::TemplateParam:
/* TODO: add this
filter(theTranslator->trTemplateParam()); break;
*/
m_t << "\n\\begin{DoxyTemplParams}{";
filter("Template Parameters");
break;
default:
ASSERT(0);
}
m_t << "}\n";
}
void LatexDocVisitor::visitPost(DocParamSect *s)
{
if (m_hide) return;
switch(s->type())
{
case DocParamSect::Param:
m_t << "\\end{DoxyParams}\n";
break;
case DocParamSect::RetVal:
m_t << "\\end{DoxyRetVals}\n";
break;
case DocParamSect::Exception:
m_t << "\\end{DoxyExceptions}\n";
break;
case DocParamSect::TemplateParam:
m_t << "\\end{DoxyTemplParams}\n";
break;
default:
ASSERT(0);
}
}
void LatexDocVisitor::visitPre(DocParamList *pl)
{
if (m_hide) return;
DocParamSect::Type parentType = DocParamSect::Unknown;
DocParamSect *sect = 0;
if (pl->parent() && pl->parent()->kind()==DocNode::Kind_ParamSect)
{
parentType = ((DocParamSect*)pl->parent())->type();
sect=(DocParamSect*)pl->parent();
}
bool useTable = parentType==DocParamSect::Param ||
parentType==DocParamSect::RetVal ||
parentType==DocParamSect::Exception ||
parentType==DocParamSect::TemplateParam;
if (!useTable)
{
m_t << "\\item[";
}
if (sect && sect->hasInOutSpecifier())
{
if (pl->direction()!=DocParamSect::Unspecified)
{
m_t << "\\mbox{\\tt ";
if (pl->direction()==DocParamSect::In)
{
m_t << "in";
}
else if (pl->direction()==DocParamSect::Out)
{
m_t << "out";
}
else if (pl->direction()==DocParamSect::InOut)
{
m_t << "in,out";
}
m_t << "} ";
}
if (useTable) m_t << " & ";
}
if (sect && sect->hasTypeSpecifier())
{
QListIterator<DocNode> li(pl->paramTypes());
DocNode *type;
bool first=TRUE;
for (li.toFirst();(type=li.current());++li)
{
if (!first) m_t << " | "; else first=FALSE;
if (type->kind()==DocNode::Kind_Word)
{
visit((DocWord*)type);
}
else if (type->kind()==DocNode::Kind_LinkedWord)
{
visit((DocLinkedWord*)type);
}
}
if (useTable) m_t << " & ";
}
m_t << "{\\em ";
//QStrListIterator li(pl->parameters());
//const char *s;
QListIterator<DocNode> li(pl->parameters());
DocNode *param;
bool first=TRUE;
for (li.toFirst();(param=li.current());++li)
{
if (!first) m_t << ","; else first=FALSE;
m_insideItem=TRUE;
if (param->kind()==DocNode::Kind_Word)
{
visit((DocWord*)param);
}
else if (param->kind()==DocNode::Kind_LinkedWord)
{
visit((DocLinkedWord*)param);
}
m_insideItem=FALSE;
}
m_t << "}";
if (useTable)
{
m_t << " & ";
}
else
{
m_t << "]";
}
}
void LatexDocVisitor::visitPost(DocParamList *pl)
{
if (m_hide) return;
DocParamSect::Type parentType = DocParamSect::Unknown;
if (pl->parent() && pl->parent()->kind()==DocNode::Kind_ParamSect)
{
parentType = ((DocParamSect*)pl->parent())->type();
}
bool useTable = parentType==DocParamSect::Param ||
parentType==DocParamSect::RetVal ||
parentType==DocParamSect::Exception ||
parentType==DocParamSect::TemplateParam;
if (useTable)
{
m_t << "\\\\" << endl
<< "\\hline" << endl;
}
}
void LatexDocVisitor::visitPre(DocXRefItem *x)
{
if (m_hide) return;
m_t << "\\begin{DoxyRefDesc}{";
filter(x->title());
m_t << "}" << endl;
bool anonymousEnum = x->file()=="@";
m_t << "\\item[";
if (Config_getBool("PDF_HYPERLINKS") && !anonymousEnum)
{
m_t << "\\hyperlink{" << stripPath(x->file()) << "_" << x->anchor() << "}{";
}
else
{
m_t << "{\\bf ";
}
m_insideItem=TRUE;
filter(x->title());
m_insideItem=FALSE;
m_t << "}]";
}
void LatexDocVisitor::visitPost(DocXRefItem *)
{
if (m_hide) return;
m_t << "\\end{DoxyRefDesc}" << endl;
}
void LatexDocVisitor::visitPre(DocInternalRef *ref)
{
if (m_hide) return;
startLink(0,ref->file(),ref->anchor());
}
void LatexDocVisitor::visitPost(DocInternalRef *ref)
{
if (m_hide) return;
endLink(0,ref->file(),ref->anchor());
}
void LatexDocVisitor::visitPre(DocCopy *)
{
}
void LatexDocVisitor::visitPost(DocCopy *)
{
}
void LatexDocVisitor::visitPre(DocText *)
{
}
void LatexDocVisitor::visitPost(DocText *)
{
}
void LatexDocVisitor::visitPre(DocHtmlBlockQuote *)
{
if (m_hide) return;
m_t << "\\begin{quotation}" << endl;
}
void LatexDocVisitor::visitPost(DocHtmlBlockQuote *)
{
if (m_hide) return;
m_t << "\\end{quotation}" << endl;
}
void LatexDocVisitor::filter(const char *str)
{
filterLatexString(m_t,str,m_insideTabbing,m_insidePre,m_insideItem);
}
void LatexDocVisitor::startLink(const QCString &ref,const QCString &file,const QCString &anchor)
{
if (ref.isEmpty() && Config_getBool("PDF_HYPERLINKS")) // internal PDF link
{
if (ref.isEmpty()) {
m_t << "\\hyperlink{";
if (!file.isEmpty()) m_t << stripPath(file);
if (!file.isEmpty() && !anchor.isEmpty()) m_t << "_";
if (!anchor.isEmpty()) m_t << anchor;
m_t << "}{";
}
else
{
QCString *dest;
m_t << "\\href{";
if ((dest=Doxygen::tagDestinationDict[ref])) m_t << *dest << "/";
if (!file.isEmpty()) m_t << file << Doxygen::htmlFileExtension;
if (!anchor.isEmpty()) m_t << "#" << anchor;
m_t << "}{";
}
}
else if (ref.isEmpty()) // internal non-PDF link
{
m_t << "\\doxyref{";
}
else // external link
{
m_t << "{\\bf ";
}
}
void LatexDocVisitor::endLink(const QCString &ref,const QCString &file,const QCString &anchor)
{
m_t << "}";
if (ref.isEmpty() && !Config_getBool("PDF_HYPERLINKS"))
{
m_t << "{";
filter(theTranslator->trPageAbbreviation());
m_t << "}{" << file;
if (!anchor.isEmpty()) m_t << "_" << anchor;
m_t << "}";
}
}
void LatexDocVisitor::pushEnabled()
{
m_enabled.push(new bool(m_hide));
}
void LatexDocVisitor::popEnabled()
{
bool *v=m_enabled.pop();
ASSERT(v!=0);
m_hide = *v;
delete v;
}
void LatexDocVisitor::startDotFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption
)
{
QCString baseName=fileName;
int i;
if ((i=baseName.findRev('/'))!=-1)
{
baseName=baseName.right(baseName.length()-i-1);
}
if ((i=baseName.find('.'))!=-1)
{
baseName=baseName.left(i);
}
baseName.prepend("dot_");
QCString outDir = Config_getString("LATEX_OUTPUT");
QCString name = fileName;
writeDotGraphFromFile(name,outDir,baseName,EPS);
if (hasCaption)
{
m_t << "\n\\begin{DoxyImage}\n";
}
else
{
m_t << "\n\\begin{DoxyImageNoCaption}\n"
" \\mbox{";
}
m_t << "\\includegraphics";
if (!width.isEmpty())
{
m_t << "[width=" << width << "]";
}
else if (!height.isEmpty())
{
m_t << "[height=" << height << "]";
}
else
{
m_t << "[width=\\textwidth]";
}
m_t << "{" << baseName << "}";
if (hasCaption)
{
m_t << "\n\\caption{";
}
}
void LatexDocVisitor::endDotFile(bool hasCaption)
{
if (m_hide) return;
m_t << "}\n"; // end caption or mbox
if (hasCaption)
{
m_t << "\\end{DoxyImage}\n";
}
else
{
m_t << "\\end{DoxyImageNoCaption}\n";
}
}
void LatexDocVisitor::startMscFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption
)
{
QCString baseName=fileName;
int i;
if ((i=baseName.findRev('/'))!=-1)
{
baseName=baseName.right(baseName.length()-i-1);
}
if ((i=baseName.find('.'))!=-1)
{
baseName=baseName.left(i);
}
baseName.prepend("msc_");
QCString outDir = Config_getString("LATEX_OUTPUT");
writeMscGraphFromFile(fileName,outDir,baseName,MSC_EPS);
if (hasCaption)
{
m_t << "\n\\begin{DoxyImage}\n";
}
else
{
m_t << "\n\\begin{DoxyImageNoCaption}\n"
" \\mbox{";
}
m_t << "\\includegraphics";
if (!width.isEmpty())
{
m_t << "[width=" << width << "]";
}
else if (!height.isEmpty())
{
m_t << "[height=" << height << "]";
}
else
{
m_t << "[width=\\textwidth]";
}
m_t << "{" << baseName << "}";
if (hasCaption)
{
m_t << "\n\\caption{";
}
}
void LatexDocVisitor::endMscFile(bool hasCaption)
{
if (m_hide) return;
m_t << "}\n"; // end caption or mbox
if (hasCaption)
{
m_t << "\\end{DoxyImage}\n";
}
else
{
m_t << "\\end{DoxyImageNoCaption}\n";
}
}
void LatexDocVisitor::writeMscFile(const QCString &baseName)
{
QCString shortName = baseName;
int i;
if ((i=shortName.findRev('/'))!=-1)
{
shortName=shortName.right(shortName.length()-i-1);
}
QCString outDir = Config_getString("LATEX_OUTPUT");
writeMscGraphFromFile(baseName+".msc",outDir,shortName,MSC_EPS);
m_t << "\n\\begin{DoxyImageNoCaption}"
" \\mbox{\\includegraphics";
m_t << "{" << shortName << "}";
m_t << "}\n"; // end mbox
m_t << "\\end{DoxyImageNoCaption}\n";
}
| TextusData/Mover | thirdparty/doxygen-1.8.1.2/src/latexdocvisitor.cpp | C++ | gpl-3.0 | 45,222 |
// mauIRC - The original mauIRC web frontend
// Copyright (C) 2016 Tulir Asokan
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Package ui contains UI-related functions
package ui
import (
"encoding/json"
"fmt"
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/jquery"
"maunium.net/go/mauirc-common/messages"
"maunium.net/go/mauirc/data"
"maunium.net/go/mauirc/templates"
"maunium.net/go/mauirc/util/console"
)
// GetHistory gets n messages of the history of channel @ network
func GetHistory(network, channel string, n int) {
data.MustGetChannel(network, channel).FetchingHistory = true
GetChannel(network, channel).SetHtml("<div class='loader-center-wrapper'><div class='loader'/></div>")
jquery.Ajax(map[string]interface{}{
"type": "GET",
"url": fmt.Sprintf("/history/%s/%s/?n=%d", network, js.Global.Call("encodeURIComponent", channel).String(), n),
jquery.SUCCESS: func(rawData string) {
GetChannel(network, channel).Empty()
var histData = make([]messages.Message, 0)
json.Unmarshal([]byte(rawData), &histData)
for i := len(histData) - 1; i >= 0; i-- {
Receive(histData[i], false)
}
chanData := data.MustGetChannel(network, channel)
Loop:
for {
select {
case obj := <-chanData.MessageCache:
Receive(obj, true)
default:
break Loop
}
}
chanData.FetchingHistory = false
chanData.HistoryFetched = true
ScrollDown()
},
jquery.ERROR: func(info map[string]interface{}, textStatus, errorThrown string) {
console.Error("Failed to fetch history: HTTP", info["status"])
console.Error(info)
data.MustGetChannel(network, channel).FetchingHistory = false
if len(GetActiveNetwork()) == 0 || len(GetActiveChannel()) == 0 {
return
}
templates.AppendObj("error", GetActiveChannelObj(), fmt.Sprintln("Failed to fetch history:", textStatus, errorThrown))
ScrollDown()
},
})
}
| tulir/mauirc | ui/history.go | GO | gpl-3.0 | 2,486 |
package com.bourke.finch;
import com.bourke.finch.common.TwitterTask;
public class ConnectionsTimelineFragment extends BaseTimelineFragment {
private static final String TAG = "Finch/ConnectionsTimelineFragment";
public ConnectionsTimelineFragment() {
super(TwitterTask.GET_MENTIONS);
}
@Override
public void onResume() {
super.onResume();
refresh();
}
public void setupActionMode() {
// TODO
}
}
| brk3/finch | src/com/bourke/finch/fragments/ConnectionsTimelineFragment.java | Java | gpl-3.0 | 467 |
package org.jumpmind.metl.core.ui.views.custom;
import com.vaadin.server.Resource;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.IDatabasePlatform;
import org.jumpmind.properties.TypedProperties;
import org.jumpmind.vaadin.ui.sqlexplorer.DbTree;
import org.jumpmind.vaadin.ui.sqlexplorer.IDb;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CustomDbTreeNode implements Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected String description;
protected String type;
protected Resource icon;
protected TypedProperties properties = new TypedProperties();
protected CustomDbTreeNode parent;
protected List<CustomDbTreeNode> children = new ArrayList<CustomDbTreeNode>();
protected CustomDbTree dbTree;
public CustomDbTreeNode(CustomDbTree dbTree, String name, String type, Resource icon,
CustomDbTreeNode parent) {
this.name = name;
this.type = type;
this.parent = parent;
this.icon = icon;
this.dbTree = dbTree;
}
public CustomDbTreeNode() {
}
public void setParent(CustomDbTreeNode parent) {
this.parent = parent;
}
public CustomDbTreeNode getParent() {
return parent;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return name;
}
public boolean hasChildren() {
return children.size() > 0;
}
public List<CustomDbTreeNode> getChildren() {
return children;
}
public void setChildren(List<CustomDbTreeNode> children) {
this.children = children;
}
public CustomDbTreeNode find(CustomDbTreeNode node) {
if (this.equals(node)) {
return this;
} else if (children != null && children.size() > 0) {
Iterator<CustomDbTreeNode> it = children.iterator();
while (it.hasNext()) {
CustomDbTreeNode child = (CustomDbTreeNode) it.next();
if (child.equals(node)) {
return child;
}
}
for (CustomDbTreeNode child : children) {
CustomDbTreeNode target = child.find(node);
if (target != null) {
return target;
}
}
}
return null;
}
protected Table getTableFor() {
IDb db = dbTree.getDbForNode(this);
IDatabasePlatform platform = db.getPlatform();
TypedProperties nodeProperties = getProperties();
return platform.getTableFromCache(
nodeProperties.get(DbTree.PROPERTY_CATALOG_NAME),
nodeProperties.get(DbTree.PROPERTY_SCHEMA_NAME), name, false);
}
public boolean delete(CustomDbTreeNode node) {
if (children != null && children.size() > 0) {
Iterator<CustomDbTreeNode> it = children.iterator();
while (it.hasNext()) {
CustomDbTreeNode child = (CustomDbTreeNode) it.next();
if (child.equals(node)) {
it.remove();
return true;
}
}
for (CustomDbTreeNode child : children) {
if (child.delete(node)) {
return true;
}
}
}
return false;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setIcon(Resource icon) {
this.icon = icon;
}
public Resource getIcon() {
return icon;
}
public List<String> findTreeNodeNamesOfType(String type) {
List<String> names = new ArrayList<String>();
if (this.getType().equals(type)) {
names.add(getName());
}
findTreeNodeNamesOfType(type, getChildren(), names);
return names;
}
public void findTreeNodeNamesOfType(String type,
List<CustomDbTreeNode> treeNodes, List<String> names) {
for (CustomDbTreeNode treeNode : treeNodes) {
if (treeNode.getType().equals(type)) {
names.add(treeNode.getName());
}
findTreeNodeNamesOfType(type, treeNode.getChildren(), names);
}
}
public void setProperties(TypedProperties properties) {
this.properties = properties;
}
public TypedProperties getProperties() {
return properties;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomDbTreeNode other = (CustomDbTreeNode) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (parent == null) {
if (other.parent != null) {
return false;
}
} else if (!parent.equals(other.parent)) {
return false;
}
return true;
}
} | awol2010ex/metl | metl-patch-db2-97/src/main/java/org/jumpmind/metl/core/ui/views/custom/CustomDbTreeNode.java | Java | gpl-3.0 | 6,297 |
<?php
/**
*
* @package install
* @version $Id: functions_phpbb20.php,v 1.56 2007/07/27 17:33:15 acydburn Exp $
* @copyright (c) 2006 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* Helper functions for phpBB 2.0.x to phpBB 3.0.x conversion
*/
/**
* Set forum flags - only prune old polls by default
*/
function phpbb_forum_flags()
{
// Set forum flags
$forum_flags = 0;
// FORUM_FLAG_LINK_TRACK
$forum_flags += 0;
// FORUM_FLAG_PRUNE_POLL
$forum_flags += FORUM_FLAG_PRUNE_POLL;
// FORUM_FLAG_PRUNE_ANNOUNCE
$forum_flags += 0;
// FORUM_FLAG_PRUNE_STICKY
$forum_flags += 0;
// FORUM_FLAG_ACTIVE_TOPICS
$forum_flags += 0;
// FORUM_FLAG_POST_REVIEW
$forum_flags += FORUM_FLAG_POST_REVIEW;
return $forum_flags;
}
/**
* Insert/Convert forums
*/
function phpbb_insert_forums()
{
global $db, $src_db, $same_db, $convert, $user, $config;
$db->sql_query($convert->truncate_statement . FORUMS_TABLE);
// Determine the highest id used within the old forums table (we add the categories after the forum ids)
$sql = 'SELECT MAX(fid) AS max_forum_id
FROM ' . $convert->src_table_prefix . 'forums';
$result = $src_db->sql_query($sql);
$max_forum_id = (int) $src_db->sql_fetchfield('max_forum_id');
$src_db->sql_freeresult($result);
$max_forum_id++;
// pruning disabled globally?
$prune_enabled = 0;
// Insert categories
$sql = 'SELECT fid as cat_id, name as cat_title
FROM '. $convert->src_table_prefix . 'forums WHERE fup=0 ORDER BY cat_id';
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'binary'");
}
$result = $src_db->sql_query($sql);
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'utf8'");
}
switch ($db->sql_layer)
{
case 'mssql':
case 'mssql_odbc':
$db->sql_query('SET IDENTITY_INSERT ' . FORUMS_TABLE . ' ON');
break;
}
$cats_added = array();
while ($row = $src_db->sql_fetchrow($result))
{
$sql_ary = array(
'forum_id' => (int) $row['cat_id'],
'forum_name' => ($row['cat_title']) ? htmlspecialchars(phpbb_set_default_encoding($row['cat_title']), ENT_COMPAT, 'UTF-8') : $user->lang['CATEGORY'],
'parent_id' => 0,
'forum_parents' => '',
'forum_desc' => '',
'forum_type' => FORUM_CAT,
'forum_status' => ITEM_UNLOCKED,
'forum_rules' => '',
);
$sql = 'SELECT MAX(right_id) AS right_id
FROM ' . FORUMS_TABLE;
$_result = $db->sql_query($sql);
$cat_row = $db->sql_fetchrow($_result);
$db->sql_freeresult($_result);
$sql_ary['left_id'] = (int) ($cat_row['right_id'] + 1);
$sql_ary['right_id'] = (int) ($cat_row['right_id'] + 2);
$sql = 'INSERT INTO ' . FORUMS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
$db->sql_query($sql);
$cats_added[$row['cat_id']] = $max_forum_id;
$max_forum_id++;
}
$src_db->sql_freeresult($result);
// Now insert the forums
$sql='SELECT * FROM '. $convert->src_table_prefix . 'forums WHERE fup <> 0 ORDER BY type, fid';
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'binary'");
}
$result = $src_db->sql_query($sql);
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'utf8'");
}
while ($row = $src_db->sql_fetchrow($result))
{
// Define the new forums sql ary
$sql_ary = array(
'forum_id' => (int) $row['fid'],
'forum_name' => htmlspecialchars(phpbb_set_default_encoding($row['name']), ENT_COMPAT, 'UTF-8'),
'parent_id' => (int) $row['fup'],
'forum_parents' => '',
'forum_desc' => htmlspecialchars(phpbb_set_default_encoding(''), ENT_COMPAT, 'UTF-8'),
'forum_type' => FORUM_POST,
'forum_status' => 0,
'enable_prune' => 0,
'prune_next' => 0,
'prune_days' => 0,
'prune_viewed' => 0,
'prune_freq' => 0,
'forum_flags' => phpbb_forum_flags(),
// Default values
'forum_desc_bitfield' => '',
'forum_desc_options' => 7,
'forum_desc_uid' => '',
'forum_link' => '',
'forum_password' => '',
'forum_style' => 0,
'forum_image' => '',
'forum_rules' => '',
'forum_rules_link' => '',
'forum_rules_bitfield' => '',
'forum_rules_options' => 7,
'forum_rules_uid' => '',
'forum_topics_per_page' => 0,
'forum_posts' => 0,
'forum_topics' => 0,
'forum_topics_real' => 0,
'forum_last_post_id' => 0,
'forum_last_poster_id' => 0,
'forum_last_post_subject' => '',
'forum_last_post_time' => 0,
'forum_last_poster_name' => '',
'forum_last_poster_colour' => '',
'display_on_index' => 1,
'enable_indexing' => 1,
'enable_icons' => 0,
);
// Now add the forums with proper left/right ids
$sql = 'SELECT left_id, right_id
FROM ' . FORUMS_TABLE . '
WHERE forum_id = ' . $row['fup'];
$_result = $db->sql_query($sql);
$cat_row = $db->sql_fetchrow($_result);
$db->sql_freeresult($_result);
$sql = 'UPDATE ' . FORUMS_TABLE . '
SET left_id = left_id + 2, right_id = right_id + 2
WHERE left_id > ' . $cat_row['right_id'];
$db->sql_query($sql);
$sql = 'UPDATE ' . FORUMS_TABLE . '
SET right_id = right_id + 2
WHERE ' . $cat_row['left_id'] . ' BETWEEN left_id AND right_id';
$db->sql_query($sql);
$sql_ary['left_id'] = (int) $cat_row['right_id'];
$sql_ary['right_id'] = (int) ($cat_row['right_id'] + 1);
$sql = 'INSERT INTO ' . FORUMS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
$db->sql_query($sql);
}
$src_db->sql_freeresult($result);
switch ($db->sql_layer)
{
case 'postgres':
$db->sql_query("SELECT SETVAL('" . FORUMS_TABLE . "_seq',(select case when max(forum_id)>0 then max(forum_id)+1 else 1 end from " . FORUMS_TABLE . '));');
break;
case 'mssql':
case 'mssql_odbc':
$db->sql_query('SET IDENTITY_INSERT ' . FORUMS_TABLE . ' OFF');
break;
case 'oracle':
$result = $db->sql_query('SELECT MAX(forum_id) as max_id FROM ' . FORUMS_TABLE);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$largest_id = (int) $row['max_id'];
if ($largest_id)
{
$db->sql_query('DROP SEQUENCE ' . FORUMS_TABLE . '_seq');
$db->sql_query('CREATE SEQUENCE ' . FORUMS_TABLE . '_seq START WITH ' . ($largest_id + 1));
}
break;
}
}
/**
* Function for recoding text with the default language
*
* @param string $text text to recode to utf8
* @param bool $grab_user_lang if set to true the function tries to use $convert_row['user_lang'] (and falls back to $convert_row['poster_id']) instead of the boards default language
*/
function dz_set_encoding($text, $grab_user_lang = true)
{
//不知道是否dz有各种不用的编码版本,本次拿到的dz数据库为gbk,所以此处需要使用gbk。可以考虑让用户自己填写编码,或者想办法判断出资料的编码 add by fan
return utf8_recode($text, 'gbk');
//return utf8_recode($text, 'UTF-8');
}
/**
* Same as dz_set_encoding, but forcing boards default language
*/
function phpbb_set_default_encoding($text)
{
return dz_set_encoding($text, false);
}
/**
* Convert Birthday from Birthday MOD to phpBB Format
*/
function phpbb_get_birthday($birthday = '')
{
if (defined('MOD_BIRTHDAY_TERRA'))
{
$birthday = (string) $birthday;
// stored as month, day, year
if (!$birthday)
{
return ' 0- 0- 0';
}
// We use the original mod code to retrieve the birthday (not ideal)
preg_match('/(..)(..)(....)/', sprintf('%08d', $birthday), $birthday_parts);
$month = $birthday_parts[1];
$day = $birthday_parts[2];
$year = $birthday_parts[3];
return sprintf('%2d-%2d-%4d', $day, $month, $year);
}
else
{
$birthday = (int) $birthday;
if (!$birthday || $birthday == 999999 || $birthday < 0)
{
return ' 0- 0- 0';
}
// The birthday mod from niels is using this code to transform to day/month/year
return gmdate('d-m-Y', $birthday * 86400 + 1);
}
}
/**
* Return correct user id value
* Everyone's id will be one higher to allow the guest/anonymous user to have a positive id as well
*/
function phpbb_user_id($user_id)
{
global $config;
// Increment user id if the old forum is having a user with the id 1
if (!isset($config['increment_user_id']))
{
global $src_db, $same_db, $convert;
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'binary'");
}
// Now let us set a temporary config variable for user id incrementing
$sql = "SELECT uid
FROM {$convert->src_table_prefix}members
WHERE uid = 1";
$result = $src_db->sql_query($sql);
$id = (int) $src_db->sql_fetchfield('uid');
$src_db->sql_freeresult($result);
// Try to get the maximum user id possible...
$sql = "SELECT MAX(uid) AS max_user_id
FROM {$convert->src_table_prefix}members";
$result = $src_db->sql_query($sql);
$max_id = (int) $src_db->sql_fetchfield('max_user_id');
$src_db->sql_freeresult($result);
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'utf8'");
}
// If there is a user id 1, we need to increment user ids. :/
if ($id === 1)
{
set_config('increment_user_id', ($max_id + 1), true);
$config['increment_user_id'] = $max_id + 1;
}
else
{
set_config('increment_user_id', 0, true);
$config['increment_user_id'] = 0;
}
}
// If the old user id is 0 in Discuz6 it is the anonymous user...
if ($user_id == 0)
{
return ANONYMOUS;
}
if (!empty($config['increment_user_id']) && $user_id == 1)
{
return $config['increment_user_id'];
}
// A user id of 0 can happen, for example within the ban table if no user is banned...
// Within the posts and topics table this can be "dangerous" but is the fault of the user
// having mods installed (a poster id of 0 is not possible in 2.0.x).
// Therefore, we return the user id "as is".
return (int) $user_id;
}
/* Copy additional table fields from old forum to new forum if user wants this (for Mod compatibility for example)
function phpbb_copy_table_fields()
{
}
*/
/**
* Convert authentication
* user, group and forum table has to be filled in order to work
*/
function phpbb_convert_authentication($mode)
{
global $db, $src_db, $same_db, $convert, $user, $config, $cache;
if ($mode == 'start')
{
$db->sql_query($convert->truncate_statement . ACL_USERS_TABLE);
$db->sql_query($convert->truncate_statement . ACL_GROUPS_TABLE);
// What we will do is handling all 2.0.x admins as founder to replicate what is common in 2.0.x.
// After conversion the main admin need to make sure he is removing permissions and the founder status if wanted.
// Grab user ids of users with user_level of ADMIN
$sql = "SELECT uid AS user_id
FROM {$convert->src_table_prefix}members
WHERE adminid = 1
ORDER BY regdate ASC";
$result = $src_db->sql_query($sql);
while ($row = $src_db->sql_fetchrow($result))
{
$user_id = (int) phpbb_user_id($row['user_id']);
// Set founder admin...
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_type = ' . USER_FOUNDER . "
WHERE user_id = $user_id";
$db->sql_query($sql);
}
$src_db->sql_freeresult($result);
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = '" . $db->sql_escape('BOTS') . "'";
$result = $db->sql_query($sql);
$bot_group_id = (int) $db->sql_fetchfield('group_id');
$db->sql_freeresult($result);
}
// Grab forum auth information
$sql = "SELECT *
FROM {$convert->src_table_prefix}forums";
$result = $src_db->sql_query($sql);
$forum_access = array();
while ($row = $src_db->sql_fetchrow($result))
{
$forum_access[] = $row;
}
$src_db->sql_freeresult($result);
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'binary'");
}
// 获取版主用户ID以及对应的版面ID, 有继承关系的版主需要在转换后进行设置
$sql = "SELECT * from {$convert->src_table_prefix}moderators";
$result = $src_db->sql_query($sql);
$user_access = array();
while ($row = $src_db->sql_fetchrow($result))
{
$user_access[$row['fid']][] = $row;
}
$src_db->sql_freeresult($result);
// Grab group auth information
/*$sql = "SELECT g.group_id, aa.*
FROM {$convert->src_table_prefix}auth_access aa, {$convert->src_table_prefix}groups g
WHERE g.group_id = aa.group_id
AND g.group_single_user <> 1";
$result = $src_db->sql_query($sql);
$group_access = array();
while ($row = $src_db->sql_fetchrow($result))
{
$group_access[$row['forum_id']][] = $row;
}
$src_db->sql_freeresult($result);*/
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'utf8'");
}
// Add Forum Access List
$auth_map = array(
'auth_view' => array('f_', 'f_list'),
'auth_read' => array('f_read', 'f_search'),
'auth_post' => array('f_post', 'f_bbcode', 'f_smilies', 'f_img', 'f_sigs', 'f_postcount', 'f_report', 'f_subscribe', 'f_print', 'f_email'),
'auth_reply' => 'f_reply',
'auth_edit' => 'f_edit',
'auth_delete' => 'f_delete',
'auth_pollcreate' => 'f_poll',
'auth_vote' => 'f_vote',
'auth_announce' => 'f_announce',
'auth_sticky' => 'f_sticky',
'auth_attachments' => array('f_attach', 'f_download'),
'auth_download' => 'f_download',
);
// Define the ACL constants used in 2.0 to make the code slightly more readable
define('AUTH_ALL', 0);
define('AUTH_REG', 1);
define('AUTH_ACL', 2);
define('AUTH_MOD', 3);
define('AUTH_ADMIN', 5);
// A mapping of the simple permissions used by 2.0
$simple_auth_ary = array(
'public' => array(
'auth_view' => AUTH_ALL,
'auth_read' => AUTH_ALL,
'auth_post' => AUTH_ALL,
'auth_reply' => AUTH_ALL,
'auth_edit' => AUTH_REG,
'auth_delete' => AUTH_REG,
'auth_sticky' => AUTH_MOD,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_REG,
'auth_pollcreate' => AUTH_REG,
),
'registered' => array(
'auth_view' => AUTH_ALL,
'auth_read' => AUTH_ALL,
'auth_post' => AUTH_REG,
'auth_reply' => AUTH_REG,
'auth_edit' => AUTH_REG,
'auth_delete' => AUTH_REG,
'auth_sticky' => AUTH_MOD,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_REG,
'auth_pollcreate' => AUTH_REG,
),
'registered_hidden' => array(
'auth_view' => AUTH_REG,
'auth_read' => AUTH_REG,
'auth_post' => AUTH_REG,
'auth_reply' => AUTH_REG,
'auth_edit' => AUTH_REG,
'auth_delete' => AUTH_REG,
'auth_sticky' => AUTH_MOD,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_REG,
'auth_pollcreate' => AUTH_REG,
),
'private' => array(
'auth_view' => AUTH_ALL,
'auth_read' => AUTH_ACL,
'auth_post' => AUTH_ACL,
'auth_reply' => AUTH_ACL,
'auth_edit' => AUTH_ACL,
'auth_delete' => AUTH_ACL,
'auth_sticky' => AUTH_ACL,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_ACL,
'auth_pollcreate' => AUTH_ACL,
),
'private_hidden' => array(
'auth_view' => AUTH_ACL,
'auth_read' => AUTH_ACL,
'auth_post' => AUTH_ACL,
'auth_reply' => AUTH_ACL,
'auth_edit' => AUTH_ACL,
'auth_delete' => AUTH_ACL,
'auth_sticky' => AUTH_ACL,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_ACL,
'auth_pollcreate' => AUTH_ACL,
),
'moderator' => array(
'auth_view' => AUTH_ALL,
'auth_read' => AUTH_MOD,
'auth_post' => AUTH_MOD,
'auth_reply' => AUTH_MOD,
'auth_edit' => AUTH_MOD,
'auth_delete' => AUTH_MOD,
'auth_sticky' => AUTH_MOD,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_MOD,
'auth_pollcreate' => AUTH_MOD,
),
'moderator_hidden' => array(
'auth_view' => AUTH_MOD,
'auth_read' => AUTH_MOD,
'auth_post' => AUTH_MOD,
'auth_reply' => AUTH_MOD,
'auth_edit' => AUTH_MOD,
'auth_delete' => AUTH_MOD,
'auth_sticky' => AUTH_MOD,
'auth_announce' => AUTH_MOD,
'auth_vote' => AUTH_MOD,
'auth_pollcreate' => AUTH_MOD,
),
);
if ($mode == 'start')
{
user_group_auth('guests', 'SELECT user_id, {GUESTS} FROM ' . USERS_TABLE . ' WHERE user_id = ' . ANONYMOUS, false);
user_group_auth('registered', 'SELECT user_id, {REGISTERED} FROM ' . USERS_TABLE . ' WHERE user_id <> ' . ANONYMOUS . " AND group_id <> $bot_group_id", false);
// Selecting from old table
if (!empty($config['increment_user_id']))
{
$auth_sql = 'SELECT uid AS user_id, {ADMINISTRATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1 AND uid <> 1';
user_group_auth('administrators', $auth_sql, true);
$auth_sql = 'SELECT ' . $config['increment_user_id'] . ' as user_id, {ADMINISTRATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1 AND uid = 1';
user_group_auth('administrators', $auth_sql, true);
}
else
{
$auth_sql = 'SELECT uid AS user_id, {ADMINISTRATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1';
user_group_auth('administrators', $auth_sql, true);
}
if (!empty($config['increment_user_id']))
{
$auth_sql = 'SELECT uid AS user_id, {GLOBAL_MODERATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1 AND uid <> 1';
user_group_auth('global_moderators', $auth_sql, true);
$auth_sql = 'SELECT ' . $config['increment_user_id'] . ' as user_id, {GLOBAL_MODERATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1 AND uid = 1';
user_group_auth('global_moderators', $auth_sql, true);
}
else
{
$auth_sql = 'SELECT uid AS user_id, {GLOBAL_MODERATORS} FROM ' . $convert->src_table_prefix . 'members WHERE adminid = 1';
user_group_auth('global_moderators', $auth_sql, true);
}
}
else if ($mode == 'first')
{
// Go through all 2.0.x forums
foreach ($forum_access as $forum)
{
$new_forum_id = (int) $forum['fid'];
// Administrators have full access to all forums whatever happens
mass_auth('group_role', $new_forum_id, 'administrators', 'FORUM_FULL');
$matched_type = 'public'; // 全部使用公开属性, 需要在转换后调整
switch ($matched_type)
{
case 'public':
mass_auth('group_role', $new_forum_id, 'guests', 'FORUM_LIMITED');
mass_auth('group_role', $new_forum_id, 'registered', 'FORUM_LIMITED_POLLS');
mass_auth('group_role', $new_forum_id, 'bots', 'FORUM_BOT');
break;
case 'registered':
mass_auth('group_role', $new_forum_id, 'guests', 'FORUM_READONLY');
mass_auth('group_role', $new_forum_id, 'bots', 'FORUM_BOT');
// no break;
case 'registered_hidden':
mass_auth('group_role', $new_forum_id, 'registered', 'FORUM_POLLS');
break;
case 'private':
case 'private_hidden':
case 'moderator':
case 'moderator_hidden':
default:
// The permissions don't match a simple set, so we're going to have to map them directly
// No post approval for all, in 2.0.x this feature does not exist
mass_auth('group', $new_forum_id, 'guests', 'f_noapprove', ACL_YES);
mass_auth('group', $new_forum_id, 'registered', 'f_noapprove', ACL_YES);
break;
}
}
}
else if ($mode == 'second')
{
// Assign permission roles and other default permissions
// guests having u_download and u_search ability
$db->sql_query('INSERT INTO ' . ACL_GROUPS_TABLE . ' (group_id, forum_id, auth_option_id, auth_role_id, auth_setting) SELECT ' . get_group_id('guests') . ', 0, auth_option_id, 0, 1 FROM ' . ACL_OPTIONS_TABLE . " WHERE auth_option IN ('u_', 'u_download', 'u_search')");
// administrators/global mods having full user features
mass_auth('group_role', 0, 'administrators', 'USER_FULL');
mass_auth('group_role', 0, 'global_moderators', 'USER_FULL');
// By default all converted administrators are given full access
mass_auth('group_role', 0, 'administrators', 'ADMIN_FULL');
// All registered users are assigned the standard user role
mass_auth('group_role', 0, 'registered', 'USER_STANDARD');
mass_auth('group_role', 0, 'registered_coppa', 'USER_STANDARD');
// Instead of administrators being global moderators we give the MOD_FULL role to global mods (admins already assigned to this group)
mass_auth('group_role', 0, 'global_moderators', 'MOD_FULL');
// And now those who have had their avatar rights removed get assigned a more restrictive role
//以下注释掉对没有头像权限和站内PM权限的用户进行的权限设置, 需转换后在后台控制面板进行设置
/*$sql = 'SELECT uid FROM ' . $convert->src_table_prefix . 'members
WHERE user_allowavatar = 0
AND user_id > 0';
$result = $src_db->sql_query($sql);
while ($row = $src_db->sql_fetchrow($result))
{
mass_auth('user_role', 0, (int) phpbb_user_id($row['user_id']), 'USER_NOAVATAR');
}
$src_db->sql_freeresult($result);
// And the same for those who have had their PM rights removed
$sql = 'SELECT user_id FROM ' . $convert->src_table_prefix . 'users
WHERE user_allow_pm = 0
AND user_id > 0';
$result = $src_db->sql_query($sql);
while ($row = $src_db->sql_fetchrow($result))
{
mass_auth('user_role', 0, (int) phpbb_user_id($row['user_id']), 'USER_NOPM');
}
$src_db->sql_freeresult($result);*/
}
else if ($mode == 'third')
{
// And now the moderators 在这里设置版主权限
// We make sure that they have at least standard access to the forums they moderate in addition to the moderating permissions
foreach ($user_access as $forum_id => $access_map)
{
$forum_id = (int) $forum_id;
foreach ($access_map as $access)
{
mass_auth('user_role', $forum_id, (int) phpbb_user_id($access['uid']), 'MOD_STANDARD');
mass_auth('user_role', $forum_id, (int) phpbb_user_id($access['uid']), 'FORUM_STANDARD');
}
}
/*foreach ($group_access as $forum_id => $access_map)
{
$forum_id = (int) $forum_id;
foreach ($access_map as $access)
{
if (isset($access['auth_mod']) && $access['auth_mod'] == 1)
{
mass_auth('group_role', $forum_id, (int) $access['group_id'], 'MOD_STANDARD');
mass_auth('group_role', $forum_id, (int) $access['group_id'], 'FORUM_STANDARD');
}
}
}*/
// We grant everyone readonly access to the categories to ensure that the forums are visible
$sql = 'SELECT forum_id, forum_name, parent_id, left_id, right_id
FROM ' . FORUMS_TABLE . '
ORDER BY left_id ASC';
$result = $db->sql_query($sql);
$parent_forums = $forums = array();
while ($row = $db->sql_fetchrow($result))
{
if ($row['parent_id'] == 0)
{
mass_auth('group_role', $row['forum_id'], 'administrators', 'FORUM_FULL');
mass_auth('group_role', $row['forum_id'], 'global_moderators', 'FORUM_FULL');
$parent_forums[] = $row;
}
else
{
$forums[] = $row;
}
}
$db->sql_freeresult($result);
global $auth;
// Let us see which groups have access to these forums...
foreach ($parent_forums as $row)
{
// Get the children
$branch = $forum_ids = array();
foreach ($forums as $key => $_row)
{
if ($_row['left_id'] > $row['left_id'] && $_row['left_id'] < $row['right_id'])
{
$branch[] = $_row;
$forum_ids[] = $_row['forum_id'];
continue;
}
}
if (sizeof($forum_ids))
{
// Now make sure the user is able to read these forums
$hold_ary = $auth->acl_group_raw_data(false, 'f_list', $forum_ids);
if (empty($hold_ary))
{
continue;
}
foreach ($hold_ary as $g_id => $f_id_ary)
{
$set_group = false;
foreach ($f_id_ary as $f_id => $auth_ary)
{
foreach ($auth_ary as $auth_option => $setting)
{
if ($setting == ACL_YES)
{
$set_group = true;
break 2;
}
}
}
if ($set_group)
{
mass_auth('group', $row['forum_id'], $g_id, 'f_list', ACL_YES);
}
}
}
}
}
}
/**
* Set primary group.
* Really simple and only based on user_level (remaining groups will be assigned later)
*/
function phpbb_set_primary_group($user_level)
{
global $convert_row;
if ($user_level == 1)
{
return get_group_id('administrators');
}
/* else if ($user_level == 2)
{
return get_group_id('global_moderators');
}
else if ($user_level == 0 && $convert_row['user_active'])*/
else if ($convert_row['user_active'])
{
return get_group_id('registered');
}
return 0;
}
/**
* Convert the group name, making sure to avoid conflicts with 3.0 special groups
*/
function phpbb_convert_group_name($group_name)
{
$default_groups = array(
'GUESTS',
'REGISTERED',
'REGISTERED_COPPA',
'GLOBAL_MODERATORS',
'ADMINISTRATORS',
'BOTS',
);
if (in_array(strtoupper($group_name), $default_groups))
{
return 'phpBB2 - ' . $group_name;
}
return phpbb_set_default_encoding($group_name);
}
/**
* Convert the group type constants
*/
function phpbb_convert_group_type($group_type)
{
switch ($group_type)
{
case 0:
return GROUP_OPEN;
break;
case 1:
return GROUP_CLOSED;
break;
case 2:
return GROUP_HIDDEN;
break;
}
// Never return GROUP_SPECIAL here, because only phpBB3's default groups are allowed to have this type set.
return GROUP_HIDDEN;
}
/**
* Convert the topic type constants
*/
function phpbb_convert_topic_type($topic_type)
{
switch ($topic_type)
{
case 0:
return POST_NORMAL;
break;
case 1:
return POST_STICKY;
break;
case 2:
return POST_ANNOUNCE;
break;
case 3:
return POST_GLOBAL;
break;
}
return POST_NORMAL;
}
function phpbb_replace_size($matches)
{
return '[size=' . min(200, ceil(60 + (((double) $matches[1])*20))) . ']';
}
/**
* Reparse the message stripping out the bbcode_uid values and adding new ones and setting the bitfield
* @todo What do we want to do about HTML in messages - currently it gets converted to the entities, but there may be some objections to this
*/
function phpbb_prepare_message($message)
{
global $phpbb_root_path, $phpEx, $db, $convert, $user, $config, $cache, $convert_row, $message_parser;
if (!$message)
{
$convert->row['mp_bbcode_bitfield'] = $convert_row['mp_bbcode_bitfield'] = 0;
return '';
}
// Adjust size...
if (strpos($message, '[size=') !== false)
{
//$message = preg_replace_callback('/\[size=(\d*):(' . $convert->row['old_bbcode_uid'] . ')\]/', 'phpbb_replace_size', $message);
$message = preg_replace_callback('/\[size=(\d*)\]/', 'phpbb_replace_size', $message);
}
if (strpos($message, '[font=') !== false)
{
$message = preg_replace('/\[font=(.*?)\]/s', '', $message);
$message = preg_replace('/\[\/font\]/s', '', $message);
}
if (strpos($message, '[quote=') !== false)
{
$message = preg_replace('/\[quote="(.*?)"\]/s', '[quote="\1"]', $message);
$message = preg_replace('/\[quote=\\\"(.*?)\\\"\]/s', '[quote="\1"]', $message);
// let's hope that this solves more problems than it causes. Deal with escaped quotes.
$message = str_replace('\"', '"', $message);
$message = str_replace('\"', '"', $message);
}
// Already the new user id ;)
$user_id = $convert->row['poster_id'];
$message = str_replace('<', '<', $message);
$message = str_replace('>', '>', $message);
$message = str_replace('<br />', "\n", $message);
// make the post UTF-8
$message = dz_set_encoding($message);
$message_parser->warn_msg = array(); // Reset the errors from the previous message
$message_parser->bbcode_uid = make_uid($convert->row['post_time']);
$message_parser->message = $message;
unset($message);
// Make sure options are set.
// $enable_html = (!isset($row['enable_html'])) ? false : $row['enable_html'];
$enable_bbcode = (!isset($convert->row['enable_bbcode'])) ? true : $convert->row['enable_bbcode'];
$enable_smilies = (!isset($convert->row['enable_smilies'])) ? true : $convert->row['enable_smilies'];
$enable_magic_url = (!isset($convert->row['enable_magic_url'])) ? true : $convert->row['enable_magic_url'];
// parse($allow_bbcode, $allow_magic_url, $allow_smilies, $allow_img_bbcode = true, $allow_flash_bbcode = true, $allow_quote_bbcode = true, $allow_url_bbcode = true, $update_this_message = true, $mode = 'post')
$message_parser->parse($enable_bbcode, $enable_magic_url, $enable_smilies);
if (sizeof($message_parser->warn_msg))
{
$msg_id = isset($convert->row['post_id']) ? $convert->row['post_id'] : $convert->row['privmsgs_id'];
$convert->p_master->error('<span style="color:red">' . $user->lang['POST_ID'] . ': ' . $msg_id . ' ' . $user->lang['CONV_ERROR_MESSAGE_PARSER'] . ': <br /><br />' . implode('<br />', $message_parser->warn_msg), __LINE__, __FILE__, true);
}
$convert->row['mp_bbcode_bitfield'] = $convert_row['mp_bbcode_bitfield'] = $message_parser->bbcode_bitfield;
$message = $message_parser->message;
unset($message_parser->message);
return $message;
}
/**
* Return the bitfield calculated by the previous function
*/
function get_bbcode_bitfield()
{
global $convert_row;
return $convert_row['mp_bbcode_bitfield'];
}
/**
* Determine the last user to edit a post
* In practice we only tracked edits by the original poster in 2.0.x so this will only be set if they had edited their own post
*/
function phpbb_post_edit_user()
{
global $convert_row, $config;
if (isset($convert_row['post_edit_count']))
{
return phpbb_user_id($convert_row['poster_id']);
}
return 0;
}
/**
* Obtain the path to uploaded files on the 2.0.x forum
* This is only used if the Attachment MOD was installed
*/
function phpbb_get_files_dir()
{
if (!defined('MOD_ATTACHMENT'))
{
return;
}
global $src_db, $same_db, $convert, $user, $config, $cache;
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'binary'");
}
$sql = 'SELECT config_value AS upload_dir
FROM ' . $convert->src_table_prefix . "attachments_config
WHERE config_name = 'upload_dir'";
$result = $src_db->sql_query($sql);
$upload_path = $src_db->sql_fetchfield('upload_dir');
$src_db->sql_freeresult($result);
$sql = 'SELECT config_value AS ftp_upload
FROM ' . $convert->src_table_prefix . "attachments_config
WHERE config_name = 'allow_ftp_upload'";
$result = $src_db->sql_query($sql);
$ftp_upload = (int) $src_db->sql_fetchfield('ftp_upload');
$src_db->sql_freeresult($result);
if ($convert->mysql_convert && $same_db)
{
$src_db->sql_query("SET NAMES 'utf8'");
}
if ($ftp_upload)
{
$convert->p_master->error($user->lang['CONV_ERROR_ATTACH_FTP_DIR'], __LINE__, __FILE__);
}
return $upload_path;
}
/**
* Copy thumbnails of uploaded images from the 2.0.x forum
* This is only used if the Attachment MOD was installed
*/
function phpbb_copy_thumbnails()
{
global $db, $convert, $user, $config, $cache, $phpbb_root_path;
$src_path = $convert->options['forum_path'] . '/' . phpbb_get_files_dir() . '/thumbs/';
if ($handle = @opendir($src_path))
{
while ($entry = readdir($handle))
{
if ($entry[0] == '.')
{
continue;
}
if (is_dir($src_path . $entry))
{
continue;
}
else
{
copy_file($src_path . $entry, $config['upload_path'] . '/' . preg_replace('/^t_/', 'thumb_', $entry));
@unlink($phpbb_root_path . $config['upload_path'] . '/thumbs/' . $entry);
}
}
closedir($handle);
}
}
/**
* Convert the attachment category constants
* This is only used if the Attachment MOD was installed
*/
function phpbb_attachment_category($cat_id)
{
switch ($cat_id)
{
case 1:
return ATTACHMENT_CATEGORY_IMAGE;
break;
case 2:
return ATTACHMENT_CATEGORY_WM;
break;
case 3:
return ATTACHMENT_CATEGORY_FLASH;
break;
}
return ATTACHMENT_CATEGORY_NONE;
}
/**
* Obtain list of forums in which different attachment categories can be used
*/
function phpbb_attachment_forum_perms($forum_permissions)
{
if (empty($forum_permissions))
{
return '';
}
// Decode forum permissions
$forum_ids = array();
$one_char_encoding = '#';
$two_char_encoding = '.';
$auth_len = 1;
for ($pos = 0; $pos < strlen($forum_permissions); $pos += $auth_len)
{
$forum_auth = substr($forum_permissions, $pos, 1);
if ($forum_auth == $one_char_encoding)
{
$auth_len = 1;
continue;
}
else if ($forum_auth == $two_char_encoding)
{
$auth_len = 2;
$pos--;
continue;
}
$forum_auth = substr($forum_permissions, $pos, $auth_len);
$forum_id = base64_unpack($forum_auth);
$forum_ids[] = (int) $forum_id;
}
if (sizeof($forum_ids))
{
return attachment_forum_perms($forum_ids);
}
return '';
}
/**
* Convert the avatar type constants
*/
function phpbb_avatar_type($type)
{
switch ($type)
{
case 1:
return AVATAR_UPLOAD;
break;
case 2:
return AVATAR_REMOTE;
break;
case 3:
return AVATAR_GALLERY;
break;
}
return 0;
}
/**
* Just undos the replacing of '<' and '>'
*/
function phpbb_smilie_html_decode($code)
{
$code = str_replace('<', '<', $code);
return str_replace('>', '>', $code);
}
/**
* Transfer avatars, copying the image if it was uploaded
*/
function phpbb_import_avatar($user_avatar)
{
global $convert_row;
if (!$convert_row['user_avatar_type'])
{
return '';
}
else if ($convert_row['user_avatar_type'] == 1)
{
// Uploaded avatar
return import_avatar($user_avatar, false, $convert_row['user_id']);
}
else if ($convert_row['user_avatar_type'] == 2)
{
// Remote avatar
return $user_avatar;
}
else if ($convert_row['user_avatar_type'] == 3)
{
// Gallery avatar
return $user_avatar;
}
return '';
}
/**
* Find out about the avatar's dimensions
*/
function phpbb_get_avatar_height($user_avatar)
{
global $convert_row;
if (empty($convert_row['user_avatar_type']))
{
return 0;
}
return get_avatar_height($user_avatar, 'phpbb_avatar_type', $convert_row['user_avatar_type']);
}
/**
* Find out about the avatar's dimensions
*/
function phpbb_get_avatar_width($user_avatar)
{
global $convert_row;
if (empty($convert_row['user_avatar_type']))
{
return 0;
}
return get_avatar_width($user_avatar, 'phpbb_avatar_type', $convert_row['user_avatar_type']);
}
/**
* Calculate the correct to_address field for private messages
*/
function phpbb_privmsgs_to_userid($to_userid)
{
global $config;
return 'u_' . phpbb_user_id($to_userid);
}
/**
* Calculate whether a private message was unread using the bitfield
*/
function phpbb_unread_pm($pm_type)
{
return ($pm_type == 5) ? 1 : 0;
}
/**
* Calculate whether a private message was new using the bitfield
*/
function phpbb_new_pm($pm_type)
{
return ($pm_type == 1) ? 1 : 0;
}
/**
* Obtain the folder_id for the custom folder created to replace the savebox from 2.0.x (used to store saved private messages)
*/
function phpbb_get_savebox_id($user_id)
{
global $db;
$user_id = phpbb_user_id($user_id);
// Only one custom folder, check only one
$sql = 'SELECT folder_id
FROM ' . PRIVMSGS_FOLDER_TABLE . '
WHERE user_id = ' . $user_id;
$result = $db->sql_query_limit($sql, 1);
$folder_id = (int) $db->sql_fetchfield('folder_id');
$db->sql_freeresult($result);
return $folder_id;
}
/**
* Transfer attachment specific configuration options
* These were not stored in the main config table on 2.0.x
* This is only used if the Attachment MOD was installed
*/
function phpbb_import_attach_config()
{
global $db, $src_db, $same_db, $convert, $config;
set_config('allow_attachments', 1);
set_config('max_filesize', '262144');
set_config('max_filesize_pm', '262144');
set_config('attachment_quota', '102428800');
set_config('max_attachments', '3');
set_config('max_attachments_pm', '3');
set_config('allow_pm_attach', '0');
set_config('img_display_inlined', $attach_config['img_display_inlined']);
set_config('img_max_width', $attach_config['img_max_width']);
set_config('img_max_height', $attach_config['img_max_height']);
set_config('img_link_width', $attach_config['img_link_width']);
set_config('img_link_height', $attach_config['img_link_height']);
set_config('img_create_thumbnail', $attach_config['img_create_thumbnail']);
set_config('img_max_thumb_width', 400);
set_config('img_min_thumb_filesize', $attach_config['img_min_thumb_filesize']);
set_config('img_imagick', $attach_config['img_imagick']);
}
/**
* Adjust 2.0.x disallowed names to 3.0.x format
*/
function phpbb_disallowed_username($username)
{
// Replace * with %
$username = phpbb_set_default_encoding(str_replace('*', '%', $username));
return utf8_htmlspecialchars($username);
}
/**
* Checks whether there are any usernames on the old board that would map to the same
* username_clean on phpBB3. Prints out a list if any exist and exits.
*/
function dz_check_username_collisions()
{
global $db, $src_db, $convert, $table_prefix, $user, $lang;
$map_dbms = '';
switch ($db->sql_layer)
{
case 'mysql':
$map_dbms = 'mysql_40';
break;
case 'mysql4':
if (version_compare($db->mysql_version, '4.1.3', '>='))
{
$map_dbms = 'mysql_41';
}
else
{
$map_dbms = 'mysql_40';
}
break;
case 'mysqli':
$map_dbms = 'mysql_41';
break;
case 'mssql':
case 'mssql_odbc':
$map_dbms = 'mssql';
break;
default:
$map_dbms = $db->sql_layer;
break;
}
// create a temporary table in which we store the clean usernames
$drop_sql = 'DROP TABLE ' . $table_prefix . 'userconv';
switch ($map_dbms)
{
case 'firebird':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id INTEGER NOT NULL,
username_clean VARCHAR(255) CHARACTER SET UTF8 DEFAULT \'\' NOT NULL COLLATE UNICODE
)';
break;
case 'mssql':
$create_sql = 'CREATE TABLE [' . $table_prefix . 'userconv] (
[user_id] [int] NOT NULL ,
[username_clean] [varchar] (255) DEFAULT (\'\') NOT NULL
)';
break;
case 'mysql_40':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id mediumint(8) NOT NULL,
username_clean blob NOT NULL
)';
break;
case 'mysql_41':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id mediumint(8) NOT NULL,
username_clean varchar(255) DEFAULT \'\' NOT NULL
) CHARACTER SET `utf8` COLLATE `utf8_bin`';
break;
case 'oracle':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id number(8) NOT NULL,
username_clean varchar2(255) DEFAULT \'\'
)';
break;
case 'postgres':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id INT4 DEFAULT \'0\',
username_clean varchar_ci DEFAULT \'\' NOT NULL
)';
break;
case 'sqlite':
$create_sql = 'CREATE TABLE ' . $table_prefix . 'userconv (
user_id INTEGER NOT NULL DEFAULT \'0\',
username_clean varchar(255) NOT NULL DEFAULT \'\'
)';
break;
}
$db->sql_return_on_error(true);
$db->sql_query($drop_sql);
$db->sql_return_on_error(false);
$db->sql_query($create_sql);
// now select all user_ids and usernames and then convert the username (this can take quite a while!)
$sql = 'SELECT uid as user_id, username
FROM ' . $convert->src_table_prefix . 'members';
$result = $src_db->sql_query($sql);
$insert_ary = array();
$i = 0;
while ($row = $src_db->sql_fetchrow($result))
{
$clean_name = utf8_clean_string(phpbb_set_default_encoding($row['username']));
$insert_ary[] = array('user_id' => (int) $row['user_id'], 'username_clean' => (string) $clean_name);
if ($i % 1000 == 999)
{
$db->sql_multi_insert($table_prefix . 'userconv', $insert_ary);
$insert_ary = array();
}
$i++;
}
$src_db->sql_freeresult($result);
if (sizeof($insert_ary))
{
$db->sql_multi_insert($table_prefix . 'userconv', $insert_ary);
}
unset($insert_ary);
// now find the clean version of the usernames that collide
$sql = 'SELECT username_clean
FROM ' . $table_prefix . 'userconv
GROUP BY username_clean
HAVING COUNT(user_id) > 1';
$result = $db->sql_query($sql);
$colliding_names = array();
while ($row = $db->sql_fetchrow($result))
{
$colliding_names[] = $row['username_clean'];
}
$db->sql_freeresult($result);
// there was at least one collision, the admin will have to solve it before conversion can continue
if (sizeof($colliding_names))
{
$sql = 'SELECT user_id, username_clean
FROM ' . $table_prefix . 'userconv
WHERE ' . $db->sql_in_set('username_clean', $colliding_names);
$result = $db->sql_query($sql);
unset($colliding_names);
$colliding_user_ids = array();
while ($row = $db->sql_fetchrow($result))
{
$colliding_user_ids[(int) $row['user_id']] = $row['username_clean'];
}
$db->sql_freeresult($result);
$sql = 'SELECT username, uid as user_id, posts as user_posts
FROM ' . $convert->src_table_prefix . 'members
WHERE ' . $src_db->sql_in_set('uid', array_keys($colliding_user_ids));
$result = $src_db->sql_query($sql);
$colliding_users = array();
while ($row = $db->sql_fetchrow($result))
{
$row['user_id'] = (int) $row['user_id'];
if (isset($colliding_user_ids[$row['user_id']]))
{
$colliding_users[$colliding_user_ids[$row['user_id']]][] = $row;
}
}
$db->sql_freeresult($result);
unset($colliding_user_ids);
$list = '';
foreach ($colliding_users as $username_clean => $users)
{
$list .= sprintf($user->lang['COLLIDING_CLEAN_USERNAME'], $username_clean) . "<br />\n";
foreach ($users as $i => $row)
{
$list .= sprintf($user->lang['COLLIDING_USER'], $row['user_id'], phpbb_set_default_encoding($row['username']), $row['user_posts']) . "<br />\n";
}
}
$lang['INST_ERR_FATAL'] = $user->lang['CONV_ERR_FATAL'];
$convert->p_master->error('<span style="color:red">' . $user->lang['COLLIDING_USERNAMES_FOUND'] . '</span></b><br /><br />' . $list . '<b>', __LINE__, __FILE__);
}
$db->sql_query($drop_sql);
}
function dz_online_count($input){
if (preg_match('/(\d+)\s+(\d+)/', $input, $m)){
return trim($m[1]);
}
return 0;
}
function dz_online_date($input){
if (preg_match('/(\d+)\s+(\d+)/', $input, $m)){
return trim($m[2]);
}
return 0;
}
function dz_get_uidbyname($in_name){
global $db, $src_db, $convert, $table_prefix;
$sql = 'SELECT uid as user_id, username
FROM ' . $convert->src_table_prefix . "members WHERE username='".trim($in_name)."'";
$result = $src_db->sql_query($sql);
$row = $src_db->sql_fetchrow($result);
$src_db->sql_freeresult($result);
if (empty($row['user_id']) || $row['user_id'] == ''){
$row['user_id'] = -1;
}
return $row['user_id'];
}
function dz_get_first_pidbytid( $tid )
{
global $db, $src_db, $convert, $table_prefix;
$tid = intval( $tid );
$sql = 'select pid from ' . $convert->src_table_prefix . 'posts where tid = ' . $tid . ' order by dateline asc limit 0, 1';
$result = $src_db->sql_query($sql);
$row = $src_db->sql_fetchrow($result);
$src_db->sql_freeresult($result);
if (empty($row['pid']) || $row['pid'] == ''){
$row['pid'] = 0;
}
return $row['pid'];
}
function dz_get_last_pidbytid ( $tid )
{
global $db, $src_db, $convert, $table_prefix;
$tid = intval( $tid );
$sql = 'select pid from ' . $convert->src_table_prefix . 'posts where tid = ' . $tid . ' order by dateline desc limit 0, 1';
$result = $src_db->sql_query($sql);
$row = $src_db->sql_fetchrow($result);
$src_db->sql_freeresult($result);
if (empty($row['pid']) || $row['pid'] == ''){
$row['pid'] = 0;
}
return $row['pid'];
}
function dz_convert_topic_type( $displayorder )
{
//define('POST_NORMAL', 0);
//define('POST_STICKY', 1);
//define('POST_ANNOUNCE', 2);
//define('POST_GLOBAL', 3);
switch ($displayorder)
{
case 0:
return POST_NORMAL;
break;
case 1:
return POST_STICKY;
break;
case 2:
return POST_ANNOUNCE;
break;
case 3:
return POST_GLOBAL;
break;
}
return POST_NORMAL;
}
function dz_import_smiley( $url )
{
global $convert;
//copy( $convert->options[forum_path] . '/' . $convert->convertor[smilies_path] . $url, '../images/smilies/' . $url );
//print_r( $convert );exit;
//echo $url;
//exit;
return $url;
}
function dz_negative ($input)
{
if ($input == -1){
return 1;
}else{
return 0;
}
}
function dz_convert_group_type ($group_type)
{
if ($group_type == 'system'){
return GROUP_SPECIAL;
} else if ($group_type == 'member') {
return GROUP_OPEN;
} else if ($group_type == 'special'){
return GROUP_SPECIAL ;
} else {
return GROUP_CLOSED;
}
}
function dz_set_user_type ($user_type)
{
if($user_type == 1)
{
return 3;
} else {
return 0;
}
}
function dz_get_birthday($birthday)
{
}
function dz_import_avatar($source)
{
if (empty($source) || preg_match('#^https?:#i', $source) || preg_match('#blank\.(gif|png)$#i', $source))
{
return $source;
}
global $convert, $phpbb_root_path, $config, $user;
if (!isset($convert->convertor['avatar_path']))
{
$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_AVATAR_PATH'], 'import_avatar()'), __LINE__, __FILE__);
}
if (preg_match('/^images\/avatars\/(.*)/', $source, $m))
{
return 'dz_avatars/'.$m[1];
} else if (preg_match('/^customavatars\/(.*)/', $source, $m)) {
return 'dz_custom_avatars/'.$m[1];
} else {
return '';
}
/*if ($use_target === false && $convert_row['user_id'] !== false)
{
$use_target = $config['avatar_salt'] . '_' . $user_id . '.' . substr(strrchr($source, '.'), 1);
}
$result = _import_check('avatar_path', $source, $use_target);
return ((!empty($user_id)) ? $user_id : $use_target) . '.' . substr(strrchr($source, '.'), 1);*/
}
function dz_avatar_type($source)
{
if (empty($source) || preg_match('#^https?:#i', $source) || preg_match('#blank\.(gif|png)$#i', $source))
{
return 2;
} else if (preg_match('/images\/avatars\/(.*)/', $source, $m)) {
return 3;
} else if (preg_match('/^customavatars\//', $source, $m)) {
return 3;
}
return 1;
}
function import_custom_avatar($gallery_name = '')
{
global $config, $convert, $phpbb_root_path, $user;
$relative_path = empty($convert->convertor['source_path_absolute']);
if (empty($convert->convertor['avatar_gallery_path']))
{
$convert->p_master->error(sprintf($user->lang['CONV_ERROR_NO_GALLERY_PATH'], 'import_avatar_gallery()'), __LINE__, __FILE__);
}
$src_path = relative_base(path($convert->convertor['avatar_gallery_path'], $relative_path), $relative_path);
if (is_dir($src_path))
{
// Do not die on failure... safe mode restrictions may be in effect.
copy_dir($convert->convertor['avatar_custom_path'], path($config['avatar_gallery_path']) . $gallery_name, true, false, false, $relative_path);
}
}
function dz_import_attachment($source, $use_target = false)
{
if (empty($source))
{
return '';
}
return 'dz_files/' . $source;
}
function dz_get_extension($source)
{
if (empty($source))
{
return '';
}
$path_parts = pathinfo($source);
return $path_parts["extension"];
}
function nozerotoone($input){
if ($input == 0){
return 0;
} else {
return 1;
}
}
function change_poll_option_id_type() {
global $db, $src_db, $same_db, $convert, $user, $config, $cache;
$sql = 'ALTER TABLE ' . POLL_OPTIONS_TABLE . " CHANGE `poll_option_id` `poll_option_id` INT( 10 ) NOT NULL default '0'";
$db->sql_query($sql);
}
?>
| wuts/xiaodoudian | forum/install/convertors/functions_discuz60.php | PHP | gpl-3.0 | 46,660 |
/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.filter;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ports.metadata.AttributeMetaData;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.preprocessing.AbstractValueProcessing;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.math.container.Range;
/**
* This operator simply replaces all values by their absolute respective value.
*
* @author Ingo Mierswa, Sebastian Land, Tobias Malbrecht
*/
public class AbsoluteValueFilter extends AbstractValueProcessing {
public AbsoluteValueFilter(OperatorDescription description) {
super(description);
}
@Override
public ExampleSetMetaData applyOnFilteredMetaData(ExampleSetMetaData metaData) {
for (AttributeMetaData amd : metaData.getAllAttributes()) {
if (amd.isNumerical() && !amd.isSpecial()) {
Range range = amd.getValueRange();
amd.setValueRange(new Range(0, Math.max(Math.abs(range.getLower()), Math.abs(range.getUpper()))),
amd.getValueSetRelation());
amd.getMean().setUnkown();
}
}
return metaData;
}
@Override
public ExampleSet applyOnFiltered(ExampleSet exampleSet) throws OperatorException {
for (Example example : exampleSet) {
for (Attribute attribute : exampleSet.getAttributes()) {
if (attribute.isNumerical()) {
double value = example.getValue(attribute);
value = Math.abs(value);
example.setValue(attribute, value);
}
}
}
return exampleSet;
}
@Override
protected int[] getFilterValueTypes() {
return new int[] { Ontology.NUMERICAL };
}
@Override
public boolean writesIntoExistingData() {
return true;
}
}
| transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/preprocessing/filter/AbsoluteValueFilter.java | Java | gpl-3.0 | 2,782 |
/* jslint node: true */
'use strict';
var express = require('express'),
sections = require('./sections'),
http = require('http'),
expressLess = require('express-less'),
path = require('path');
/**
* Create server
*/
var app = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 4000);
app.set('views', __dirname + '/sections');
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use('/css', expressLess(__dirname + '/sections/_default/less'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/vendor', express.static(__dirname + '/bower_components'));
app.use(app.router);
/**
* Routes
*/
/*
* Start Server
*/
var server = http.createServer( app ),
io = require('socket.io')( server ),
params = {
server: app,
io: io
};
// Add the routes from the sections
sections( params );
// serve index and view partials
app.get('/', function (req, res) {
res.render('_default/index');
});
app.get(/\/html\/([\w\/]+)\.html/, function (req, res) {
var name = req.params[0];
res.render(name);
});
server.listen(app.get('port'), function () {
console.log('Express app listening on port ' + app.get('port'));
});
| RenderTeam/focus | index.js | JavaScript | gpl-3.0 | 1,333 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "ColorButton.h"
static const int ARROW_SIZE_CX = 4 ;
static const int ARROW_SIZE_CY = 2 ;
/*
================
ColorButton_SetColor
Sets the current color button color
================
*/
void ColorButton_SetColor ( HWND hWnd, COLORREF color )
{
if ( NULL == hWnd )
{
return;
}
SetWindowLong ( hWnd, GWL_USERDATA, color );
InvalidateRect ( hWnd, NULL, FALSE );
}
void ColorButton_SetColor ( HWND hWnd, const char* color )
{
float red;
float green;
float blue;
float alpha;
if ( NULL == hWnd )
{
return;
}
sscanf ( color, "%f,%f,%f,%f", &red, &green, &blue, &alpha );
ColorButton_SetColor ( hWnd, RGB(red*255.0f, green*255.0f, blue*255.0f) );
}
void AlphaButton_SetColor ( HWND hWnd, const char* color )
{
float red;
float green;
float blue;
float alpha;
if ( NULL == hWnd )
{
return;
}
sscanf ( color, "%f,%f,%f,%f", &red, &green, &blue, &alpha );
ColorButton_SetColor ( hWnd, RGB(alpha*255.0f, alpha*255.0f, alpha*255.0f) );
}
/*
================
ColorButton_GetColor
Retrieves the current color button color
================
*/
COLORREF ColorButton_GetColor ( HWND hWnd )
{
return (COLORREF) GetWindowLong ( hWnd, GWL_USERDATA );
}
/*
================
ColorButton_DrawArrow
Draws the arrow on the color button
================
*/
static void ColorButton_DrawArrow ( HDC hDC, RECT* pRect, COLORREF color )
{
POINT ptsArrow[3];
ptsArrow[0].x = pRect->left;
ptsArrow[0].y = pRect->top;
ptsArrow[1].x = pRect->right;
ptsArrow[1].y = pRect->top;
ptsArrow[2].x = (pRect->left + pRect->right)/2;
ptsArrow[2].y = pRect->bottom;
HBRUSH arrowBrush = CreateSolidBrush ( color );
HPEN arrowPen = CreatePen ( PS_SOLID, 1, color );
HGDIOBJ oldBrush = SelectObject ( hDC, arrowBrush );
HGDIOBJ oldPen = SelectObject ( hDC, arrowPen );
SetPolyFillMode(hDC, WINDING);
Polygon(hDC, ptsArrow, 3);
SelectObject ( hDC, oldBrush );
SelectObject ( hDC, oldPen );
DeleteObject ( arrowBrush );
DeleteObject ( arrowPen );
}
/*
================
ColorButton_DrawItem
Draws the actual color button as as reponse to a WM_DRAWITEM message
================
*/
void ColorButton_DrawItem ( HWND hWnd, LPDRAWITEMSTRUCT dis )
{
assert ( dis );
HDC hDC = dis->hDC;
UINT state = dis->itemState;
RECT rDraw = dis->rcItem;
RECT rArrow;
// Draw outter edge
UINT uFrameState = DFCS_BUTTONPUSH|DFCS_ADJUSTRECT;
if (state & ODS_SELECTED)
{
uFrameState |= DFCS_PUSHED;
}
if (state & ODS_DISABLED)
{
uFrameState |= DFCS_INACTIVE;
}
DrawFrameControl ( hDC, &rDraw, DFC_BUTTON, uFrameState );
// Draw Focus
if (state & ODS_SELECTED)
{
OffsetRect(&rDraw, 1,1);
}
if (state & ODS_FOCUS)
{
RECT rFocus = {rDraw.left,
rDraw.top,
rDraw.right - 1,
rDraw.bottom};
DrawFocusRect ( hDC, &rFocus );
}
InflateRect ( &rDraw, -GetSystemMetrics(SM_CXEDGE), -GetSystemMetrics(SM_CYEDGE) );
// Draw the arrow
rArrow.left = rDraw.right - ARROW_SIZE_CX - GetSystemMetrics(SM_CXEDGE) /2;
rArrow.right = rArrow.left + ARROW_SIZE_CX;
rArrow.top = (rDraw.bottom + rDraw.top)/2 - ARROW_SIZE_CY / 2;
rArrow.bottom = (rDraw.bottom + rDraw.top)/2 + ARROW_SIZE_CY / 2;
ColorButton_DrawArrow ( hDC, &rArrow, (state & ODS_DISABLED) ? ::GetSysColor(COLOR_GRAYTEXT) : RGB(0,0,0) );
rDraw.right = rArrow.left - GetSystemMetrics(SM_CXEDGE)/2;
// Draw separator
DrawEdge ( hDC, &rDraw, EDGE_ETCHED, BF_RIGHT);
rDraw.right -= (GetSystemMetrics(SM_CXEDGE) * 2) + 1 ;
// Draw Color
if ((state & ODS_DISABLED) == 0)
{
HBRUSH color = CreateSolidBrush ( (COLORREF)GetWindowLong ( hWnd, GWL_USERDATA ) );
FillRect ( hDC, &rDraw, color );
FrameRect ( hDC, &rDraw, (HBRUSH)::GetStockObject(BLACK_BRUSH));
DeleteObject( color );
}
}
| anonreclaimer/morpheus | neo/tools/common/ColorButton.cpp | C++ | gpl-3.0 | 5,304 |
<?php
// Heading
$_['heading_title'] = 'Layouts';
// Text
$_['text_success'] = 'Success: You have modified layouts!';
$_['text_list'] = 'Layout List';
$_['text_add'] = 'Add Layout';
$_['text_edit'] = 'Edit Layout';
$_['text_default'] = 'Default';
$_['text_content_top'] = 'Content Top';
$_['text_content_bottom'] = 'Content Bottom';
$_['text_header_background'] = 'Header Background';
$_['text_column_left'] = 'Column Left';
$_['text_column_right'] = 'Column Right';
// Column
$_['column_name'] = 'Layout Name';
$_['column_action'] = 'Action';
// Entry
$_['entry_name'] = 'Layout Name';
$_['entry_store'] = 'Store';
$_['entry_route'] = 'Route';
$_['entry_module'] = 'Module';
$_['entry_position'] = 'Position';
$_['entry_sort_order'] = 'Sort Order';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify layouts!';
$_['error_name'] = 'Layout Name must be between 3 and 64 characters!';
$_['error_default'] = 'Warning: This layout cannot be deleted as it is currently assigned as the default store layout!';
$_['error_store'] = 'Warning: This layout cannot be deleted as it is currently assigned to %s stores!';
$_['error_product'] = 'Warning: This layout cannot be deleted as it is currently assigned to %s products!';
$_['error_category'] = 'Warning: This layout cannot be deleted as it is currently assigned to %s categories!';
$_['error_information'] = 'Warning: This layout cannot be deleted as it is currently assigned to %s information pages!'; | shanksimi/opencart.vn | upload/admin/language/english/design/layout.php | PHP | gpl-3.0 | 1,633 |
package com.epam.gepard.gherkin.jbehave.helper;
/*==========================================================================
Copyright 2004-2015 EPAM Systems
This file is part of Gepard.
Gepard is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gepard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gepard. If not, see <http://www.gnu.org/licenses/>.
===========================================================================*/
import java.io.IOException;
import java.io.InputStream;
/**
* Wrapper for org.apache.commons.io.IOUtils.
* @author Adam_Csaba_Kiraly
*/
public class IOUtils {
/**
* Get the contents of an InputStream as a String using the default character encoding of the platform.
* This method buffers the input internally, so there is no need to use a BufferedInputStream.
* @param inputStream the InputStream to read from
* @return the contents of the inputStream
* @throws IOException - if an I/O error occurs
*/
public String toString(final InputStream inputStream) throws IOException {
return org.apache.commons.io.IOUtils.toString(inputStream);
}
}
| epam/Gepard | gepard-gherkin-jbehave/src/main/java/com/epam/gepard/gherkin/jbehave/helper/IOUtils.java | Java | gpl-3.0 | 1,559 |
package com.xebia.assesment.dto.impl;
import com.xebia.assesment.dto.Observer;
import com.xebia.assesment.dto.Subject;
import com.xebia.assesment.utils.RobotConstants;
import java.util.ArrayList;
/**
* @author Shivansh Sharma
* This class is responsible for managing the operation/events performed by robots
*/
public class Robot implements Subject
{
// Predefined max strength of robot
private static final Double MAX_ROBOT_STRENGTH = 5.0;
// Predefined max load threshold attain by robot
private static final Double MAX_ROBOT_LOAD_THRESHOLD = 10.0;
private static boolean OVERWEIGHT_INDICATOR = false;
private static boolean LOW_BATTERY = false;
private ArrayList<Observer> observers = new ArrayList<Observer>();
private Double strength;
private Double load;
String consumptionMsg;
public Robot(Double aStrength, Double aLoad, String aConsumptionMsg)
{
super();
strength = aStrength;
load = aLoad;
consumptionMsg = aConsumptionMsg;
}
/**
* Calculate the Capacity & efficiency of the robot based on the activity performed by it.
*/
public void consumption()
{
try
{
double unitPercentileStrength = strength / MAX_ROBOT_STRENGTH;
for (Observer ob : observers)
{
// System.out.println("Distance " + ob.getDistanceInput());
// System.out.println("Weight " + ob.getWeightInput());
double distance = ob.getDistanceInput();
double weight = ob.getWeightInput();
if (null != ob.getDistanceInput() && null != ob.getWeightInput())
{
if (distance != 0.0)
{
double result = unitPercentileStrength * distance;
strength = strength - result;
if (strength <= 15.0)
{
LOW_BATTERY = true;
}
}
if (weight > 10.0 && !LOW_BATTERY)
{
OVERWEIGHT_INDICATOR = true;
}
else
{
strength = strength - (2 * weight);
}
notifyObservers(ob, strength.toString(), LOW_BATTERY, OVERWEIGHT_INDICATOR);
// System.out.println("Result" + strength);
}
// ob.getMessages(this.consumptionMsg);
strength = 100.0;
LOW_BATTERY = false;
OVERWEIGHT_INDICATOR = false;
}
}
catch (Exception e)
{
System.out.println(RobotConstants.INPUT_NAN_KEY);
}
}
/**
* @return the observers
*/
public ArrayList<Observer> getObservers()
{
return observers;
}
/**
* @param aObservers the observers to set
*/
public void setObservers(ArrayList<Observer> aObservers)
{
observers = aObservers;
}
/**
* @return the strength
*/
public Double getStrength()
{
return strength;
}
/**
* @param aStrength the strength to set
*/
public void setStrength(Double aStrength)
{
strength = aStrength;
}
/**
* @return the load
*/
public Double getLoad()
{
return load;
}
/**
* @param aLoad the load to set
*/
public void setLoad(Double aLoad)
{
load = aLoad;
}
/**
* @return the consumptionMsg
*/
public String getConsumptionMsg()
{
return consumptionMsg;
}
/**
* @param aConsumptionMsg the consumptionMsg to set
*/
public void setConsumptionMsg(String aConsumptionMsg)
{
consumptionMsg = aConsumptionMsg;
// notifyObservers();
}
@Override
public void registerObserver(Observer aObserver)
{
observers.add(aObserver);
}
@Override
public void removeObserver(Observer aObserver)
{
observers.remove(aObserver);
}
/**
* Notifying to all the subscribers and publish the messages
*/
@Override
public String notifyObservers(Observer ob, String msg, boolean lb, boolean ow)
{
if (lb)
{
ob.getMessages(RobotConstants.LOW_BATTERY);
}
if (ow)
{
ob.getMessages(RobotConstants.OVER_WEIGHT);
}
if (!lb && !ow)
{
ob.getMessages(msg);
}
return msg;
}
}
| risingshivansh/robotics | portlet/Robotics-Portlet-portlet/docroot/WEB-INF/src/com/xebia/assesment/dto/impl/Robot.java | Java | gpl-3.0 | 4,881 |
/*
* Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1.
* Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2.
*
* This file is part of GOOL.
*
* GOOL is free software: you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation, version 3.
*
* GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License version 3 for more details.
*
* You should have received a copy of the GNU General Public License along with GOOL,
* in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>.
*/
package gool.generator.objc;
import gool.executor.common.SpecificCompiler;
import gool.executor.objc.ObjcCompiler;
import gool.generator.common.CodePrinter;
import gool.generator.common.Platform;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
public class ObjcPlatform extends Platform {
/**
* Name of the directory where the ouput files will be written in.
*/
protected static String outputDir;
public String getOutputDir() {
return outputDir;
}
protected ObjcPlatform(Collection<File> myFile, String outDir) {
super("OBJC", myFile);
if (outDir == null)
outputDir = "";
else
outputDir = outDir;
}
@Override
protected CodePrinter initializeCodeWriter() {
return new ObjcCodePrinter(new File(outputDir), myFileToCopy);
}
@Override
protected SpecificCompiler initializeCompiler() {
return new ObjcCompiler(new File(outputDir), new ArrayList<File>());
}
private static ObjcPlatform instance = new ObjcPlatform(myFileToCopy, outputDir);
public static ObjcPlatform getInstance(Collection<File> myF, String outDir) {
if (myF == null) {
myFileToCopy = new ArrayList<File>();
}
else{
myFileToCopy = myF;
}
if (outDir == null){
outputDir = "";
}
else{
outputDir = outDir;
}
return instance;
}
public static ObjcPlatform getInstance(Collection<File> myF) {
return getInstance(myF, outputDir);
}
public static ObjcPlatform getInstance(String outDir) {
return getInstance(myFileToCopy, outDir);
}
public static ObjcPlatform getInstance() {
if (myFileToCopy == null) {
myFileToCopy = new ArrayList<File>();
}
if (outputDir == null){
outputDir = "";
}
return instance;
}
public static void newInstance() {
instance = new ObjcPlatform(myFileToCopy, outputDir);
}
} | darrivau/GOOL | src/main/java/gool/generator/objc/ObjcPlatform.java | Java | gpl-3.0 | 2,582 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | cfMesh: A library for mesh generation
\\ / O peration |
\\ / A nd | Author: Franjo Juretic (franjo.juretic@c-fields.com)
\\/ M anipulation | Copyright (C) Creative Fields, Ltd.
-------------------------------------------------------------------------------
License
This file is part of cfMesh.
cfMesh is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
cfMesh is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with cfMesh. If not, see <http://www.gnu.org/licenses/>.
Class
checkMeshDict
Description
Check whether the meshDict file is set correctly
SourceFiles
checkMeshDict.C
\*---------------------------------------------------------------------------*/
#ifndef checkMeshDict_H
#define checkMeshDict_H
#include "IOdictionary.H"
#include <map>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class checkMeshDict Declaration
\*---------------------------------------------------------------------------*/
class checkMeshDict
{
//- Reference to the mesh
IOdictionary& meshDict_;
// Private member functions
//- check patchCellSize entry
void checkPatchCellSize() const;
//- check subsetCellSize entry
void checkSubsetCellSize() const;
//- check local refinement level
void checkLocalRefinementLevel() const;
//- check keepCellsIntersectingPatches entry
void checkKeepCellsIntersectingPatches() const;
//- check removeCellsIntersectingPatches entry
void checkRemoveCellsIntersectingPatches() const;
//- check objectRefinements entry
void checkObjectRefinements() const;
//- check entry for boundary layers
void checkBoundaryLayers() const;
//- check renameBoundary entry
void checkRenameBoundary() const;
//- perform all checks
void checkEntries() const;
//- update patchCellSize entry
void updatePatchCellSize(const std::map<word, wordList>&);
//- update subsetCellSize entry
void updateSubsetCellSize(const std::map<word, wordList>&);
//- update local refinement
void updateLocalRefinementLevel(const std::map<word, wordList>&);
//- check keepCellsIntersectingPatches entry
void updateKeepCellsIntersectingPatches
(
const std::map<word, wordList>&
);
//- check removeCellsIntersectingPatches entry
void updateRemoveCellsIntersectingPatches
(
const std::map<word, wordList>&
);
//- check objectRefinements entry
void updateObjectRefinements(const std::map<word, wordList>&);
//- check entry for boundary layers
void updateBoundaryLayers(const std::map<word, wordList>&);
//- check renameBoundary entry
void updateRenameBoundary
(
const std::map<word, wordList>&,
const std::map<word, word>&
);
public:
// Constructors
//- Construct from IOdictionary
checkMeshDict(IOdictionary& meshDict);
// Destructor
~checkMeshDict();
// Public member functions
//- update meshDict based on modification of patches in the surface
void updateDictionaries
(
const std::map<word, wordList>& patchesForPatch,
const std::map<word, word>& patchTypes,
const bool renamePatches = true
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| wyldckat/cfMesh | meshLibrary/utilities/checkMeshDict/checkMeshDict.H | C++ | gpl-3.0 | 4,486 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'hue-gui.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1161, 620)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.channel1Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel1Check.setGeometry(QtCore.QRect(10, 10, 161, 17))
self.channel1Check.setChecked(True)
self.channel1Check.setObjectName("channel1Check")
self.channel2Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel2Check.setGeometry(QtCore.QRect(10, 30, 151, 17))
self.channel2Check.setChecked(True)
self.channel2Check.setObjectName("channel2Check")
self.modeWidget = QtWidgets.QTabWidget(self.centralwidget)
self.modeWidget.setGeometry(QtCore.QRect(10, 60, 1131, 451))
self.modeWidget.setObjectName("modeWidget")
self.presetTab = QtWidgets.QWidget()
self.presetTab.setObjectName("presetTab")
self.presetModeWidget = QtWidgets.QTabWidget(self.presetTab)
self.presetModeWidget.setGeometry(QtCore.QRect(6, 10, 1101, 411))
self.presetModeWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.presetModeWidget.setObjectName("presetModeWidget")
self.fixedTab = QtWidgets.QWidget()
self.fixedTab.setObjectName("fixedTab")
self.groupBox = QtWidgets.QGroupBox(self.fixedTab)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox.setObjectName("groupBox")
self.fixedList = QtWidgets.QListWidget(self.groupBox)
self.fixedList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fixedList.setObjectName("fixedList")
self.fixedAdd = QtWidgets.QPushButton(self.groupBox)
self.fixedAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fixedAdd.setObjectName("fixedAdd")
self.fixedDelete = QtWidgets.QPushButton(self.groupBox)
self.fixedDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fixedDelete.setObjectName("fixedDelete")
self.presetModeWidget.addTab(self.fixedTab, "")
self.breathingTab = QtWidgets.QWidget()
self.breathingTab.setObjectName("breathingTab")
self.groupBox_2 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_2.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_2.setObjectName("groupBox_2")
self.breathingList = QtWidgets.QListWidget(self.groupBox_2)
self.breathingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.breathingList.setObjectName("breathingList")
self.breathingAdd = QtWidgets.QPushButton(self.groupBox_2)
self.breathingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.breathingAdd.setObjectName("breathingAdd")
self.breathingDelete = QtWidgets.QPushButton(self.groupBox_2)
self.breathingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.breathingDelete.setObjectName("breathingDelete")
self.groupBox_11 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_11.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_11.setObjectName("groupBox_11")
self.breathingSpeed = QtWidgets.QSlider(self.groupBox_11)
self.breathingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.breathingSpeed.setMaximum(4)
self.breathingSpeed.setProperty("value", 2)
self.breathingSpeed.setOrientation(QtCore.Qt.Vertical)
self.breathingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.breathingSpeed.setObjectName("breathingSpeed")
self.label_2 = QtWidgets.QLabel(self.groupBox_11)
self.label_2.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_2.setObjectName("label_2")
self.label_4 = QtWidgets.QLabel(self.groupBox_11)
self.label_4.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.groupBox_11)
self.label_5.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_5.setObjectName("label_5")
self.presetModeWidget.addTab(self.breathingTab, "")
self.fadingTab = QtWidgets.QWidget()
self.fadingTab.setObjectName("fadingTab")
self.groupBox_3 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_3.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_3.setObjectName("groupBox_3")
self.fadingList = QtWidgets.QListWidget(self.groupBox_3)
self.fadingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fadingList.setObjectName("fadingList")
self.fadingAdd = QtWidgets.QPushButton(self.groupBox_3)
self.fadingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fadingAdd.setObjectName("fadingAdd")
self.fadingDelete = QtWidgets.QPushButton(self.groupBox_3)
self.fadingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fadingDelete.setObjectName("fadingDelete")
self.groupBox_12 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_12.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_12.setObjectName("groupBox_12")
self.fadingSpeed = QtWidgets.QSlider(self.groupBox_12)
self.fadingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.fadingSpeed.setMaximum(4)
self.fadingSpeed.setProperty("value", 2)
self.fadingSpeed.setOrientation(QtCore.Qt.Vertical)
self.fadingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.fadingSpeed.setObjectName("fadingSpeed")
self.label_9 = QtWidgets.QLabel(self.groupBox_12)
self.label_9.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_9.setObjectName("label_9")
self.label_10 = QtWidgets.QLabel(self.groupBox_12)
self.label_10.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_10.setObjectName("label_10")
self.label_11 = QtWidgets.QLabel(self.groupBox_12)
self.label_11.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_11.setObjectName("label_11")
self.presetModeWidget.addTab(self.fadingTab, "")
self.marqueeTab = QtWidgets.QWidget()
self.marqueeTab.setObjectName("marqueeTab")
self.groupBox_4 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_4.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_4.setObjectName("groupBox_4")
self.marqueeList = QtWidgets.QListWidget(self.groupBox_4)
self.marqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.marqueeList.setObjectName("marqueeList")
self.marqueeAdd = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.marqueeAdd.setObjectName("marqueeAdd")
self.marqueeDelete = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.marqueeDelete.setObjectName("marqueeDelete")
self.groupBox_13 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_13.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_13.setObjectName("groupBox_13")
self.marqueeSpeed = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.marqueeSpeed.setMaximum(4)
self.marqueeSpeed.setProperty("value", 2)
self.marqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.marqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSpeed.setObjectName("marqueeSpeed")
self.label_15 = QtWidgets.QLabel(self.groupBox_13)
self.label_15.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_15.setObjectName("label_15")
self.label_16 = QtWidgets.QLabel(self.groupBox_13)
self.label_16.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.groupBox_13)
self.label_17.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_17.setObjectName("label_17")
self.marqueeSize = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.marqueeSize.setMaximum(3)
self.marqueeSize.setProperty("value", 2)
self.marqueeSize.setOrientation(QtCore.Qt.Vertical)
self.marqueeSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSize.setObjectName("marqueeSize")
self.label_18 = QtWidgets.QLabel(self.groupBox_13)
self.label_18.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_18.setObjectName("label_18")
self.label_19 = QtWidgets.QLabel(self.groupBox_13)
self.label_19.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_19.setObjectName("label_19")
self.label_20 = QtWidgets.QLabel(self.groupBox_13)
self.label_20.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_20.setObjectName("label_20")
self.marqueeBackwards = QtWidgets.QCheckBox(self.groupBox_13)
self.marqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.marqueeBackwards.setObjectName("marqueeBackwards")
self.presetModeWidget.addTab(self.marqueeTab, "")
self.coverMarqueeTab = QtWidgets.QWidget()
self.coverMarqueeTab.setObjectName("coverMarqueeTab")
self.groupBox_5 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_5.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_5.setObjectName("groupBox_5")
self.coverMarqueeList = QtWidgets.QListWidget(self.groupBox_5)
self.coverMarqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.coverMarqueeList.setObjectName("coverMarqueeList")
self.coverMarqueeAdd = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.coverMarqueeAdd.setObjectName("coverMarqueeAdd")
self.coverMarqueeDelete = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.coverMarqueeDelete.setObjectName("coverMarqueeDelete")
self.groupBox_15 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_15.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_15.setObjectName("groupBox_15")
self.coverMarqueeSpeed = QtWidgets.QSlider(self.groupBox_15)
self.coverMarqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.coverMarqueeSpeed.setMaximum(4)
self.coverMarqueeSpeed.setProperty("value", 2)
self.coverMarqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.coverMarqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.coverMarqueeSpeed.setObjectName("coverMarqueeSpeed")
self.label_27 = QtWidgets.QLabel(self.groupBox_15)
self.label_27.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_27.setObjectName("label_27")
self.label_28 = QtWidgets.QLabel(self.groupBox_15)
self.label_28.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_28.setObjectName("label_28")
self.label_29 = QtWidgets.QLabel(self.groupBox_15)
self.label_29.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_29.setObjectName("label_29")
self.coverMarqueeBackwards = QtWidgets.QCheckBox(self.groupBox_15)
self.coverMarqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.coverMarqueeBackwards.setObjectName("coverMarqueeBackwards")
self.presetModeWidget.addTab(self.coverMarqueeTab, "")
self.pulseTab = QtWidgets.QWidget()
self.pulseTab.setObjectName("pulseTab")
self.groupBox_6 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_6.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_6.setObjectName("groupBox_6")
self.pulseList = QtWidgets.QListWidget(self.groupBox_6)
self.pulseList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.pulseList.setObjectName("pulseList")
self.pulseAdd = QtWidgets.QPushButton(self.groupBox_6)
self.pulseAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.pulseAdd.setObjectName("pulseAdd")
self.pulseDelete = QtWidgets.QPushButton(self.groupBox_6)
self.pulseDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.pulseDelete.setObjectName("pulseDelete")
self.groupBox_16 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_16.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_16.setObjectName("groupBox_16")
self.pulseSpeed = QtWidgets.QSlider(self.groupBox_16)
self.pulseSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.pulseSpeed.setMaximum(4)
self.pulseSpeed.setProperty("value", 2)
self.pulseSpeed.setOrientation(QtCore.Qt.Vertical)
self.pulseSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.pulseSpeed.setObjectName("pulseSpeed")
self.label_33 = QtWidgets.QLabel(self.groupBox_16)
self.label_33.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_33.setObjectName("label_33")
self.label_34 = QtWidgets.QLabel(self.groupBox_16)
self.label_34.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_34.setObjectName("label_34")
self.label_35 = QtWidgets.QLabel(self.groupBox_16)
self.label_35.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_35.setObjectName("label_35")
self.presetModeWidget.addTab(self.pulseTab, "")
self.spectrumTab = QtWidgets.QWidget()
self.spectrumTab.setObjectName("spectrumTab")
self.groupBox_17 = QtWidgets.QGroupBox(self.spectrumTab)
self.groupBox_17.setGeometry(QtCore.QRect(0, 0, 321, 361))
self.groupBox_17.setObjectName("groupBox_17")
self.spectrumSpeed = QtWidgets.QSlider(self.groupBox_17)
self.spectrumSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.spectrumSpeed.setMaximum(4)
self.spectrumSpeed.setProperty("value", 2)
self.spectrumSpeed.setOrientation(QtCore.Qt.Vertical)
self.spectrumSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.spectrumSpeed.setObjectName("spectrumSpeed")
self.label_39 = QtWidgets.QLabel(self.groupBox_17)
self.label_39.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_39.setObjectName("label_39")
self.label_40 = QtWidgets.QLabel(self.groupBox_17)
self.label_40.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_40.setObjectName("label_40")
self.label_41 = QtWidgets.QLabel(self.groupBox_17)
self.label_41.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_41.setObjectName("label_41")
self.spectrumBackwards = QtWidgets.QCheckBox(self.groupBox_17)
self.spectrumBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.spectrumBackwards.setObjectName("spectrumBackwards")
self.presetModeWidget.addTab(self.spectrumTab, "")
self.alternatingTab = QtWidgets.QWidget()
self.alternatingTab.setObjectName("alternatingTab")
self.groupBox_7 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_7.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_7.setObjectName("groupBox_7")
self.alternatingList = QtWidgets.QListWidget(self.groupBox_7)
self.alternatingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.alternatingList.setObjectName("alternatingList")
self.alternatingAdd = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.alternatingAdd.setObjectName("alternatingAdd")
self.alternatingDelete = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.alternatingDelete.setObjectName("alternatingDelete")
self.groupBox_18 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_18.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_18.setObjectName("groupBox_18")
self.alternatingSpeed = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.alternatingSpeed.setMaximum(4)
self.alternatingSpeed.setProperty("value", 2)
self.alternatingSpeed.setOrientation(QtCore.Qt.Vertical)
self.alternatingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSpeed.setObjectName("alternatingSpeed")
self.label_45 = QtWidgets.QLabel(self.groupBox_18)
self.label_45.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_45.setObjectName("label_45")
self.label_46 = QtWidgets.QLabel(self.groupBox_18)
self.label_46.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_46.setObjectName("label_46")
self.label_47 = QtWidgets.QLabel(self.groupBox_18)
self.label_47.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_47.setObjectName("label_47")
self.alternatingSize = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.alternatingSize.setMaximum(3)
self.alternatingSize.setProperty("value", 2)
self.alternatingSize.setOrientation(QtCore.Qt.Vertical)
self.alternatingSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSize.setObjectName("alternatingSize")
self.label_48 = QtWidgets.QLabel(self.groupBox_18)
self.label_48.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_48.setObjectName("label_48")
self.label_49 = QtWidgets.QLabel(self.groupBox_18)
self.label_49.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_49.setObjectName("label_49")
self.label_50 = QtWidgets.QLabel(self.groupBox_18)
self.label_50.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_50.setObjectName("label_50")
self.alternatingBackwards = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.alternatingBackwards.setObjectName("alternatingBackwards")
self.alternatingMoving = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingMoving.setGeometry(QtCore.QRect(20, 290, 89, 26))
self.alternatingMoving.setObjectName("alternatingMoving")
self.presetModeWidget.addTab(self.alternatingTab, "")
self.candleTab = QtWidgets.QWidget()
self.candleTab.setObjectName("candleTab")
self.groupBox_8 = QtWidgets.QGroupBox(self.candleTab)
self.groupBox_8.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_8.setObjectName("groupBox_8")
self.candleList = QtWidgets.QListWidget(self.groupBox_8)
self.candleList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.candleList.setObjectName("candleList")
self.candleAdd = QtWidgets.QPushButton(self.groupBox_8)
self.candleAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.candleAdd.setObjectName("candleAdd")
self.candleDelete = QtWidgets.QPushButton(self.groupBox_8)
self.candleDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.candleDelete.setObjectName("candleDelete")
self.presetModeWidget.addTab(self.candleTab, "")
self.wingsTab = QtWidgets.QWidget()
self.wingsTab.setObjectName("wingsTab")
self.groupBox_9 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_9.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_9.setObjectName("groupBox_9")
self.wingsList = QtWidgets.QListWidget(self.groupBox_9)
self.wingsList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.wingsList.setObjectName("wingsList")
self.wingsAdd = QtWidgets.QPushButton(self.groupBox_9)
self.wingsAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.wingsAdd.setObjectName("wingsAdd")
self.wingsDelete = QtWidgets.QPushButton(self.groupBox_9)
self.wingsDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.wingsDelete.setObjectName("wingsDelete")
self.groupBox_20 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_20.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_20.setObjectName("groupBox_20")
self.wingsSpeed = QtWidgets.QSlider(self.groupBox_20)
self.wingsSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.wingsSpeed.setMaximum(4)
self.wingsSpeed.setProperty("value", 2)
self.wingsSpeed.setOrientation(QtCore.Qt.Vertical)
self.wingsSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.wingsSpeed.setObjectName("wingsSpeed")
self.label_57 = QtWidgets.QLabel(self.groupBox_20)
self.label_57.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_57.setObjectName("label_57")
self.label_58 = QtWidgets.QLabel(self.groupBox_20)
self.label_58.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_58.setObjectName("label_58")
self.label_59 = QtWidgets.QLabel(self.groupBox_20)
self.label_59.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_59.setObjectName("label_59")
self.presetModeWidget.addTab(self.wingsTab, "")
self.audioLevelTab = QtWidgets.QWidget()
self.audioLevelTab.setObjectName("audioLevelTab")
self.groupBox_21 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_21.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_21.setObjectName("groupBox_21")
self.label_60 = QtWidgets.QLabel(self.groupBox_21)
self.label_60.setGeometry(QtCore.QRect(10, 30, 62, 20))
self.label_60.setObjectName("label_60")
self.label_61 = QtWidgets.QLabel(self.groupBox_21)
self.label_61.setGeometry(QtCore.QRect(10, 80, 81, 20))
self.label_61.setObjectName("label_61")
self.audioLevelTolerance = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelTolerance.setGeometry(QtCore.QRect(10, 50, 68, 23))
self.audioLevelTolerance.setDecimals(1)
self.audioLevelTolerance.setProperty("value", 1.0)
self.audioLevelTolerance.setObjectName("audioLevelTolerance")
self.audioLevelSmooth = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelSmooth.setGeometry(QtCore.QRect(10, 100, 68, 23))
self.audioLevelSmooth.setDecimals(0)
self.audioLevelSmooth.setProperty("value", 3.0)
self.audioLevelSmooth.setObjectName("audioLevelSmooth")
self.groupBox_10 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_10.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_10.setObjectName("groupBox_10")
self.audioLevelList = QtWidgets.QListWidget(self.groupBox_10)
self.audioLevelList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.audioLevelList.setObjectName("audioLevelList")
self.audioLevelAdd = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.audioLevelAdd.setObjectName("audioLevelAdd")
self.audioLevelDelete = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.audioLevelDelete.setObjectName("audioLevelDelete")
self.presetModeWidget.addTab(self.audioLevelTab, "")
self.customTab = QtWidgets.QWidget()
self.customTab.setObjectName("customTab")
self.groupBox_22 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_22.setGeometry(QtCore.QRect(630, 0, 321, 371))
self.groupBox_22.setObjectName("groupBox_22")
self.customSpeed = QtWidgets.QSlider(self.groupBox_22)
self.customSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.customSpeed.setMaximum(4)
self.customSpeed.setProperty("value", 2)
self.customSpeed.setOrientation(QtCore.Qt.Vertical)
self.customSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.customSpeed.setObjectName("customSpeed")
self.label_62 = QtWidgets.QLabel(self.groupBox_22)
self.label_62.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_62.setObjectName("label_62")
self.label_63 = QtWidgets.QLabel(self.groupBox_22)
self.label_63.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_63.setObjectName("label_63")
self.label_64 = QtWidgets.QLabel(self.groupBox_22)
self.label_64.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_64.setObjectName("label_64")
self.customMode = QtWidgets.QComboBox(self.groupBox_22)
self.customMode.setGeometry(QtCore.QRect(190, 70, 86, 25))
self.customMode.setObjectName("customMode")
self.customMode.addItem("")
self.customMode.addItem("")
self.customMode.addItem("")
self.label_65 = QtWidgets.QLabel(self.groupBox_22)
self.label_65.setGeometry(QtCore.QRect(190, 40, 62, 20))
self.label_65.setObjectName("label_65")
self.groupBox_19 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_19.setGeometry(QtCore.QRect(0, 0, 611, 371))
self.groupBox_19.setObjectName("groupBox_19")
self.customTable = QtWidgets.QTableWidget(self.groupBox_19)
self.customTable.setGeometry(QtCore.QRect(10, 30, 471, 331))
self.customTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.customTable.setDragDropOverwriteMode(False)
self.customTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.customTable.setRowCount(40)
self.customTable.setColumnCount(2)
self.customTable.setObjectName("customTable")
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(1, item)
self.customTable.verticalHeader().setVisible(False)
self.customEdit = QtWidgets.QPushButton(self.groupBox_19)
self.customEdit.setGeometry(QtCore.QRect(500, 40, 83, 28))
self.customEdit.setObjectName("customEdit")
self.presetModeWidget.addTab(self.customTab, "")
self.profileTab = QtWidgets.QWidget()
self.profileTab.setObjectName("profileTab")
self.groupBox_14 = QtWidgets.QGroupBox(self.profileTab)
self.groupBox_14.setGeometry(QtCore.QRect(0, 0, 421, 361))
self.groupBox_14.setObjectName("groupBox_14")
self.profileList = QtWidgets.QListWidget(self.groupBox_14)
self.profileList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.profileList.setObjectName("profileList")
self.profileAdd = QtWidgets.QPushButton(self.groupBox_14)
self.profileAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.profileAdd.setObjectName("profileAdd")
self.profileDelete = QtWidgets.QPushButton(self.groupBox_14)
self.profileDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.profileDelete.setObjectName("profileDelete")
self.profileRefresh = QtWidgets.QPushButton(self.groupBox_14)
self.profileRefresh.setGeometry(QtCore.QRect(130, 130, 83, 28))
self.profileRefresh.setObjectName("profileRefresh")
self.profileName = QtWidgets.QLineEdit(self.groupBox_14)
self.profileName.setGeometry(QtCore.QRect(300, 50, 113, 28))
self.profileName.setObjectName("profileName")
self.label_3 = QtWidgets.QLabel(self.groupBox_14)
self.label_3.setGeometry(QtCore.QRect(220, 50, 62, 20))
self.label_3.setObjectName("label_3")
self.presetModeWidget.addTab(self.profileTab, "")
self.animatedTab = QtWidgets.QWidget()
self.animatedTab.setObjectName("animatedTab")
self.groupBox_23 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_23.setGeometry(QtCore.QRect(0, 0, 721, 371))
self.groupBox_23.setObjectName("groupBox_23")
self.animatedTable = QtWidgets.QTableWidget(self.groupBox_23)
self.animatedTable.setGeometry(QtCore.QRect(230, 30, 361, 331))
self.animatedTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.animatedTable.setDragDropOverwriteMode(False)
self.animatedTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.animatedTable.setRowCount(40)
self.animatedTable.setColumnCount(2)
self.animatedTable.setObjectName("animatedTable")
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(1, item)
self.animatedTable.verticalHeader().setVisible(False)
self.animatedEdit = QtWidgets.QPushButton(self.groupBox_23)
self.animatedEdit.setGeometry(QtCore.QRect(610, 40, 83, 28))
self.animatedEdit.setObjectName("animatedEdit")
self.animatedList = QtWidgets.QListWidget(self.groupBox_23)
self.animatedList.setGeometry(QtCore.QRect(10, 40, 111, 291))
self.animatedList.setObjectName("animatedList")
self.animatedDelete = QtWidgets.QPushButton(self.groupBox_23)
self.animatedDelete.setGeometry(QtCore.QRect(130, 80, 83, 28))
self.animatedDelete.setObjectName("animatedDelete")
self.animatedAdd = QtWidgets.QPushButton(self.groupBox_23)
self.animatedAdd.setGeometry(QtCore.QRect(130, 40, 83, 28))
self.animatedAdd.setObjectName("animatedAdd")
self.animatedRoundName = QtWidgets.QLineEdit(self.groupBox_23)
self.animatedRoundName.setGeometry(QtCore.QRect(130, 120, 81, 25))
self.animatedRoundName.setObjectName("animatedRoundName")
self.groupBox_24 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_24.setGeometry(QtCore.QRect(740, 0, 331, 371))
self.groupBox_24.setObjectName("groupBox_24")
self.label_66 = QtWidgets.QLabel(self.groupBox_24)
self.label_66.setGeometry(QtCore.QRect(10, 40, 201, 20))
self.label_66.setObjectName("label_66")
self.animatedSpeed = QtWidgets.QDoubleSpinBox(self.groupBox_24)
self.animatedSpeed.setGeometry(QtCore.QRect(10, 70, 68, 26))
self.animatedSpeed.setDecimals(0)
self.animatedSpeed.setMinimum(15.0)
self.animatedSpeed.setMaximum(5000.0)
self.animatedSpeed.setSingleStep(10.0)
self.animatedSpeed.setProperty("value", 50.0)
self.animatedSpeed.setObjectName("animatedSpeed")
self.label_21 = QtWidgets.QLabel(self.groupBox_24)
self.label_21.setGeometry(QtCore.QRect(40, 130, 261, 71))
self.label_21.setWordWrap(True)
self.label_21.setObjectName("label_21")
self.presetModeWidget.addTab(self.animatedTab, "")
self.modeWidget.addTab(self.presetTab, "")
self.timesTab = QtWidgets.QWidget()
self.timesTab.setObjectName("timesTab")
self.label_7 = QtWidgets.QLabel(self.timesTab)
self.label_7.setGeometry(QtCore.QRect(30, 20, 461, 17))
self.label_7.setObjectName("label_7")
self.offTime = QtWidgets.QLineEdit(self.timesTab)
self.offTime.setGeometry(QtCore.QRect(30, 40, 113, 25))
self.offTime.setObjectName("offTime")
self.onTime = QtWidgets.QLineEdit(self.timesTab)
self.onTime.setGeometry(QtCore.QRect(30, 100, 113, 25))
self.onTime.setObjectName("onTime")
self.label_8 = QtWidgets.QLabel(self.timesTab)
self.label_8.setGeometry(QtCore.QRect(30, 80, 461, 17))
self.label_8.setObjectName("label_8")
self.label_12 = QtWidgets.QLabel(self.timesTab)
self.label_12.setGeometry(QtCore.QRect(160, 50, 131, 17))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.timesTab)
self.label_13.setGeometry(QtCore.QRect(160, 110, 131, 17))
self.label_13.setObjectName("label_13")
self.label_14 = QtWidgets.QLabel(self.timesTab)
self.label_14.setGeometry(QtCore.QRect(30, 140, 341, 111))
font = QtGui.QFont()
font.setPointSize(11)
self.label_14.setFont(font)
self.label_14.setWordWrap(True)
self.label_14.setObjectName("label_14")
self.timeSave = QtWidgets.QPushButton(self.timesTab)
self.timeSave.setGeometry(QtCore.QRect(40, 290, 82, 25))
self.timeSave.setObjectName("timeSave")
self.modeWidget.addTab(self.timesTab, "")
self.applyBtn = QtWidgets.QPushButton(self.centralwidget)
self.applyBtn.setGeometry(QtCore.QRect(490, 530, 101, 41))
self.applyBtn.setObjectName("applyBtn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(940, 20, 62, 20))
self.label.setObjectName("label")
self.portTxt = QtWidgets.QLineEdit(self.centralwidget)
self.portTxt.setGeometry(QtCore.QRect(1000, 20, 113, 28))
self.portTxt.setObjectName("portTxt")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(180, -10, 741, 91))
font = QtGui.QFont()
font.setPointSize(13)
self.label_6.setFont(font)
self.label_6.setWordWrap(True)
self.label_6.setObjectName("label_6")
self.unitLEDBtn = QtWidgets.QPushButton(self.centralwidget)
self.unitLEDBtn.setGeometry(QtCore.QRect(840, 50, 121, 21))
self.unitLEDBtn.setObjectName("unitLEDBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.modeWidget.setCurrentIndex(0)
self.presetModeWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.channel1Check, self.channel2Check)
MainWindow.setTabOrder(self.channel2Check, self.modeWidget)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "hue_plus"))
self.channel1Check.setText(_translate("MainWindow", "Channel 1"))
self.channel2Check.setText(_translate("MainWindow", "Channel 2"))
self.groupBox.setTitle(_translate("MainWindow", "Colors"))
self.fixedAdd.setText(_translate("MainWindow", "Add color"))
self.fixedDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fixedTab), _translate("MainWindow", "Fixed"))
self.groupBox_2.setTitle(_translate("MainWindow", "Colors"))
self.breathingAdd.setText(_translate("MainWindow", "Add color"))
self.breathingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_11.setTitle(_translate("MainWindow", "Other"))
self.label_2.setText(_translate("MainWindow", "Speed"))
self.label_4.setText(_translate("MainWindow", "Fastest"))
self.label_5.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.breathingTab), _translate("MainWindow", "Breathing"))
self.groupBox_3.setTitle(_translate("MainWindow", "Colors"))
self.fadingAdd.setText(_translate("MainWindow", "Add color"))
self.fadingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_12.setTitle(_translate("MainWindow", "Other"))
self.label_9.setText(_translate("MainWindow", "Speed"))
self.label_10.setText(_translate("MainWindow", "Fastest"))
self.label_11.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fadingTab), _translate("MainWindow", "Fading"))
self.groupBox_4.setTitle(_translate("MainWindow", "Colors"))
self.marqueeAdd.setText(_translate("MainWindow", "Add color"))
self.marqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_13.setTitle(_translate("MainWindow", "Other"))
self.label_15.setText(_translate("MainWindow", "Speed"))
self.label_16.setText(_translate("MainWindow", "Fastest"))
self.label_17.setText(_translate("MainWindow", "Slowest"))
self.label_18.setText(_translate("MainWindow", "Smaller"))
self.label_19.setText(_translate("MainWindow", "Size"))
self.label_20.setText(_translate("MainWindow", "Larger"))
self.marqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.marqueeTab), _translate("MainWindow", "Marquee"))
self.groupBox_5.setTitle(_translate("MainWindow", "Colors"))
self.coverMarqueeAdd.setText(_translate("MainWindow", "Add color"))
self.coverMarqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_15.setTitle(_translate("MainWindow", "Other"))
self.label_27.setText(_translate("MainWindow", "Speed"))
self.label_28.setText(_translate("MainWindow", "Fastest"))
self.label_29.setText(_translate("MainWindow", "Slowest"))
self.coverMarqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.coverMarqueeTab), _translate("MainWindow", "Covering Marquee"))
self.groupBox_6.setTitle(_translate("MainWindow", "Colors"))
self.pulseAdd.setText(_translate("MainWindow", "Add color"))
self.pulseDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_16.setTitle(_translate("MainWindow", "Other"))
self.label_33.setText(_translate("MainWindow", "Speed"))
self.label_34.setText(_translate("MainWindow", "Fastest"))
self.label_35.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.pulseTab), _translate("MainWindow", "Pulse"))
self.groupBox_17.setTitle(_translate("MainWindow", "Other"))
self.label_39.setText(_translate("MainWindow", "Speed"))
self.label_40.setText(_translate("MainWindow", "Fastest"))
self.label_41.setText(_translate("MainWindow", "Slowest"))
self.spectrumBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.spectrumTab), _translate("MainWindow", "Spectrum"))
self.groupBox_7.setTitle(_translate("MainWindow", "Colors"))
self.alternatingAdd.setText(_translate("MainWindow", "Add color"))
self.alternatingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_18.setTitle(_translate("MainWindow", "Other"))
self.label_45.setText(_translate("MainWindow", "Speed"))
self.label_46.setText(_translate("MainWindow", "Fastest"))
self.label_47.setText(_translate("MainWindow", "Slowest"))
self.label_48.setText(_translate("MainWindow", "Smaller"))
self.label_49.setText(_translate("MainWindow", "Size"))
self.label_50.setText(_translate("MainWindow", "Larger"))
self.alternatingBackwards.setText(_translate("MainWindow", "Backwards"))
self.alternatingMoving.setText(_translate("MainWindow", "Moving"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.alternatingTab), _translate("MainWindow", "Alternating"))
self.groupBox_8.setTitle(_translate("MainWindow", "Colors"))
self.candleAdd.setText(_translate("MainWindow", "Add color"))
self.candleDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.candleTab), _translate("MainWindow", "Candle"))
self.groupBox_9.setTitle(_translate("MainWindow", "Colors"))
self.wingsAdd.setText(_translate("MainWindow", "Add color"))
self.wingsDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_20.setTitle(_translate("MainWindow", "Other"))
self.label_57.setText(_translate("MainWindow", "Speed"))
self.label_58.setText(_translate("MainWindow", "Fastest"))
self.label_59.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.wingsTab), _translate("MainWindow", "Wings"))
self.groupBox_21.setTitle(_translate("MainWindow", "Other"))
self.label_60.setText(_translate("MainWindow", "Tolerance"))
self.label_61.setText(_translate("MainWindow", "Smoothness"))
self.groupBox_10.setTitle(_translate("MainWindow", "Colors"))
self.audioLevelAdd.setText(_translate("MainWindow", "Add color"))
self.audioLevelDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.audioLevelTab), _translate("MainWindow", "Audio Level"))
self.groupBox_22.setTitle(_translate("MainWindow", "Other"))
self.label_62.setText(_translate("MainWindow", "Speed"))
self.label_63.setText(_translate("MainWindow", "Fastest"))
self.label_64.setText(_translate("MainWindow", "Slowest"))
self.customMode.setItemText(0, _translate("MainWindow", "Fixed"))
self.customMode.setItemText(1, _translate("MainWindow", "Breathing"))
self.customMode.setItemText(2, _translate("MainWindow", "Wave"))
self.label_65.setText(_translate("MainWindow", "Mode"))
self.groupBox_19.setTitle(_translate("MainWindow", "Colors"))
item = self.customTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.customTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.customEdit.setText(_translate("MainWindow", "Edit Color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.customTab), _translate("MainWindow", "Custom"))
self.groupBox_14.setTitle(_translate("MainWindow", "Profiles"))
self.profileAdd.setText(_translate("MainWindow", "Add profile"))
self.profileDelete.setText(_translate("MainWindow", "Delete profile"))
self.profileRefresh.setText(_translate("MainWindow", "Refresh"))
self.profileName.setText(_translate("MainWindow", "profile1"))
self.label_3.setText(_translate("MainWindow", "Name:"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.profileTab), _translate("MainWindow", "Profiles"))
self.groupBox_23.setTitle(_translate("MainWindow", "Colors"))
item = self.animatedTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.animatedTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.animatedEdit.setText(_translate("MainWindow", "Edit Color"))
self.animatedDelete.setText(_translate("MainWindow", "Delete round"))
self.animatedAdd.setText(_translate("MainWindow", "Add round"))
self.animatedRoundName.setText(_translate("MainWindow", "round1"))
self.groupBox_24.setTitle(_translate("MainWindow", "Other"))
self.label_66.setText(_translate("MainWindow", "Speed between refresh, in ms"))
self.label_21.setText(_translate("MainWindow", "To use, simply set a custom pattern for each round."))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.animatedTab), _translate("MainWindow", "Custom Animated"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.presetTab), _translate("MainWindow", "Preset"))
self.label_7.setText(_translate("MainWindow", "The time to turn off the lights (in 24 hour time, separated by a colon)"))
self.offTime.setText(_translate("MainWindow", "00:00"))
self.onTime.setText(_translate("MainWindow", "00:00"))
self.label_8.setText(_translate("MainWindow", "The time to turn on the lights (in 24 hour time, separated by a colon)"))
self.label_12.setText(_translate("MainWindow", "00:00 means none"))
self.label_13.setText(_translate("MainWindow", "00:00 means none"))
self.label_14.setText(_translate("MainWindow", "This looks for a profile called previous and uses that. If that profile does not exist, the time will not work."))
self.timeSave.setText(_translate("MainWindow", "Save"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.timesTab), _translate("MainWindow", "Times"))
self.applyBtn.setText(_translate("MainWindow", "Apply"))
self.label.setText(_translate("MainWindow", "Port:"))
self.portTxt.setText(_translate("MainWindow", "/dev/ttyACM0"))
self.label_6.setText(_translate("MainWindow", "Now with support for turning on and off at specific times, audio on Windows, a way to make your own modes, and more!"))
self.unitLEDBtn.setText(_translate("MainWindow", "Toggle Unit LED"))
| kusti8/hue-plus | hue_plus/hue_gui.py | Python | gpl-3.0 | 45,771 |
package cn.wizzer.app.shop.modules.services.impl;
import cn.wizzer.app.shop.modules.models.Shop_order_pay_payment;
import cn.wizzer.app.shop.modules.services.ShopOrderPayPaymentService;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
/**
* Created by wizzer on 2019/6/14
*/
@IocBean(args = {"refer:dao"})
public class ShopOrderPayPaymentServiceImpl extends BaseServiceImpl<Shop_order_pay_payment> implements ShopOrderPayPaymentService {
public ShopOrderPayPaymentServiceImpl(Dao dao) {
super(dao);
}
}
| Wizzercn/NutzShop | src/main/java/cn/wizzer/app/shop/modules/services/impl/ShopOrderPayPaymentServiceImpl.java | Java | gpl-3.0 | 603 |
<table class="fpcm-ui-table">
<tr>
<td><?php $FPCM_LANG->write('FILE_LIST_SMILEYCODE'); ?>:</td>
<td>
<?php \fpcm\model\view\helper::textInput('smiley[code]', '', $smiley->getSmileyCode()); ?>
</td>
</tr>
<tr>
<td><?php $FPCM_LANG->write('FILE_LIST_FILENAME'); ?>:</td>
<td>
<?php \fpcm\model\view\helper::textInput('smiley[filename]', '', $smiley->getFilename()); ?>
</td>
</tr>
</table>
<div class="<?php \fpcm\model\view\helper::buttonsContainerClass(); ?> fpcm-ui-list-buttons">
<div class="fpcm-ui-margin-center">
<?php \fpcm\model\view\helper::saveButton('saveSmiley'); ?>
</div>
</div> | sea75300/fanpresscm3 | core/views/smileys/editor.php | PHP | gpl-3.0 | 748 |
/*
Copyright (C) 2015 RedstoneLamp Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package redstonelamp.entity;
/**
* A Villager
*/
public class Villager extends Entity{
public final static short NETWORK_ID = 15;
public Villager(int id) {
super(id);
}
}
| Creeperface01/RedstoneLamp | src/redstonelamp/entity/Villager.java | Java | gpl-3.0 | 908 |
<?php
use yii\db\Migration;
class m161025_115253_add_permissions extends Migration
{
public function up()
{
$auth = Yii::$app->authManager;
/*Vendor controller*/
$viewVendorList = $auth->createPermission('viewVendorList');
$viewVendorList->description = 'View list of vendors';
$auth->add($viewVendorList);
$saveVendor = $auth->createPermission('saveVendor');
$saveVendor->description = 'Create and edit vendor';
$auth->add($saveVendor);
$deleteVendor = $auth->createPermission('deleteVendor');
$deleteVendor->description = 'Delete vendor';
$auth->add($deleteVendor);
$vendorManager = $auth->createRole('vendorManager');
$vendorManager->description = 'Vendor manager';
$auth->add($vendorManager);
$auth->addChild($vendorManager, $viewVendorList);
$auth->addChild($vendorManager, $saveVendor);
$auth->addChild($vendorManager, $deleteVendor);
/*Product availability controller*/
$viewProductAvailabilityList = $auth->createPermission('viewProductAvailabilityList');
$viewProductAvailabilityList->description = 'View list of product availabilities';
$auth->add($viewProductAvailabilityList);
$saveProductAvailability = $auth->createPermission('saveProductAvailability');
$saveProductAvailability->description = 'Save product availability';
$auth->add($saveProductAvailability);
$deleteProductAvailability = $auth->createPermission('deleteProductAvailability');
$deleteProductAvailability->description = 'Delete product availability';
$auth->add($deleteProductAvailability);
$productAvailabilityManager = $auth->createRole('productAvailabilityManager');
$productAvailabilityManager->description = 'Product availability manager';
$auth->add($productAvailabilityManager);
$auth->addChild($productAvailabilityManager, $viewProductAvailabilityList);
$auth->addChild($productAvailabilityManager, $saveProductAvailability);
$auth->addChild($productAvailabilityManager, $deleteProductAvailability);
/*PartnersController*/
$viewPartnerRequest = $auth->createPermission('viewPartnerRequest');
$viewPartnerRequest->description = 'View partner request';
$auth->add($viewPartnerRequest);
$deletePartnerRequest = $auth->createPermission('deletePartnerRequest');
$deletePartnerRequest->description = 'Delete partner request';
$auth->add($deletePartnerRequest);
$moderationManager = $auth->getRole('moderationManager');
$auth->addChild($moderationManager, $viewPartnerRequest);
$auth->addChild($moderationManager, $deletePartnerRequest);
/*OrderStatusController*/
$viewOrderStatusList = $auth->createPermission('viewOrderStatusList');
$viewOrderStatusList->description = 'View order status';
$auth->add($viewOrderStatusList);
$saveOrderStatus = $auth->createPermission('saveOrderStatus');
$saveOrderStatus->description = 'Save order status';
$auth->add($saveOrderStatus);
$deleteOrderStatus = $auth->createPermission('deleteOrderStatus');
$deleteOrderStatus->description = 'Delete order status';
$auth->add($deleteOrderStatus);
$orderStatusManager = $auth->createRole('orderStatusManager');
$orderStatusManager->description = 'Order status manager';
$auth->add($orderStatusManager);
$auth->addChild($orderStatusManager, $viewOrderStatusList);
$auth->addChild($orderStatusManager, $saveOrderStatus);
$auth->addChild($orderStatusManager, $deleteOrderStatus);
/*OrderController*/
$viewOrderList = $auth->createPermission('viewOrderList');
$viewOrderList->description = 'View list of orders';
$auth->add($viewOrderList);
$viewOrder = $auth->createPermission('viewOrder');
$viewOrder->description = 'View order';
$auth->add($viewOrder);
$deleteOrder = $auth->createPermission('deleteOrder');
$deleteOrder->description = 'Delete order';
$auth->add($deleteOrder);
$deleteOrderProduct = $auth->createPermission('deleteOrderProduct');
$deleteOrderProduct->description = 'Delete order product';
$auth->add($deleteOrderProduct);
$orderManager = $auth->createRole('orderManager');
$orderManager->description = 'Order manager';
$auth->add($orderManager);
$auth->addChild($orderManager, $viewOrderList);
$auth->addChild($orderManager, $viewOrder);
$auth->addChild($orderManager, $deleteOrder);
$auth->addChild($orderManager, $deleteOrderProduct);
/*FilterController*/
$viewFilterList = $auth->createPermission('viewFilterList');
$viewFilterList->description = 'View list of filters';
$auth->add($viewFilterList);
$saveFilter = $auth->createPermission('saveFilter');
$saveFilter->description = 'Save filter';
$auth->add($saveFilter);
$deleteFilter = $auth->createPermission('deleteFilter');
$deleteFilter->description = 'Delete filter';
$auth->add($deleteFilter);
$filterManager = $auth->createRole('filterManager');
$filterManager->description = 'Filter manager';
$auth->add($filterManager);
$auth->addChild($filterManager, $viewFilterList);
$auth->addChild($filterManager, $saveFilter);
$auth->addChild($filterManager, $deleteFilter);
/*DeliveryMethodController*/
$viewDeliveryMethodList = $auth->createPermission('viewDeliveryMethodList');
$viewDeliveryMethodList->description = 'View list of delivery methods';
$auth->add($viewDeliveryMethodList);
$saveDeliveryMethod = $auth->createPermission('saveDeliveryMethod');
$saveDeliveryMethod->description = 'Save delivery method';
$auth->add($saveDeliveryMethod);
$deleteDeliveryMethod = $auth->createPermission('deleteDeliveryMethod');
$deleteDeliveryMethod->description = 'Delete delivery method';
$auth->add($deleteDeliveryMethod);
$deliveryMethodManager = $auth->createRole('deliveryMethodManager');
$deliveryMethodManager->description = 'Delivery method manager';
$auth->add($deliveryMethodManager);
$auth->addChild($deliveryMethodManager, $viewDeliveryMethodList);
$auth->addChild($deliveryMethodManager, $saveDeliveryMethod);
$auth->addChild($deliveryMethodManager, $deleteDeliveryMethod);
/*CurrencyController*/
$viewCurrencyList = $auth->createPermission('viewCurrencyList');
$viewCurrencyList->description = 'View list of currencies';
$auth->add($viewCurrencyList);
$updateCurrency = $auth->createPermission('updateCurrency');
$updateCurrency->description = 'Update currency';
$auth->add($updateCurrency);
$deleteCurrency = $auth->createPermission('deleteCurrency');
$deleteCurrency->description = 'Delete currency';
$auth->add($deleteCurrency);
$currencyManager = $auth->createRole('currencyManager');
$currencyManager->description = 'Currency manager';
$auth->add($currencyManager);
$auth->addChild($currencyManager, $viewCurrencyList);
$auth->addChild($currencyManager, $updateCurrency);
$auth->addChild($currencyManager, $deleteCurrency);
/*CountryController*/
$viewCountryList = $auth->createPermission('viewCountryList');
$viewCountryList->description = 'View list of countries';
$auth->add($viewCountryList);
$saveCountry = $auth->createPermission('saveCountry');
$saveCountry->description = 'Save country';
$auth->add($saveCountry);
$deleteCountry = $auth->createPermission('deleteCountry');
$deleteCountry->description = 'Delete country';
$auth->add($deleteCountry);
$countryManager = $auth->createRole('countryManager');
$countryManager->description = 'Country manager';
$auth->add($countryManager);
$auth->addChild($countryManager, $viewCountryList);
$auth->addChild($countryManager, $saveCountry);
$auth->addChild($countryManager, $deleteCountry);
/*CategoryController*/
$viewCategoryList = $auth->createPermission('viewShopCategoryList');
$viewCategoryList->description = 'View list of categories';
$auth->add($viewCategoryList);
$saveCategory = $auth->createPermission('saveShopCategory');
$saveCategory->description = 'Save category';
$auth->add($saveCategory);
$deleteCategory = $auth->createPermission('deleteShopCategory');
$deleteCategory->description = 'Delete category';
$auth->add($deleteCategory);
$categoryManager = $auth->createRole('shopCategoryManager');
$categoryManager->description = 'Category manager';
$auth->add($categoryManager);
$auth->addChild($categoryManager, $viewCategoryList);
$auth->addChild($categoryManager, $saveCategory);
$auth->addChild($categoryManager, $deleteCategory);
/*AttributeController*/
$viewAttributeList = $auth->createPermission('viewAttributeList');
$viewAttributeList->description = 'View list of attributes';
$auth->add($viewAttributeList);
$saveAttribute = $auth->createPermission('saveAttribute');
$saveAttribute->description = 'Save attribute';
$auth->add($saveAttribute);
$deleteAttribute = $auth->createPermission('deleteAttribute');
$deleteAttribute->description = 'Delete attribute';
$auth->add($deleteAttribute);
$addAttributeValue = $auth->createPermission('addAttributeValue');
$addAttributeValue->description = 'Add attribute value';
$auth->add($addAttributeValue);
$attributeManager = $auth->createRole('attributeManager');
$attributeManager->description = 'Attribute manager';
$auth->add($attributeManager);
$auth->addChild($attributeManager, $viewAttributeList);
$auth->addChild($attributeManager, $saveAttribute);
$auth->addChild($attributeManager, $deleteAttribute);
$auth->addChild($attributeManager, $addAttributeValue);
}
public function down()
{
$auth = Yii::$app->authManager;
$viewPartnerRequest = $auth->getPermission('viewPartnerRequest');
$deletePartnerRequest = $auth->getPermission('deletePartnerRequest');
$moderationManager = $auth->getRole('moderationManager');
$auth->removeChild($moderationManager, $viewPartnerRequest);
$auth->removeChild($moderationManager, $deletePartnerRequest);
$auth->remove($viewPartnerRequest);
$auth->remove($deletePartnerRequest);
$permissions = [
'viewVendorList', 'saveVendor', 'deleteVendor', 'viewProductAvailabilityList', 'saveProductAvailability',
'deleteProductAvailability', 'viewPartnerRequest', 'deletePartnerRequest', 'viewOrderStatusList',
'saveOrderStatus', 'deleteOrderStatus', 'viewOrderList', 'viewOrder', 'deleteOrder', 'deleteOrderProduct',
'viewFilterList', 'saveFilter', 'deleteFilter', 'viewDeliveryMethodList', 'saveDeliveryMethod',
'deleteDeliveryMethod', 'viewCurrencyList', 'updateCurrency', 'deleteCurrency', 'viewCountryList',
'saveCountry', 'deleteCountry', 'viewShopCategoryList', 'saveShopCategory', 'deleteShopCategory', 'viewAttributeList',
'saveAttribute', 'deleteAttribute', 'addAttributeValue'
];
$roles = [
'vendorManager', 'productAvailabilityManager', 'orderStatusManager', 'orderManager',
'filterManager', 'deliveryMethodManager', 'currencyManager', 'countryManager',
'shopCategoryManager', 'attributeManager'
];
foreach ($roles as $role) {
$auth->removeChildren($role);
$auth->remove($role);
}
foreach ($permissions as $item) {
$permission = $auth->getPermission($item);
$auth->remove($permission);
}
}
}
| black-lamp/blcms-shop | migrations/m161025_115253_add_permissions.php | PHP | gpl-3.0 | 12,310 |
<?php
/**
* Front Page Template
*
* Child Theme Name: OBM-Genesis-Child
* Author: Orange Blossom Media
* Url: https://orangeblossommedia.com/
*
* @package OBM-Genesis-Child
*/
// Execute custom home page. If no widgets active, then loop.
add_action( 'genesis_meta', 'obm_custom_homepage' );
/**
* Controls display of homepage
*/
function obm_custom_homepage() {
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
// Remove default page content.
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'obm_do_home_loop' );
}
/**
* Creates a custom loop for the homepage content.
*/
function obm_do_home_loop() {
}
genesis();
| davidlaietta/obm-genesis-child | front-page.php | PHP | gpl-3.0 | 713 |
package wayerr.reflect;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
final class ParameterizedTypeImpl implements ParameterizedType {
private final Class rawType;
private final Type[] actualTypeArguments;
private final Type ownerType;
public ParameterizedTypeImpl(Class rawType, Type[] actualTypeArguments, Type ownerType) {
this.rawType = rawType;
this.actualTypeArguments = actualTypeArguments;
if(ownerType != null) {
this.ownerType = ownerType;
} else {
this.ownerType = this.rawType.getDeclaringClass();
}
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments.clone();
}
@Override
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof ParameterizedType)) {
return false;
} else {
// Check that information is equivalent
ParameterizedType that = (ParameterizedType)o;
if(this == that) {
return true;
}
Type thatOwner = that.getOwnerType();
Type thatRawType = that.getRawType();
return (ownerType == null ? thatOwner == null : ownerType.equals(thatOwner)) && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
}
}
@Override
public int hashCode() {
return Arrays.hashCode(actualTypeArguments) ^ (ownerType == null ? 0 : ownerType.hashCode()) ^ (rawType == null ? 0 : rawType.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(ownerType != null) {
if(ownerType instanceof Class) {
sb.append(((Class)ownerType).getName());
} else {
sb.append(ownerType.toString());
}
sb.append(".");
if(ownerType instanceof ParameterizedTypeImpl) {
// Find simple name of nested type by removing the
// shared prefix with owner.
sb.append(rawType.getName().replace(((ParameterizedTypeImpl)ownerType).rawType.getName() + "$",
""));
} else {
sb.append(rawType.getName());
}
} else {
sb.append(rawType.getName());
}
if(actualTypeArguments != null
&& actualTypeArguments.length > 0) {
sb.append("<");
boolean first = true;
for(Type t : actualTypeArguments) {
if(!first) {
sb.append(", ");
}
if(t instanceof Class) {
sb.append(((Class)t).getName());
} else {
sb.append(t.toString());
}
first = false;
}
sb.append(">");
}
return sb.toString();
}
}
| wayerr/ivasu | src/main/java/wayerr/reflect/ParametrizedTypeImpl.java | Java | gpl-3.0 | 3,188 |
package com.jyie.leet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
*
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
*
*
* Created by Jangwon Yie on 2018. 4. 2..
*/
public class BTLOT {
private static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new LinkedList<List<Integer>>();
Queue<TreeNode> init = new LinkedList<TreeNode> ();
init.offer(root);
addLevel(list, init);
return list;
}
private void addLevel(List<List<Integer>> list, Queue<TreeNode> queue){
if(queue.isEmpty())
return;
Queue<TreeNode> next = new LinkedList<TreeNode> ();
List<Integer> levelList = null;
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(null != node){
if(null == levelList)
levelList = new LinkedList<Integer> ();
levelList.add(node.val);
if(null != node.left)
next.offer(node.left);
if(null != node.right)
next.offer(node.right);
}
}
if(null != levelList)
list.add(levelList);
if(!next.isEmpty())
addLevel(list, next);
}
}
| JangwonYie/LeetCodeChallenge | src/main/java/com/jyie/leet/BTLOT.java | Java | gpl-3.0 | 1,668 |
#include "field_of_vision.hpp"
using namespace engine;
FieldOfVision::FieldOfVision(double x, double y, int size, double angle){
range = size;
total_angle = angle;
catch_effect = new Audio("assets/sounds/GUARDAVIU.wav", "EFFECT", 128);
active = true;
//not including centerLine
number_of_lines = 10;
createLines(x,y,range);
}
int FieldOfVision::getAngle(){
return center_line->getAngle();
}
void FieldOfVision::resetLines(){
//free(centerLine);
for(auto line: lines){
free(line);
}
lines.clear();
}
void FieldOfVision::deactivate(){
active = false;
}
bool FieldOfVision::isActive(){
return active;
}
void FieldOfVision::createLines(double x, double y, int size){
resetLines();
center_line = new Line(x,y,size, 0);
double angle_inc = ((double)total_angle/2.0)/((double)number_of_lines/2.0);
for(double i = 0, line_angle = angle_inc; i<number_of_lines/2; i+=1, line_angle += angle_inc) {
Line* new_upper_line = new Line(center_line);
new_upper_line->rotateLine(line_angle);
lines.push_back(new_upper_line);
Line* new_lower_line = new Line(center_line);
new_lower_line->rotateLine(-line_angle);
lines.push_back(new_lower_line);
}
}
void FieldOfVision::updateCenter(double inc_x, double inc_y){
center_line->updatePosition(inc_x,inc_y);
for(auto line: lines){
line->updatePosition(inc_x,inc_y);
}
}
void FieldOfVision::draw(){
if(active){
AnimationManager::instance.addFieldOfVision(this);
}
}
void FieldOfVision::incrementAngle(double angle){
center_line->rotateLine(angle);
for(auto line:lines){
line->rotateLine(angle);
}
}
void FieldOfVision::setAngle(double angle){
center_line->changeAngleTo(angle);
double angle_inc = ((double)total_angle/2.0)/((double)number_of_lines/2.0);
double line_angle = angle;
int i = 0;
bool inverteu = false;
for(auto line:lines){
if(i >= number_of_lines/2 && !inverteu){
line_angle = angle;
angle_inc *= (-1);
inverteu = true;
}
line_angle -= angle_inc;
line->changeAngleTo(line_angle);
i++;
}
}
std::vector<Line*> FieldOfVision::getLines(){
std::vector<Line*> lines_return;
lines_return.push_back(center_line);
for(auto line:lines){
lines_return.push_back(line);
}
return lines_return;
}
int FieldOfVision::getRange(){
return range;
}
void FieldOfVision::playEffect(){
catch_effect->play(0);
}
| joaosaliba/Conspiracy | engine/src/field_of_vision.cpp | C++ | gpl-3.0 | 2,568 |
#
# Cookbook Name:: zabbix_opsworks
# Recipe:: default
#
# Copyright (c) 2016 GPL v3.
| paulopontesm/zabbix_opsworks | recipes/default.rb | Ruby | gpl-3.0 | 86 |
// Copyright 2020 Author: Ruslan Bikchentaev. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package json
import (
"bytes"
"database/sql"
"io"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/ruslanBik4/logs"
)
func TestAnyJSON(t *testing.T) {
type args struct {
arrJSON map[string]interface{}
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := AnyJSON(tt.args.arrJSON); got != tt.want {
t.Errorf("AnyJSON() = %v, want %v", got, tt.want)
}
})
}
}
func TestArrJSON(t *testing.T) {
type args struct {
arrJSON []interface{}
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ArrJSON(tt.args.arrJSON); got != tt.want {
t.Errorf("ArrJSON() = %v, want %v", got, tt.want)
}
})
}
}
type UsersFields struct {
Id int32 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Isdel bool `json:"isdel"`
Id_roles int32 `json:"id_roles"`
Last_login time.Time `json:"last_login"`
Hash int64 `json:"hash"`
Last_page sql.NullString `json:"last_page"`
Address sql.NullString `json:"address"`
Emailpool []string `json:"emailpool"`
Phones []string `json:"phones"`
Languages []string `json:"languages"`
IdHomepages int32 `json:"homepage"`
CreateAt time.Time `json:"createAt"`
}
type FormActions struct {
FormErrors map[string]string `json:"formErrors"`
}
type User struct {
*UsersFields
Form string `json:"form"`
Lang string `json:"lang"`
Token string `json:"token"`
ContentURL string `json:"content_url"`
FormActions []FormActions `json:"formActions"`
}
func TestElement(t *testing.T) {
tests := []struct {
name string
args interface{}
want string
}{
// TODO: Add test cases.
{
"string with escaped symbols",
`tralal"'"as'"'as`,
`"tralal\"\u0027\"as\u0027\"\u0027as"`,
},
{
"forms",
User{
UsersFields: &UsersFields{
Id: 0,
Name: "ruslan",
Email: "trep@mail.com",
Isdel: false,
Id_roles: 3,
Last_login: time.Date(2020, 01, 14, 12, 34, 12, 0, time.UTC),
Hash: 131313,
Last_page: sql.NullString{String: "/profile/user/", Valid: true},
Address: sql.NullString{String: `Kyiv, Xhrechatik, 2"A"/12`, Valid: true},
Emailpool: []string{"ru@ru.ru", "ASFSfsfs@gmail.ru"},
Phones: []string{"+380(66)13e23423", "(443)343434d12"},
Languages: []string{"ua", "en", "ru"},
IdHomepages: 0,
CreateAt: time.Date(2020, 01, 14, 12, 34, 12, 0, time.UTC),
},
Form: "form",
Lang: "en",
Token: "@#%&#!^$%&^$",
ContentURL: "ww.google.com",
FormActions: []FormActions{
FormActions{FormErrors: map[string]string{"id": "wrong", "password": "true"}},
},
},
`{"id":0,"name":"ruslan","email":"trep@mail.com","isdel":false,"id_roles":3,"last_login":"2020-01-14T12:34:12Z","hash":131313,"last_page":"/profile/user/","address":"Kyiv, Xhrechatik, 2\"A\"/12","emailpool":["ru@ru.ru","ASFSfsfs@gmail.ru"],"phones":["+380(66)13e23423","(443)343434d12"],"languages":["ua","en","ru"],"homepage":0,"createAt":"2020-01-14T12:34:12Z","form":"form","lang":"en","token":"@#%&#!^$%&^$","content_url":"ww.google.com","formActions":[{"formErrors":{"id":"wrong","password":"true"}}]}
`,
},
}
logs.SetDebug(true)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if !assert.Equal(t, tt.want, Element(tt.args)) {
}
})
}
}
func TestFloat32Dimension(t *testing.T) {
type args struct {
arrJSON []float32
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Float32Dimension(tt.args.arrJSON); got != tt.want {
t.Errorf("Float32Dimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestFloat64Dimension(t *testing.T) {
type args struct {
arrJSON []float64
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Float64Dimension(tt.args.arrJSON); got != tt.want {
t.Errorf("Float64Dimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestInt32Dimension(t *testing.T) {
type args struct {
arrJSON []int32
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Int32Dimension(tt.args.arrJSON); got != tt.want {
t.Errorf("Int32Dimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestInt64Dimension(t *testing.T) {
type args struct {
arrJSON []int64
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Int64Dimension(tt.args.arrJSON); got != tt.want {
t.Errorf("Int64Dimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestSimpleDimension(t *testing.T) {
type args struct {
arrJSON []interface{}
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SimpleDimension(tt.args.arrJSON); got != tt.want {
t.Errorf("SimpleDimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestSliceJSON(t *testing.T) {
type args struct {
mapJSON []map[string]interface{}
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SliceJSON(tt.args.mapJSON); got != tt.want {
t.Errorf("SliceJSON() = %v, want %v", got, tt.want)
}
})
}
}
func TestStreamAnyJSON(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON map[string]interface{}
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamArrJSON(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []interface{}
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamElement(t *testing.T) {
type args struct {
qw422016 io.Writer
value interface{}
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamFloat32Dimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []float32
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamFloat64Dimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []float64
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamInt32Dimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []int32
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamInt64Dimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []int64
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamSimpleDimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []interface{}
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamSliceJSON(t *testing.T) {
type args struct {
qw422016 io.Writer
mapJSON []map[string]interface{}
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStreamStringDimension(t *testing.T) {
type args struct {
qw422016 io.Writer
arrJSON []string
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
func TestStringDimension(t *testing.T) {
type args struct {
arrJSON []string
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StringDimension(tt.args.arrJSON); got != tt.want {
t.Errorf("StringDimension() = %v, want %v", got, tt.want)
}
})
}
}
func TestWriteAnyJSON(t *testing.T) {
type args struct {
arrJSON map[string]interface{}
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteAnyJSON(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteAnyJSON() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteArrJSON(t *testing.T) {
type args struct {
arrJSON []interface{}
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteArrJSON(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteArrJSON() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteElement(t *testing.T) {
type args struct {
value interface{}
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteElement(qq422016, tt.args.value)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteElement() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteFloat32Dimension(t *testing.T) {
type args struct {
arrJSON []float32
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteFloat32Dimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteFloat32Dimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteFloat64Dimension(t *testing.T) {
type args struct {
arrJSON []float64
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteFloat64Dimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteFloat64Dimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteInt32Dimension(t *testing.T) {
type args struct {
arrJSON []int32
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteInt32Dimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteInt32Dimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteInt64Dimension(t *testing.T) {
type args struct {
arrJSON []int64
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteInt64Dimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteInt64Dimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteSimpleDimension(t *testing.T) {
type args struct {
arrJSON []interface{}
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteSimpleDimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteSimpleDimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteSliceJSON(t *testing.T) {
type args struct {
mapJSON []map[string]interface{}
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteSliceJSON(qq422016, tt.args.mapJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteSliceJSON() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
func TestWriteStringDimension(t *testing.T) {
type args struct {
arrJSON []string
}
tests := []struct {
name string
args args
wantQq422016 string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
qq422016 := &bytes.Buffer{}
WriteStringDimension(qq422016, tt.args.arrJSON)
if gotQq422016 := qq422016.String(); gotQq422016 != tt.wantQq422016 {
t.Errorf("WriteStringDimension() = %v, want %v", gotQq422016, tt.wantQq422016)
}
})
}
}
| ruslanBik4/httpgo | views/templates/json/anyjson.qtpl_test.go | GO | gpl-3.0 | 14,538 |
/*
* QueryBookmarkEvent.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.event;
public interface QueryBookmarkEvent extends ApplicationEvent {
/** Method name for bookmark added */
String BOOKMARK_ADDED = "queryBookmarkAdded";
/** Method name for bookmark added */
String BOOKMARK_REMOVED = "queryBookmarkRemoved";
}
| takisd123/executequery | src/org/executequery/event/QueryBookmarkEvent.java | Java | gpl-3.0 | 1,019 |
/*
Node-OpenDroneMap Node.js App and REST API to access OpenDroneMap.
Copyright (C) 2016 Node-OpenDroneMap Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const config = require('../config');
const async = require('async');
const assert = require('assert');
const logger = require('./logger');
const fs = require('fs');
const glob = require("glob");
const path = require('path');
const rmdir = require('rimraf');
const odmRunner = require('./odmRunner');
const processRunner = require('./processRunner');
const archiver = require('archiver');
const Directories = require('./Directories');
const kill = require('tree-kill');
const S3 = require('./S3');
const request = require('request');
const utils = require('./utils');
const statusCodes = require('./statusCodes');
module.exports = class Task{
constructor(uuid, name, options = [], webhook = null, skipPostProcessing = false, outputs = [], done = () => {}){
assert(uuid !== undefined, "uuid must be set");
assert(done !== undefined, "ready must be set");
this.uuid = uuid;
this.name = name !== "" ? name : "Task of " + (new Date()).toISOString();
this.dateCreated = new Date().getTime();
this.processingTime = -1;
this.setStatus(statusCodes.QUEUED);
this.options = options;
this.gcpFiles = [];
this.output = [];
this.runningProcesses = [];
this.webhook = webhook;
this.skipPostProcessing = skipPostProcessing;
this.outputs = utils.parseUnsafePathsList(outputs);
async.series([
// Read images info
cb => {
fs.readdir(this.getImagesFolderPath(), (err, files) => {
if (err) cb(err);
else{
this.images = files;
logger.debug(`Found ${this.images.length} images for ${this.uuid}`);
cb(null);
}
});
},
// Find GCP (if any)
cb => {
fs.readdir(this.getGcpFolderPath(), (err, files) => {
if (err) cb(err);
else{
files.forEach(file => {
if (/\.txt$/gi.test(file)){
this.gcpFiles.push(file);
}
});
logger.debug(`Found ${this.gcpFiles.length} GCP files (${this.gcpFiles.join(" ")}) for ${this.uuid}`);
cb(null);
}
});
}
], err => {
done(err, this);
});
}
static CreateFromSerialized(taskJson, done){
new Task(taskJson.uuid,
taskJson.name,
taskJson.options,
taskJson.webhook,
taskJson.skipPostProcessing,
taskJson.outputs,
(err, task) => {
if (err) done(err);
else{
// Override default values with those
// provided in the taskJson
for (let k in taskJson){
task[k] = taskJson[k];
}
// Tasks that were running should be put back to QUEUED state
if (task.status.code === statusCodes.RUNNING){
task.status.code = statusCodes.QUEUED;
}
done(null, task);
}
});
}
// Get path where images are stored for this task
// (relative to nodejs process CWD)
getImagesFolderPath(){
return path.join(this.getProjectFolderPath(), "images");
}
// Get path where GCP file(s) are stored
// (relative to nodejs process CWD)
getGcpFolderPath(){
return path.join(this.getProjectFolderPath(), "gcp");
}
// Get path of project (where all images and assets folder are contained)
// (relative to nodejs process CWD)
getProjectFolderPath(){
return path.join(Directories.data, this.uuid);
}
// Get the path of the archive where all assets
// outputted by this task are stored.
getAssetsArchivePath(filename){
if (filename == 'all.zip'){
// OK, do nothing
}else if (filename == 'orthophoto.tif'){
if (config.test){
if (config.testSkipOrthophotos) return false;
else filename = path.join('..', '..', 'processing_results', 'odm_orthophoto', `odm_${filename}`);
}else{
filename = path.join('odm_orthophoto', `odm_${filename}`);
}
}else{
return false; // Invalid
}
return path.join(this.getProjectFolderPath(), filename);
}
// Deletes files and folders related to this task
cleanup(cb){
rmdir(this.getProjectFolderPath(), cb);
}
setStatus(code, extra){
this.status = {
code: code
};
for (let k in extra){
this.status[k] = extra[k];
}
}
updateProcessingTime(resetTime){
this.processingTime = resetTime ?
-1 :
new Date().getTime() - this.dateCreated;
}
startTrackingProcessingTime(){
this.updateProcessingTime();
if (!this._updateProcessingTimeInterval){
this._updateProcessingTimeInterval = setInterval(() => {
this.updateProcessingTime();
}, 1000);
}
}
stopTrackingProcessingTime(resetTime){
this.updateProcessingTime(resetTime);
if (this._updateProcessingTimeInterval){
clearInterval(this._updateProcessingTimeInterval);
this._updateProcessingTimeInterval = null;
}
}
getStatus(){
return this.status.code;
}
isCanceled(){
return this.status.code === statusCodes.CANCELED;
}
// Cancels the current task (unless it's already canceled)
cancel(cb){
if (this.status.code !== statusCodes.CANCELED){
let wasRunning = this.status.code === statusCodes.RUNNING;
this.setStatus(statusCodes.CANCELED);
if (wasRunning){
this.runningProcesses.forEach(proc => {
// TODO: this does NOT guarantee that
// the process will immediately terminate.
// For eaxmple in the case of the ODM process, the process will continue running for a while
// This might need to be fixed on ODM's end.
// During testing, proc is undefined
if (proc) kill(proc.pid);
});
this.runningProcesses = [];
}
this.stopTrackingProcessingTime(true);
cb(null);
}else{
cb(new Error("Task already cancelled"));
}
}
// Starts processing the task with OpenDroneMap
// This will spawn a new process.
start(done){
const finished = err => {
this.stopTrackingProcessingTime();
done(err);
};
const postProcess = () => {
const createZipArchive = (outputFilename, files) => {
return (done) => {
this.output.push(`Compressing ${outputFilename}\n`);
let output = fs.createWriteStream(this.getAssetsArchivePath(outputFilename));
let archive = archiver.create('zip', {
zlib: { level: 1 } // Sets the compression level (1 = best speed since most assets are already compressed)
});
archive.on('finish', () => {
// TODO: is this being fired twice?
done();
});
archive.on('error', err => {
logger.error(`Could not archive .zip file: ${err.message}`);
done(err);
});
archive.pipe(output);
let globs = [];
const sourcePath = !config.test ?
this.getProjectFolderPath() :
path.join("tests", "processing_results");
// Process files and directories first
files.forEach(file => {
let filePath = path.join(sourcePath, file);
// Skip non-existing items
if (!fs.existsSync(filePath)) return;
let isGlob = /\*/.test(file),
isDirectory = !isGlob && fs.lstatSync(filePath).isDirectory();
if (isDirectory){
archive.directory(filePath, file);
}else if (isGlob){
globs.push(filePath);
}else{
archive.file(filePath, {name: file});
}
});
// Check for globs
if (globs.length !== 0){
let pending = globs.length;
globs.forEach(pattern => {
glob(pattern, (err, files) => {
if (err) done(err);
else{
files.forEach(file => {
if (fs.lstatSync(file).isFile()){
archive.file(file, {name: path.basename(file)});
}else{
logger.debug(`Could not add ${file} from glob`);
}
});
if (--pending === 0){
archive.finalize();
}
}
});
});
}else{
archive.finalize();
}
};
};
const runPostProcessingScript = () => {
return (done) => {
this.runningProcesses.push(
processRunner.runPostProcessingScript({
projectFolderPath: this.getProjectFolderPath()
}, (err, code, signal) => {
if (err) done(err);
else{
if (code === 0) done();
else done(new Error(`Process exited with code ${code}`));
}
}, output => {
this.output.push(output);
})
);
};
};
// All paths are relative to the project directory (./data/<uuid>/)
let allPaths = ['odm_orthophoto/odm_orthophoto.tif', 'odm_orthophoto/odm_orthophoto.mbtiles',
'odm_georeferencing', 'odm_texturing',
'odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles',
'orthophoto_tiles', 'potree_pointcloud', 'images.json'];
// Did the user request different outputs than the default?
if (this.outputs.length > 0) allPaths = this.outputs;
let tasks = [];
if (config.test){
if (config.testSkipOrthophotos){
logger.info("Test mode will skip orthophoto generation");
// Exclude these folders from the all.zip archive
['odm_orthophoto', 'orthophoto_tiles'].forEach(dir => {
allPaths.splice(allPaths.indexOf(dir), 1);
});
}
if (config.testSkipDems){
logger.info("Test mode will skip DEMs generation");
// Exclude these folders from the all.zip archive
['odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles'].forEach(p => {
allPaths.splice(allPaths.indexOf(p), 1);
});
}
if (config.testFailTasks){
logger.info("Test mode will fail the task");
tasks.push(done => done(new Error("Test fail")));
}
}
if (!this.skipPostProcessing) tasks.push(runPostProcessingScript());
tasks.push(createZipArchive('all.zip', allPaths));
// Upload to S3 all paths + all.zip file (if config says so)
if (S3.enabled()){
tasks.push((done) => {
let s3Paths;
if (config.test){
s3Paths = ['all.zip']; // During testing only upload all.zip
}else if (config.s3UploadEverything){
s3Paths = ['all.zip'].concat(allPaths);
}else{
s3Paths = ['all.zip', 'odm_orthophoto/odm_orthophoto.tif'];
}
S3.uploadPaths(this.getProjectFolderPath(), config.s3Bucket, this.uuid, s3Paths,
err => {
if (!err) this.output.push("Done uploading to S3!");
done(err);
}, output => this.output.push(output));
});
}
async.series(tasks, (err) => {
if (!err){
this.setStatus(statusCodes.COMPLETED);
finished();
}else{
this.setStatus(statusCodes.FAILED);
finished(err);
}
});
};
if (this.status.code === statusCodes.QUEUED){
this.startTrackingProcessingTime();
this.setStatus(statusCodes.RUNNING);
let runnerOptions = this.options.reduce((result, opt) => {
result[opt.name] = opt.value;
return result;
}, {});
runnerOptions["project-path"] = fs.realpathSync(Directories.data);
if (this.gcpFiles.length > 0){
runnerOptions.gcp = fs.realpathSync(path.join(this.getGcpFolderPath(), this.gcpFiles[0]));
}
this.runningProcesses.push(odmRunner.run(runnerOptions, this.uuid, (err, code, signal) => {
if (err){
this.setStatus(statusCodes.FAILED, {errorMessage: `Could not start process (${err.message})`});
finished(err);
}else{
// Don't evaluate if we caused the process to exit via SIGINT?
if (this.status.code !== statusCodes.CANCELED){
if (code === 0){
postProcess();
}else{
this.setStatus(statusCodes.FAILED, {errorMessage: `Process exited with code ${code}`});
finished();
}
}else{
finished();
}
}
}, output => {
// Replace console colors
output = output.replace(/\x1b\[[0-9;]*m/g, "");
// Split lines and trim
output.trim().split('\n').forEach(line => {
this.output.push(line.trim());
});
})
);
return true;
}else{
return false;
}
}
// Re-executes the task (by setting it's state back to QUEUED)
// Only tasks that have been canceled, completed or have failed can be restarted.
restart(options, cb){
if ([statusCodes.CANCELED, statusCodes.FAILED, statusCodes.COMPLETED].indexOf(this.status.code) !== -1){
this.setStatus(statusCodes.QUEUED);
this.dateCreated = new Date().getTime();
this.output = [];
this.stopTrackingProcessingTime(true);
if (options !== undefined) this.options = options;
cb(null);
}else{
cb(new Error("Task cannot be restarted"));
}
}
// Returns the description of the task.
getInfo(){
return {
uuid: this.uuid,
name: this.name,
dateCreated: this.dateCreated,
processingTime: this.processingTime,
status: this.status,
options: this.options,
imagesCount: this.images.length
};
}
// Returns the output of the OpenDroneMap process
// Optionally starting from a certain line number
getOutput(startFromLine = 0){
return this.output.slice(startFromLine, this.output.length);
}
// Reads the contents of the tasks's
// images.json and returns its JSON representation
readImagesDatabase(callback){
const imagesDbPath = !config.test ?
path.join(this.getProjectFolderPath(), 'images.json') :
path.join('tests', 'processing_results', 'images.json');
fs.readFile(imagesDbPath, 'utf8', (err, data) => {
if (err) callback(err);
else{
try{
const json = JSON.parse(data);
callback(null, json);
}catch(e){
callback(e);
}
}
});
}
callWebhooks(){
// Hooks can be passed via command line
// or for each individual task
const hooks = [this.webhook, config.webhook];
this.readImagesDatabase((err, images) => {
if (err) logger.warn(err); // Continue with callback
if (!images) images = [];
let json = this.getInfo();
json.images = images;
hooks.forEach(hook => {
if (hook && hook.length > 3){
const notifyCallback = (attempt) => {
if (attempt > 5){
logger.warn(`Webhook invokation failed, will not retry: ${hook}`);
return;
}
request.post(hook, { json },
(error, response) => {
if (error || response.statusCode != 200){
logger.warn(`Webhook invokation failed, will retry in a bit: ${hook}`);
setTimeout(() => {
notifyCallback(attempt + 1);
}, attempt * 5000);
}else{
logger.debug(`Webhook invoked: ${hook}`);
}
});
};
notifyCallback(0);
}
});
});
}
// Returns the data necessary to serialize this
// task to restore it later.
serialize(){
return {
uuid: this.uuid,
name: this.name,
dateCreated: this.dateCreated,
status: this.status,
options: this.options,
webhook: this.webhook,
skipPostProcessing: !!this.skipPostProcessing,
outputs: this.outputs || []
};
}
};
| pierotofy/node-OpenDroneMap | libs/Task.js | JavaScript | gpl-3.0 | 20,626 |
/*!
@file TheorEval.cc
@date Tue Aug 12 2013
@author Andrey Sapronov <Andrey.Sapronov@cern.ch>
Contains TheorEval class member function implementations.
*/
#include <fstream>
#include <list>
#include <sstream>
#include <stack>
#include <float.h>
#include <valarray>
#include "TheorEval.h"
#include "CommonGrid.h"
#include "xfitter_cpp.h"
using namespace std;
// extern struct ord_scales {
// double datasetmur[150];
// double datasetmuf[150];
// int datasetiorder[150];
// } cscales_;
TheorEval::TheorEval(const int dsId, const int nTerms, const std::vector<string> stn, const std::vector<string> stt,
const std::vector<string> sti, const std::vector<string> sts, const string& expr) : _dsId(dsId), _nTerms(nTerms)
{
// _iOrd = cscales_.datasetiorder[_dsId-1];
// _xmur = cscales_.datasetmur[_dsId-1];
// _xmuf = cscales_.datasetmuf[_dsId-1];
for (int it= 0 ; it<nTerms; it++ ){
_termNames.push_back(stn[it]);
_termTypes.push_back(stt[it]);
_termInfos.push_back(sti[it]);
_termSources.push_back(sts[it]);
}
_expr.assign(expr);
_ppbar = false;
}
TheorEval::~TheorEval()
{
map<CommonGrid*, valarray<double>* >::iterator itm = _mapGridToken.begin();
for (; itm!= _mapGridToken.end(); itm++){
delete itm->first;
}
vector<tToken>::iterator it = _exprRPN.begin();
for (; it!=_exprRPN.end(); it++){
if ( ! it->val ) { delete it->val; it->val = NULL; }
}
}
int
TheorEval::initTheory()
{
list<tToken> sl;
this->assignTokens(sl);
this->convertToRPN(sl);
}
int
TheorEval::assignTokens(list<tToken> &sl)
{
stringstream strexpr(_expr);
int it = 0;
const int nb = this->getNbins();
char c;
string term;
tToken t;
while (1){
strexpr.get(c);
if ( strexpr.eof() ) break;
if ( isspace(c) ) continue; // skip whitespaces.
// Oh noes! doesn't work after fortran reading expression with spaces :(.
if ( isdigit(c) ) { // process numbers
term.assign(1,c);
do {
strexpr.get(c);
if ( strexpr.eof() ) break;
if ( isdigit(c) || c=='.' ) {
term.append(1,c);
} else if ( c=='E' || c=='e' ) { // read mantissa including sign in scientific notation
term.append(1,c);
strexpr.get(c);
if ( strexpr.eof() ) break;
if ( isdigit(c) || c == '-' ){
term.append(1,c);
} else {
cout << "Theory expression syntax error: " << _expr << endl;
return -1;
}
} else {
strexpr.putback(c);
break;
}
} while (1);
double dterm = atof(term.c_str());
t.opr = 0;
t.name = term;
t.val = new valarray<double>(dterm, nb);
sl.push_back(t);
continue;
} else if ( isalpha(c) ) { // process literal terms
term.assign(1,c);
while (strexpr.get(c) ) {
if ( isalnum(c) ) term.append(1,c);
else {
strexpr.putback(c);
break;
}
}
if ( term == string("sum") ) { // special case for sum() function
t.opr = 4;
t.name = "sum";
t.val = new valarray<double>(0., nb);
sl.push_back(t);
continue;
}
/*
if ( term == string("avg") ) { // special case for avg() function
t.opr = 4;
t.name = "avg";
t.val = new valarray<double>(0., nb);
sl.push_back(t);
continue;
}
*/
vector<string>::iterator found_term = find(_termNames.begin(), _termNames.end(), term);
if ( found_term == _termNames.end() ) {
cout << "Undeclared term " << term << " in expression " << _expr << endl;
return -1;
} else {
t.opr = 0;
t.name = term;
if ( _mapInitdTerms.find(term) != _mapInitdTerms.end()){
t.val = _mapInitdTerms[term];
} else {
t.val = new valarray<double>(0.,nb);
this->initTerm(int(found_term-_termNames.begin()), t.val);
_mapInitdTerms[term] = t.val;
}
sl.push_back(t);
}
term.clear();
continue;
} else {
switch(c){
case '(': t.opr = -1; break;
case ')': t.opr = -2; break;
case '+': t.opr = 1; break;
case '-': t.opr = 1; break;
case '*': t.opr = 3; break;
case '/': t.opr = 3; break;
default: cout << "Unknown operator "<< c << " in expression " << _expr << endl;
}
t.name.assign(1,c);
t.val = new valarray<double>(0., nb);
sl.push_back(t);
}
}
}
int
TheorEval::convertToRPN(list<tToken> &sl)
{
stack<tToken> tknstk;
// convert to RPN
while ( 0!=sl.size()){
tToken t = sl.front();
sl.pop_front();
if ( 0 == t.opr ) {
_exprRPN.push_back(t);
}
//if ( 4 == t.opr ){ // push functions
// tknstk.push(t);
//}
if ( t.opr >0 ) {
while ( tknstk.size() > 0 && t.opr <= tknstk.top().opr ) {
_exprRPN.push_back(tknstk.top());
tknstk.pop();
}
tknstk.push(t);
}
if ( t.opr == -1 ){ tknstk.push(t); delete t.val;} // left parenthesis
if ( t.opr == -2 ){ // right parenthesis
while ( tknstk.top().opr != -1 ) {
if ( tknstk.size() == 0 ) cout << "ERROR: Wrong syntax in theoretical expression: "<< _expr << endl;
_exprRPN.push_back(tknstk.top());
tknstk.pop();
}
delete t.val;
tknstk.pop();
}
}
while ( tknstk.size() != 0 ){
if (tknstk.top().opr == -1 ) cout << "ERROR: Wrong syntax in theoretical expression: "<< _expr << endl;
_exprRPN.push_back(tknstk.top());
tknstk.pop();
}
/*
vector<tToken>::iterator it= _exprRPN.begin();
for (;it!=_exprRPN.end(); it++){
cout << it->name << " " ;
}
cout << endl;
*/
}
int
TheorEval::initTerm(int iterm, valarray<double> *val)
{
string term_type = _termTypes.at(iterm);
if ( term_type.find("grid") != string::npos || term_type.find("ast") != string::npos ){ //appl'grid' or f'ast'NLO
this->initGridTerm(iterm, val);
} else if ( term_type == string("kfactor")) {
this->initKfTerm(iterm, val);
} else {
int id = 15102301;
char text[] = "S: Unknown term type in expression for term";
std::cout << "Unknown term type in expression for term " << _termNames[iterm] << std::endl;
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
return -1;
}
}
int
TheorEval::initGridTerm(int iterm, valarray<double> *val)
{
string term_source = _termSources.at(iterm);
string term_type = _termTypes.at(iterm);
string term_info = _termInfos.at(iterm);
CommonGrid *g = new CommonGrid(term_type, term_source);
if ( term_type.find("grid") != string::npos ) {
// set the collision for the grid term
string collision ("pp"); // default is pp
// this is to have backward-compatibility with Tevatron datasets
if ( _ppbar ) collision.assign(string("ppbar"));
// otherwise we check beams in the TermInfo lines
else {
size_t beams_pos = term_info.find(string("beams"));
if ( beams_pos != string::npos ){
size_t semicol_pos = term_info.find(';', beams_pos);
size_t eq_pos = term_info.find('=', beams_pos);
collision.assign(term_info.substr(eq_pos+1, semicol_pos - eq_pos-1));
}
}
// strip blanks
collision.erase(std::remove(collision.begin(), collision.end(), ' '), collision.end());
// and set the collision
g->SetCollisions(collision);
g->SetDynamicScale( _dynamicscale );
// check the binning with the grids, will be ignored for normalisation grids
g->checkBins(_binFlags, _dsBins);
}
else if ( term_type.find("ast") != string::npos ){
bool PublicationUnits = true; // todo: take from new steering flag 'TermNorm'
//FastNLOReader* fnlo = g->getHBins().back().f;
FastNLOxFitter* fnlo = g->getHBins().back().f;
if(PublicationUnits)
fnlo->SetUnits(fastNLO::kPublicationUnits);
else
fnlo->SetUnits(fastNLO::kAbsoluteUnits);
// --- set scales
if(_MurDef>=0)
fnlo->SetMuRFunctionalForm((fastNLO::EScaleFunctionalForm) ((int) (_MurDef)));
if(_MufDef>=0)
fnlo->SetMuFFunctionalForm((fastNLO::EScaleFunctionalForm) ((int) (_MufDef)));
if ( _xmur!=1 || _xmuf!=1 )
fnlo->SetScaleFactorsMuRMuF(_xmur, _xmuf);
// --- set order
if ( _iOrd == 1 ) {
fnlo->SetContributionON(fastNLO::kFixedOrder,1,false); // switch 'off' NLO
}
else if (_iOrd==2) {
// that's fastNLO default
}
else if (_iOrd==3) {
fnlo->SetContributionON(fastNLO::kFixedOrder,2,true); // switch 'on' NNLO
}
else {
printf("fastNLO pert. order is not defined, ordercalc = %d:\n",_iOrd);
exit(1);
}
}
/*
appl::grid *g = new appl::grid(term_source);
if (_dynamicscale != 0)
{
#ifdef APPLGRID_DYNSCALE
g->setDynamicScale( _dynamicscale );
#else
int id = 2204201401;
char text[] = "S: Cannot use dynamic scale emulation in Applgrid, use v1.4.43 or higher";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
#endif
}
g->trim();
*/
// associate grid and valarray pointers in token
_mapGridToken[g] = val;
}
int
TheorEval::initKfTerm(int iterm, valarray<double> *val)
{
string term_source(_termSources.at(iterm));
// read k-Factor table and compare it's binning to the data
cout << "reading k-factor table from " << term_source << endl;
vector<double> tv;
vector<vector<double> > bkf(_dsBins.size(),tv);
vector<double> vkf;
ifstream kff(term_source.c_str());
string line;
if (kff.is_open()){
while (1) {
getline(kff,line);
if (true == kff.eof()) break;
if (line.at(0) == '#' ) continue; //ignore comments
line.erase(line.find_last_not_of(" \n\r\t")+1); // trim trailing whitespaces
stringstream sl(line);
// first count words
int nw(0);
while (sl.good()) {
string ts;
sl >> ts;
nw++;
}
// check that we have even number of bins (low and high columns)
if (0!=(nw-1)%2) {
int id = 14040340;
char text[] = "S: Bad number of bins in k-factor file. Each bin must have low and high value.";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
}
// check that the number of bins is equal to data binning dimension
if ((nw-1) != _dsBins.size()) {
int id = 14040341;
char text[] = "S: Bad number of bins in k-factor file. Must be equal to data binning dimension.";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
}
// now read bins
sl.clear();
sl.seekg(0);
sl.str(line);
double tb(0);
for (int iw=0; iw<nw-1; iw++) {
sl >> tb;
bkf.at(iw).push_back(tb);
}
// and k-factor
sl>>tb;
vkf.push_back(tb);
}
kff.close();
} else {
int id = 14040339;
char text[] = "S: Error reading k-factor file.";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
}
// check that k-factor file binning is compatible with data
for (int iv = 0; iv<_dsBins.size(); iv++){
for (int ib = 0; ib<_dsBins.at(iv).size(); ib++){
if ( _binFlags.at(ib) == 0 ) continue;
if ( 0 == (_binFlags.at(ib) & 2) ) {
if (fabs(bkf[iv][ib] - _dsBins[iv][ib]) > 100*DBL_MIN) {
int id = 14040338;
char text[] = "S: Data and grid bins don't match.";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
return -1;
}
}
}
}
// write k-factor array to the token valarray
*val = valarray<double>(vkf.data(), vkf.size());
}
int
TheorEval::setBins(int nBinDim, int nPoints, int *binFlags, double *allBins)
{
for(int ip = 0; ip<nPoints; ip++){
_binFlags.push_back(binFlags[ip]);
}
for(int ibd = 0; ibd < nBinDim; ibd++){
vector<double> bins;
bins.clear();
for(int ip = 0; ip<nPoints; ip++){
bins.push_back(allBins[ip*10 + ibd]);
}
_dsBins.push_back(bins);
}
return _dsBins.size();
}
int
TheorEval::setCKM(const vector<double> &v_ckm)
{
#ifdef APPLGRID_CKM
map<CommonGrid*, valarray<double>* >::iterator itm = _mapGridToken.begin();
for(; itm != _mapGridToken.end(); itm++){
itm->first->setCKM(v_ckm);
}
#else
int id = 611201320;
char text[] = "S: Cannot set CKM in Applgrid, use v1.4.33 or higher";
int textlen = strlen(text);
hf_errlog_(id, text, textlen);
#endif
}
int
TheorEval::Evaluate(valarray<double> &vte )
{
// get values from grids
this->getGridValues();
// calculate expression result
stack<valarray<double> > stk;
vector<tToken>::iterator it = _exprRPN.begin();
while(it!= _exprRPN.end()){
if ( it->opr < 0 ){
cout << "ERROR: Expression RPN is wrong" << endl;
return -1;
}
if ( it->opr == 0 ){
stk.push(*(it->val));
} else if ( it->name == string("sum") ){
double sum = stk.top().sum();
stk.top() = sum;
/* } else if ( it->name == string("avg") ){
if (0 == stk.top().size()) {
cout << "ERROR: avg() argument dimension is 0." << endl;
}
double avg = stk.top().sum()/stk.top().size();
stk.top() = avg;*/
} else if ( it->name == string("+") ){
valarray<double> a(stk.top());
stk.pop();
stk.top() += a;
} else if ( it->name == string("-") ){
valarray<double> a(stk.top());
stk.pop();
stk.top() -= a;
} else if ( it->name == string("*") ){
valarray<double> a(stk.top());
stk.pop();
stk.top() *= a;
} else if ( it->name == string("/") ){
valarray<double> a(stk.top());
stk.pop();
stk.top() /= a;
}
it++;
}
if (stk.size() != 1 ) {
cout << "ERROR: Expression RPN calculation error." << endl;
return -1;
} else {
vte = stk.top();
//Normalised cross section
if (_normalised)
{
double integral = 0;
for (int bin = 0; bin < _binFlags.size(); bin++)
if (!(vte[bin] != vte[bin])) //protection against nan
integral += (_dsBins.at(1).at(bin) - _dsBins.at(0).at(bin)) * vte[bin];
if (integral != 0)
for (int bin = 0; bin < _binFlags.size(); bin++)
vte[bin] /= integral;
}
//vte /= _units;
}
}
int
TheorEval::getGridValues()
{
map<CommonGrid*, valarray<double>*>::iterator itm;
for(itm = _mapGridToken.begin(); itm != _mapGridToken.end(); itm++){
CommonGrid* g = itm->first;
vector<double> xs;
std::vector< std::vector<double> > result = g->vconvolute(_iOrd, _xmur, _xmuf);
for(int i = 0; i < result.size(); i++)
for(int j = 0; j < result[i].size(); j++)
xs.push_back(result[i][j]);
(itm->second)->resize(xs.size());
*(itm->second) = valarray<double>(xs.data(), xs.size());
/*
for (int i = 0; i<xs.size(); i++){
cout << xs[i] << endl;
}
*/
}
}
int
TheorEval::getNbins()
{
return _dsBins[0].size();
}
void TheorEval::ChangeTheorySource(string term, string source)
{
vector<string>::iterator found_term = find(_termNames.begin(), _termNames.end(), term);
if ( found_term == _termNames.end())
{
string msg = (string) "S: Undeclared term " + term;
hf_errlog_(14020603, msg.c_str(), msg.size());
}
int iterm = int(found_term-_termNames.begin());
// cout << "switch " << _termSources[iterm] << " to " << source << endl;
_termSources[iterm] = source;
//delete old applgrid
map<CommonGrid*, valarray<double>* >::iterator itm = _mapGridToken.begin();
for (; itm!= _mapGridToken.end(); itm++)
{
if (itm->second == _mapInitdTerms[term])
{
delete itm->first;
_mapGridToken.erase(itm);
break;
}
}
initTerm(int(found_term-_termNames.begin()), _mapInitdTerms[term]);
}
string TheorEval::GetTheorySource(string term)
{
vector<string>::iterator found_term = find(_termNames.begin(), _termNames.end(), term);
if ( found_term == _termNames.end())
{
string msg = (string) "S: Undeclared term " + term;
hf_errlog_(14020603, msg.c_str(), msg.size());
}
int iterm = int(found_term-_termNames.begin());
return _termSources[iterm];
}
| veprbl/herafitter | src/TheorEval.cc | C++ | gpl-3.0 | 16,012 |
/**
* Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
*
* Licensed under the GPL, Version 3.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.gnu.org/licenses/gpl.html
*
* 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.
*/
package org.tinygroup.tinydb.test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class List2ArrayTest {
@SuppressWarnings("unchecked")
public static <T> T[] collectionToArray(List<?> collection) {
if (collection == null || collection.size() == 0) {
throw new RuntimeException("集合为空或没有元素!");
}
T[] array = (T[]) Array.newInstance(collection.get(0).getClass(),
collection.size());
for (int i = 0; i < collection.size(); i++) {
array[i] = (T) collection.get(i);
}
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] collectionToArray(Collection<?> collection) {
if (collection == null || collection.size() == 0) {
throw new RuntimeException("集合为空或没有元素!");
}
T[] array = (T[]) Array.newInstance(collection.iterator().next().getClass(),
collection.size());
int i = 0;
for (Object obj : collection) {
array[i++] = (T) obj;
}
return array;
}
/**
* @param args
*/
public static void main(String[] args) {
Collection<User> userList = new ArrayList<User>();
userList.add(new User());
userList.add(new User());
User[] array = collectionToArray(userList);
System.out.println(array.getClass().getName());
}
}
class User {
} | TinyGroup/tiny | db/org.tinygroup.tinydb/src/test/java/org/tinygroup/tinydb/test/List2ArrayTest.java | Java | gpl-3.0 | 1,949 |
#include <gtkmm/application.h>
#include <gtkmm/window.h>
#include <glibmm/main.h>
#include "MyArea.h"
int main(int argc, char** argv) {
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
Gtk::Window win;
win.set_title("Cairo example");
MyArea my_area;
win.add(my_area);
my_area.show();
return app->run(win);
}
| manuporto/megaman | examples/cairo_ex/main.cpp | C++ | gpl-3.0 | 338 |
#------------------------------------------------------------------------------------------
#
# Copyright 2017 Robert Pengelly.
#
# This file is part of ppa-helper.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#------------------------------------------------------------------------------------------
# coding: utf-8
from __future__ import unicode_literals
import collections
import os
import shutil
import sys
if sys.version_info >= (3, 0):
compat_getenv = os.getenv
compat_expanduser = os.path.expanduser
def compat_setenv(key, value, env=os.environ):
env[key] = value
else:
# Environment variables should be decoded with filesystem encoding.
# Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
def compat_getenv(key, default=None):
from .utils import get_filesystem_encoding
env = os.getenv(key, default)
if env:
env = env.decode(get_filesystem_encoding())
return env
# Python < 2.6.5 require kwargs to be bytes
try:
def _testfunc(x):
pass
_testfunc(**{'x': 0})
except TypeError:
def compat_kwargs(kwargs):
return dict((bytes(k), v) for k, v in kwargs.items())
else:
compat_kwargs = lambda kwargs: kwargs
if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
compat_get_terminal_size = shutil.get_terminal_size
else:
_terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
def compat_get_terminal_size(fallback=(80, 24)):
columns = compat_getenv('COLUMNS')
if columns:
columns = int(columns)
else:
columns = None
lines = compat_getenv('LINES')
if lines:
lines = int(lines)
else:
lines = None
if columns is None or lines is None or columns <= 0 or lines <= 0:
try:
sp = subprocess.Popen(
['stty', 'size'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
_lines, _columns = map(int, out.split())
except Exception:
_columns, _lines = _terminal_size(*fallback)
if columns is None or columns <= 0:
columns = _columns
if lines is None or lines <= 0:
lines = _lines
return _terminal_size(columns, lines) | robertapengelly/ppa-helper | ppa_helper/compat.py | Python | gpl-3.0 | 3,031 |
#include "meteodata.h"
#include "meteojour.h"
MeteoData::MeteoData(QString v,QObject *parent):QObject(parent),_ville(v){
_mesure = "metric";
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : afficher message d'erreur dans la console
remarque:
precond :
postcond:
©2017
*/
void MeteoData::onError(){
qDebug()<<"Erreur de requete";
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : effectuer une requete pour recupérer données JSON de l'API
remarque:
precond :
postcond:
©2017
*/
void MeteoData::requete(){
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
qDebug()<<"Exe Req";
//execution d'une requete
//callback du storage a la reception de la requete
qDebug()<<"Creation connexion pour succès ou echec";
connect(manager,SIGNAL(finished(QNetworkReply*)),
this,SLOT(storeReplyInObj(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://api.openweathermap.org/data/2.5/forecast/daily?q="+_ville+"&appid=9a5b3401d0ae43c0fdd643de1a05660c&units="+_mesure+"&cnt=5")));
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : Stocker la réponse de l'API dans un QJsonObject
remarque:
precond :
postcond:
©2017
*/
void MeteoData::storeReplyInObj(QNetworkReply* r){
qDebug()<<"CallBack";
if(r->error() == QNetworkReply::NoError){
QByteArray bts = r->readAll();
QString str(bts);
QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
if(!doc.isNull()){
if(doc.isObject()){
obj = doc.object();
parseObj();
}else{
qDebug()<<"le doc n'est pas un objet";
}
} else {
qDebug() << "JSON FORMAT INVALIDE";
}
//qDebug()<<bts;
}else{
qDebug()<<r->errorString();
}
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : parser le QJsonDocument pour récupérer les données
remarque:
precond :
postcond:
©2017
*/
void MeteoData::parseObj(){
qDebug() << obj.keys();//("city", "cnt", "cod", "list", "message")
QJsonArray list = obj.value("list").toArray();
for(int i = 0; i < 5;i ++){
//qDebug() << list.at(i);
QJsonObject jData = list.at(i).toObject();
//qDebug() << jData.keys();//("clouds", "deg", "dt", "humidity", "pressure", "rain", "speed", "temp", "weather")
QJsonObject jTemp = jData.value("temp").toObject();
_coeffNuage = jData.value("clouds").toDouble();
_coeffPluie = jData.value("rain").toDouble();
_pressure = jData.value("pressure").toDouble();
_humidity = jData.value("humidity").toDouble();
_tempMin = jTemp.value("min").toDouble();
_tempMax = jTemp.value("max").toDouble();
_temp = jTemp.value("day").toDouble();
emit dataChanged(i);
}
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter humidité
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getHumidity()const{
return _humidity;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter pression
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getPressure()const{
return _pressure;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter temp min
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getTempMin()const{
return _tempMin;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter temp max
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getTempMax()const{
return _tempMax;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter temp actuelle
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getTemp()const{
return _temp;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter humidité
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setHumidity(double h){
_humidity = h;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter pression
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setPressure(double p){
_pressure = p;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter temp min
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setTempMin(double t){
_tempMin = t;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter temp max
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setTempMax(double t){
_tempMax = t;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter temp actuelle
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setTemp(double t){
_temp = t;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter ville actuelle
remarque:
precond :
postcond:
©2017
*/
QString MeteoData::getVille()const{
return _ville;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter ville actuelle
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setVille(QString v){
_ville = v;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter coeff nuage
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getCoeffNuage()const{
return _coeffNuage;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : getter coeff pluie
remarque:
precond :
postcond:
©2017
*/
double MeteoData::getCoeffPluie()const{
return _coeffPluie;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter coeff nuage
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setCoeffNuage(double c){
_coeffNuage = c;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter coeff pluie
remarque:
precond :
postcond:
©2017
*/
void MeteoData::setCoeffPluie(double c){
_coeffPluie = c;
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : SLOT ré effectuer une requete après une action
remarque:
precond :
postcond:
©2017
*/
void MeteoData::reqAgain(){
requete();
}
/*
author : Fontaine pierre
mail : pierre.ftn64@gmail.com
but : setter mesure
remarque: choix entre "metric,impérial,default"
precond :
postcond:
©2017
*/
void MeteoData::setMesure(QString s){
_mesure = s;
}
| PierreFontaine/poo_project | projet/meteodata.cpp | C++ | gpl-3.0 | 6,551 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hi_IN">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>NdefManager</name>
<message>
<location filename="../ndefmanager.cpp" line="95"/>
<location filename="../ndefmanager.cpp" line="321"/>
<source>NFC hardware is available but currently switched off.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="97"/>
<location filename="../ndefmanager.cpp" line="313"/>
<source>NFC is supported and switched on.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="102"/>
<source>Update device firmware to enable NFC support.</source>
<translation>यह अनुप्रयोग चलाने के लिए कृपया अपनी डिवाइस फार्मबेयार अपडेट करें</translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="106"/>
<source>NFC not supported by this device.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="305"/>
<source>NFC is not currently supported.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="309"/>
<source>NFC is supported, but the current mode is unknown at this time.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="317"/>
<source>NFC hardware is available and currently in card emulation mode.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="337"/>
<source>Unable to query NFC feature support.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="341"/>
<source>Unable to query device software version.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="345"/>
<source>Unable to request NFC mode change notifications.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="349"/>
<source>NFC mode change notification was received, but caused an error.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ndefmanager.cpp" line="353"/>
<source>Unable to retrieve current NFC mode.</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| andijakl/nfccorkboard | loc/NfcCorkboard_hi.ts | TypeScript | gpl-3.0 | 3,041 |
using System;
namespace e10
{
class Liste<T>
{
private T[] liste = new T[5];
private int sayi = 0;
public void Ekle(T t)
{
if (sayi < 5)
liste[sayi++] = t;
}
public void Cikar()
{
sayi--;
}
public void Yazdir()
{
for (int i = 0; i < sayi; i++)
Console.Write($"{liste[i]}, ");
}
}
class Program
{
static void Main(string[] args)
{
Liste<string> isimListesi = new Liste<string>();
isimListesi.Ekle("Ali");
isimListesi.Ekle("Ayse");
isimListesi.Yazdir();
Console.WriteLine();
Liste<int> sayilar = new Liste<int>();
sayilar.Ekle(1);
sayilar.Ekle(5);
// DERLEME hatasi. Derleyici alttaki satira izin vermez
// sayilar.Ekle("Fatma");
sayilar.Yazdir();
Console.WriteLine();
}
}
}
| ozanoner/myb | myp122/w5/e10/Program.cs | C# | gpl-3.0 | 1,028 |