branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<file_sep>#!/bin/bash set -e COLOR_WARNING=$(tput setaf 1) # Light Red COLOR_NONE=$(tput setaf 0) MASTER_BRANCH="master" MAIN_BRANCH="main" # shellcheck disable=SC2207 BRANCHES=($(git branch | tr '*' ' ')) if [[ " ${BRANCHES[*]} " == *" $MASTER_BRANCH "* && " ${BRANCHES[*]} " == *" $MAIN_BRANCH "* ]]; then cat << EOF ${COLOR_WARNING} Error: This repo has a main and master branch!!! ${COLOR_NONE} The main branch is indistinguishable. Favor main over master. EOF exit 1 fi if [[ " ${BRANCHES[*]} " != *" $MASTER_BRANCH "* && " ${BRANCHES[*]} " != *" $MAIN_BRANCH "* ]]; then cat << EOF ${COLOR_WARNING} Error: This repo no main or master branch!!! ${COLOR_NONE} The main branch is indistinguishable. Favor main over master. EOF exit 1 fi if [[ " ${BRANCHES[*]} " == *" $MASTER_BRANCH "* ]]; then echo "${MASTER_BRANCH}" exit 0 fi if [[ " ${BRANCHES[*]} " == *" $MAIN_BRANCH "* ]]; then echo "${MAIN_BRANCH}" exit 0 fi <file_sep>#!/bin/bash git fetch --all --tags git push origin --tags <file_sep>#!/bin/bash git rev-parse HEAD <file_sep># git-commands ## A small collection of user friendly git commands. - `git last-tag` displays the latest tag. - `git next-tag` increments SemVer style tags. Args `major|minor|patch(default)`. - `git purge` clean up task deleting all branches merged into master. - `git info` display branches colour coded by merged status. - `git main` checks for master or main branch, exits with error if none or both are found. - `git mv-branch` built to support the switch from `master` to `main` branch on git repos. For a more inclusive tech industry. Also supports migrating arbitrary branches from one name space to another. `git mv-branch` assumes `git mv-branch master main`. Steps involved are. 1. Check your current branch status 2. Checkout deprecated branch 3. Branch to new namespace 4. Push to origin 5. Delete deprecated branch locally 6. Finally delete from remote. - `git prettylog` one line summary log output. ### Why Git Commands Git or bash aliases are useful, but hard to share and maintain across machines ie. Personal and Work machines. Let alone keeping a team in sync. This allows version controlled commands standardised by ShellCheck. ### Set up Git recognises commands in your $PATH with a prefix of `git-`. You can clone this directory and include the `/bin` folder in your path. Or copy the contents to another location already in your path. ```bash git clone git@github.com:ofhope/git-commands.git cd git-commands printf 'export PATH="%s:$PATH"' "$PWD/bin" >> ~/.bash_profile source ~/.bash_profile ### you may want to restart your terminal, .bash_profile is only read once on start. ``` The benefits of keeping this repo in your PATH is to be able to pull updates when they occur. Moving the scripts to a separate folder keeps you responsible to sync script updates or renames. ### Licence [MIT Licence](LICENSE.md) <file_sep>#!/bin/bash git for-each-ref \ --format='%(color:bold)%(tag)%(color:reset) %(tag) %(authorname) %(color:green)%(authordate:short)%(color:reset) %(subject)' \ --sort=-taggerdate <file_sep>#!/bin/bash set -e # TODO: investigate if merged at date is possible to include # TODO: investigate if created at date is possible to include # TODO: would prefer a git command `git-info` which accepts reports `git info branch` COLOR_UNMERGED='\033[1;31m' # Light Red COLOR_MERGED='\033[1;32m' # Light Green COLOR_CURRENT='\033[1;33m' # Yellow COLOR_MAIN='\033[1;34m' # Blue COLOR_NONE='\033[0m' function colorPrint { printf "${2} %s ${COLOR_NONE}" "$1" } MASTER_BRANCH=$(git main) # shellcheck disable=SC2207 BRANCHES=($(git branch --format='%(refname:short)')) # MERGED=($(git branch --merged "$(git main)" | tr '*' ' ')) # shellcheck disable=SC2207 MERGED=($(git branch --merged "$MASTER_BRANCH" --format='%(refname:short)')) # shellcheck disable=SC2207 UNMERGED=($(git branch --no-merged)) CURRENT_BRANCH=$(git branch --show-current) # Ledgend colorPrint "merged" "$COLOR_MERGED" colorPrint "unmerged" "$COLOR_UNMERGED" colorPrint "current" "$COLOR_CURRENT" colorPrint "main" "$COLOR_MAIN" echo "" && echo "" && : for BRANCH in "${BRANCHES[@]}" do if [[ " $CURRENT_BRANCH " == *" $BRANCH "* ]]; then colorPrint "$BRANCH" "$COLOR_CURRENT" echo "" && : continue fi if [[ " $MASTER_BRANCH " == *" $BRANCH "* ]]; then colorPrint "$BRANCH" "$COLOR_MAIN" echo "" && : continue fi if [[ " ${MERGED[*]} " == *" $BRANCH "* ]]; then colorPrint "$BRANCH" "$COLOR_MERGED" echo "" && : continue fi if [[ " ${UNMERGED[*]} " == *" $BRANCH "* ]]; then colorPrint "$BRANCH" "$COLOR_UNMERGED" echo "" && : continue fi done <file_sep>#!/bin/bash git fetch --all --tags git tag -a $(git next-tag) $(git last-commit) git push origin --tags <file_sep>#!/bin/bash FROM_BRANCH=${1:-master} TO_BRANCH=${2:-main} REMOTE="origin" git ls-remote --exit-code origin > /dev/null 2>&1 HAS_ORIGIN=$? set -e # Check for 0 or 2 arguments if [[ $# != 0 && $# != 2 ]]; then echo "Error: Invalid number of arguments. git migrate-branch from to (defaults master -> main)" exit 1 fi # Check your current branch status if [[ $(git status -uno -s | wc -c) -ne 0 ]]; then echo "Error: Branch is dirty, commit or stash your changes first!" exit 1 fi echo "Branch is clean" && # Checkout deprecated branch git checkout "$FROM_BRANCH" echo "Checked out $FROM_BRANCH" && # Branch to new namespace git checkout -b "$TO_BRANCH" echo "Created branch $TO_BRANCH" && # Push to origin if it exists if [[ $HAS_ORIGIN -eq 0 ]]; then git push -u "$REMOTE" "$TO_BRANCH" echo "Pushing new branch $TO_BRANCH to $REMOTE" && : fi echo "It is reccommended to delete previous branch locally and on remote" && echo "Delete old branches locally and on remote? [y/N]" read -r RESPONSE # Clean up local branch if [[ $RESPONSE =~ ^[Yy]$ ]]; then git branch -D "$FROM_BRANCH" echo "Deleted branch $FROM_BRANCH from local" && : fi # Clean up local remote if [[ $RESPONSE =~ ^[Yy]$ && $HAS_ORIGIN -eq 0 ]]; then git push $REMOTE --delete "$FROM_BRANCH" echo "Deleted branch $FROM_BRANCH from $REMOTE" && : fi echo "Done: successfully migrated from $FROM_BRANCH to $TO_BRANCH" <file_sep>#!/bin/bash ################################################ # TODO: accept argument for log length # TODO: accept argument for log offset # TODO: accept argument for log daterange # # IE. # git prettylog --date:21.05.2020 # git prettylog --date:21.05.2020-15.06.2020 # git prettylog --date:21.05.2020-15.06.2020 # # git log -10 # limits the log output to 10. # # git prettylog 10 # limits the log output to 10. # git prettylog 10:20 # limits the log output to 10 offset by 20 ################################################ git log \ --graph \ --abbrev-commit \ --decorate=no \ --date=format:'%Y-%m-%d' \ --format=format:'%C(03)%>|(26)%h%C(reset) %C(04)%ad%C(reset) %C(green)%<(16,trunc)%an%C(reset) %C(bold 1)%d%C(reset) %C(bold 0)%>|(1)%s%C(reset)' \ --all <file_sep>#!/bin/bash # TODO: Purge origin `git purge origin` # TODO: Include force flag to bypass warning `git purge -f` COLOR_MERGED='\033[1;32m' # Light Green COLOR_NONE='\033[0m' git info printf "Branches in ${COLOR_MERGED} %s ${COLOR_NONE} are merged to main and will be removed. " "green" echo "" && : echo "Are you sure? [y/N] " read -r RESPONSE if [[ $RESPONSE =~ ^[Yy]$ ]]; then git branch --merged| grep -v -E "(^\*|master)" | xargs git branch -d fi <file_sep>#!/bin/bash BUMP=${1:-patch} VALID_ARGS=("major" "minor" "patch") if [[ " ${VALID_ARGS[*]} " != *" $BUMP "* ]]; then printf "Error: Invalid argument, valid args are: " printf "%s " "${VALID_ARGS[@]}" printf "\n" exit 1; fi TAGNAME=$(git describe --abbrev=0) if [[ $TAGNAME =~ v([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then MAJOR=${BASH_REMATCH[1]} MINOR=${BASH_REMATCH[2]} PATCH=${BASH_REMATCH[3]} else printf "Error: No SemVer style tag was found \n" exit 1; fi case $BUMP in "major") MAJOR=$((MAJOR+1)) ;; "minor") MINOR=$((MINOR+1)) ;; "patch") PATCH=$((PATCH+1)) ;; esac printf "v%d.%d.%d\n" $MAJOR $MINOR $PATCH
dbc71cba754d4256cb95969dccbe0b273699b06d
[ "Markdown", "Shell" ]
11
Shell
ofhope/git-commands
6748b5d085b997d389b1ecfd8052b2689489babe
8d52c7685cc03a2d1a490b001e5235939eeedc76
refs/heads/master
<repo_name>staranto/simple-java-maven-app<file_sep>/jenkins/scripts/zstkmt.sh #!/usr/bin/env bash pwd id env echo token:::: $GITHUBPAT echo tokensubstring:::: ${GITHUBPAT:0:5} release=$(curl -XPOST -H "Authorization:token $GITHUBPAT" --data "{\"tag_name\": \"mytag\", \"target_commitish\": \"master\", \"name\": \"myname\", \"body\": \"mydesc\", \"draft\": false, \"prerelease\": true}" https://api.github.com/repos/staranto/simple-java-maven-app/releases) echo release:::: $release # Extract the id of the release from the creation response id=$(echo "$release" | sed -n -e 's/"id":\ \([0-9]\+\),/\1/p' | head -n 1 | sed 's/[[:blank:]]//g') echo id:::: $id curl -XPOST -H "Authorization:token $GITHUBPAT" -H "Content-Type:application/octet-stream" --data-binary @artifact.zip https://uploads.github.com/repos/staranto/simple-java-maven-app/releases/$id/assets?name=artifact.zip
99149f25802ab66914ec17a787e21c8a08ff87e5
[ "Shell" ]
1
Shell
staranto/simple-java-maven-app
2dd4c1717f7433abaf1ffb6d9b94c69caaf244ca
6c313a6d83b8616445133658050f48f00a637e57
refs/heads/master
<repo_name>coolkp/Scrape-NLP<file_sep>/README.md # Scraping Webpage and Deducing its Topic using NLP ## Project Setup `pip install Scrapy beautifulsoup4 ` <br> `pip install spacy && python3 -m spacy download en_core_web_sm` ## Project Run - All Links to be scraped are in [../brightedge/spiders/main_spider.py](../master/brightedge/spiders/main_spider.py) - The data scraped is cleaned and stored in **_"domainname".txt_** in the base of this directory - All generated list of topics are stored in **_"domainname_tags.txt"_** in the base of this directory ### Run `scrapy crawl scraper` ### Results Outputed in terminal in form of a list immediately after every webpage being crawled. They are also stored in txt file in base of directory They are stored for every crawl in `tags` variable in **_main_spider.py_** <file_sep>/brightedge/spiders/main_spider.py import scrapy import spacy import string from bs4 import BeautifulSoup import re class MainSpider(scrapy.Spider): name = "scraper" def start_requests(self): urls = [ 'http://blog.rei.com/camp/how-to-introduce-your-indoorsy-friend-to-the-outdoors/', 'http://www.cnn.com/2013/06/10/politics/edward-snowden-profile/', 'http://www.amazon.com/Cuisinart-CPT-122-Compact-2-SliceToaster/dp/B009GQ034C/ref=sr_1_1?s=kitchen&ie=UTF8&qid=1431620315&sr=1-1&keywords=toaster' ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): page = response.url.split("/")[2] filename = '%s.txt' % page soup = BeautifulSoup(response.text, 'lxml') headers = soup.find_all(re.compile('^h[1-6]$')) headers_text = '' for headlines in headers: headers_text += headlines.text.strip() + '. ' # print(headers_text) # Remove all extraneous text like links images vidoes ads for script in soup(["script", "style","a","span","i","input","textarea","img"]): script.decompose() # rip it out # get text all_p = soup.find_all('p') text = soup.get_text() # Clean up the text lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) nlp = spacy.load('en_core_web_sm') sentences = nlp(text) # print(sentences) output_list = {} # Create key topics list and frequency using lemming and sentence trees # bad_list = ['he','she','to','they','He','She','who','Who','it'] for token in sentences: if token.dep_ == 'nsubj' or token.tag_ == 'NNP': if token.text not in string.punctuation and token.tag_ != 'PRP' and token.tag_ != 'DT' and token.tag_ != 'WP' and token.text.isalpha() : in_text = token.text weight = 1 if token.tag_ == 'NN': in_text = token.lemma_ if token.dep_ == 'nsubj': weight += 1 if token.tag_ == 'NNP': weight += 1 if in_text == 'he': print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_) if in_text not in output_list: output_list[in_text] = 0 output_list[in_text] += 1 # print(output_list) # Sort and take top five topics and Print them final_list = sorted(output_list, key=output_list.__getitem__, reverse=True) tags = final_list[:max(len(final_list)//10,5)] print(tags) # Save all scraped text to txt file with name "top-domainname.txt" with open(filename, 'w') as f: f.write(text) tagfile = '%s_tags.txt' % page with open(tagfile, 'w') as f: f.write((',').join(tags)) self.log('Saved file %s' % filename)
ad378bcb1196868c07cdb866e680a2c3987f3336
[ "Markdown", "Python" ]
2
Markdown
coolkp/Scrape-NLP
0a4db53297cd23448fb2fcc18440fc984f6a89e5
9a92c47ff435607c351a4084eab06c23a221dc6f
refs/heads/master
<file_sep># Demo site folder This folder is the publishing base. <file_sep>// Import Fleek Storage SDK const fleekStorage = require('@fleekhq/fleek-storage-js') // Function for getting file from hash async function FileFromHash() { const myFile = await fleekStorage.getFileFromHash({ hash: 'file-haah-on-fleek', }) console.log('myFile', myFile) } // Run the function async function run() { await FileFromHash() } // Error handling run().then(() => console.log('done')).catch(console.error)<file_sep>// Import Fleek Storage SDK const fleekStorage = require('@fleekhq/fleek-storage-js') // Import fs to read files from file system const fs = require('fs'); // Function for uploading a file onto Fleek async function uploadFile() { fs.readFile('/filepath/filename', async (error, fileData) => { const uploadedFile = await fleekStorage.upload({ apiKey: 'my-key', apiSecret: 'my-secret', key: '/filepath/filename', data: fileData, }); console.log('uploadedFile', uploadedFile) }) } // N.B.: The folder structure in the filepath here will get created on Fleek // Run the function async function run() { await uploadFile() } // Error handling run().then(() => console.log('done')).catch(console.error)<file_sep># ClimateDataPool **Decentralized storage and file management for climate data** The Paris Climate Accord was a momentous accomplishment, uniting all the world's nations in an effort to tackle climate change. ClimateDataPool intends to unite the reporting of all the nations on a blockchain. Our objective with this project is to build an IPFS/Filecoin-based file management app for collecting and sharing climate data. ## External Resources - Blog: https://chaine.substack.com/ (contains thinking and history) ### Process Flow Diagram Below is a high level process flow diagram delineating the stakeholders and infrastructure. ![Process Flow](https://github.com/chaine-io/climatedatapool/blob/master/process_flow_diagram.png?raw=true "Process Flow Diagram") <file_sep>// Import Fleek Storage SDK const fleekStorage = require('@fleekhq/fleek-storage-js') // Function for getting an individual file async function getFile() { const myFile = await fleekStorage.get({ apiKey: 'my-key', apiSecret: 'my-secret', key: 'filename-on-fleek', getOptions: [ 'data', 'bucket', 'key', 'hash', 'publicUrl' ], }) console.log('myFile', myFile) } // Run the function async function run() { await getFile() } // Error handling run().then(() => console.log('done')).catch(console.error)
04a33a9d409cfe520460970efdd224b4d90ca7fa
[ "Markdown", "JavaScript" ]
5
Markdown
chaine-io/climatedatapool
1a0a113e861504cdefccac20fe6878f2a50de3dc
622b597c33dfcc26d5989090d9db2d1f3ca9a68b
refs/heads/main
<file_sep>var packageBody, ground, helicopter, package; const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; function setup() { createCanvas(800, 700); //engine controls the world engine = Engine.create(); world = engine.world; //Create a Ground ground = new Ground(); //create the drop zone box1 = new DropBox(300,610,20,100); box2 = new DropBox(520,610,20,100); box3 = new DropBox(410,650,200,20); //create the helicopter helicopter = new Helicopter(); //create package package = new Box(); Engine.run(engine); } function draw() { rectMode(CENTER); background(0); //update engine Engine.update(engine); //display all the stuff package.display(); box1.display(); box2.display(); box3.display(); ground.display(); helicopter.display(); }
0237196c673578ac716a7b81b52464d4e53c314c
[ "JavaScript" ]
1
JavaScript
neil-github-007/Project-23
20cd6114076a65c04abc948d53b45bb1c348208d
6b48ec3953eb7487b5d0c5e28ef4af2f25cff039
refs/heads/main
<file_sep>FROM node:12 WORKDIR /usr/app COPY package*.json ./ COPY . . # RUN yarn add ts-node-dev --dev # RUN apt update && apt install postgresql postgresql-contrib -y RUN yarn install EXPOSE 3333<file_sep>const { update } = require('../models/Todo'); const Todo = require('../models/Todo'); module.exports = { async listAll( request, response ) { // var { completed } = request.query; var todos = await Todo.findAll(); return response.json(todos); }, async listAllCompleted( request, response ) { const todos = await Todo.findAll({ where: { completed: true } }); return response.json(todos); }, async listAllActive( request, response ) { const todos = await Todo.findAll({ where: { completed: false } }); console.log(todos) return response.json(todos); }, async store(request, response) { const { title, completed } = request.body; const todo = await Todo.create({ title, completed }); return response.json(todo); }, async update(request, response) { const { id } = request.params; const { title, completed } = request.body; const todo = await Todo.findByPk(id); if(!todo) { return response.status(400).json({ error: 'Todo not found'}); } if( title ) todo.title = title; todo.completed = completed; await todo.save(); return response.json(todo); }, async delete(request, response) { const { id } = request.params; const todo = await Todo.findByPk(id); if(!todo) { return response.status(400).json({ error: 'Todo not found'}); } await todo.destroy(); return response.json({message: 'Todo removed'}); } };<file_sep>FROM node:12 WORKDIR /usr/api COPY package*.json ./ COPY . . RUN apt update && apt install postgresql postgresql-contrib -y RUN yarn install RUN chmod +x wait-for-it.sh EXPOSE 3000<file_sep>const { Model, DataTypes } = require('sequelize'); const { UUIDV4 } = require('sequelize'); class Todo extends Model { static init(sequelize) { super.init({ id: { type: DataTypes.UUID, primaryKey: true, defaultValue: UUIDV4 }, title: DataTypes.STRING, completed: DataTypes.BOOLEAN, }, { sequelize }) } } module.exports = Todo;<file_sep>const formatDate = (value: Date): any => { return Intl.DateTimeFormat('pt-BR').format(new Date(value)); } export default formatDate;<file_sep># :rocket: TODOS [![React](https://img.shields.io/static/v1?label=React&message=>17&colorA=darkblue&color=black&logo=REACT&logoColor=white)](https://pt-br.reactjs.org/) [![Node.js](https://img.shields.io/static/v1?label=Node.js&message=>12&colorA=blue&color=black&logo=NODE&logoColor=white)](https://nodejs.org/en/about/) [![Sequelize](https://img.shields.io/static/v1?label=Sequelize&message=>6.6.2&colorA=blue&color=black&logo=SEQUELIZE&logoColor=white)](https://sequelize.org/) [![Express](https://img.shields.io/static/v1?label=Express&message=>4.7&colorA=blue&color=black&logo=EXPRESS&logoColor=white)](https://expressjs.com/pt-br/) ## :book: Descrição Projeto construído para inserir, listar, atualizar e deletar tarafeas pessoais. O front-end foi recriado a partir de um repositório já existente que tem o intuito de fornecer estruturas para organizar o aplicativo da sua forma em JavaScript. Você pode encontrar mais informações neste [link](https://todomvc.com/). Não faz parte do repositório original a implementação do back-end, no entanto para este projeto foi construída uma API REST para consumo interno com as seguintes propriedades: - todo * title * completed * creatAt * updatedAt A API possui as funcionalidades de inserir, listar, atualizar e deletar os *todos*. ## :computer: Uso ### Docker ~~~bash docker-compose up ~~~ Caso queira executar de forma independente execute na raiz do diretório: #### front-end ~~~bash yarn install ~~~ ~~~bash yarn start ~~~ ### back-end ~~~bash yarn install ~~~ ~~~bash yarn sequelize db:create ~~~ ~~~bash yarn sequelize db:migrate ~~~ ~~~bash yarn start ~~~ ## :pencil2: Autor <table> <tr> <td align="center"> <a href="https://github.com/guilhermegoncalvess"><img style="border-radius: 50%;" src="https://avatars2.githubusercontent.com/u/45895853?s=460&u=b635cebae03921120ecee9fc2d69e1c9f56de2fe&v=4" width="100px;" alt=""/> <br /> <sub> <b><NAME></b> </sub> </a> </br> <a href="https://www.linkedin.com/in/guilhermegoncalvess/"> <img src="https://img.shields.io/badge/-LinkedIn-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/guilhermegoncalvess/"/> </a> </td> </tr> </table> <file_sep>const { response } = require('express'); const express = require('express'); const TodoController = require('./controllers/TodoController') const routes = express.Router(); routes.get('/todos', TodoController.listAll); routes.get('/todos/completed', TodoController.listAllCompleted); routes.get('/todos/active', TodoController.listAllActive); routes.post('/todos', TodoController.store); routes.put('/todos/:id', TodoController.update); routes.delete('/todos/:id', TodoController.delete); module.exports = routes;
7f347003ce6e472b993637699e8f94085cf87a5c
[ "JavaScript", "TypeScript", "Dockerfile", "Markdown" ]
7
Dockerfile
guilhermegoncalvess/todos
0f670b0a023d84c77fcd027c0db776c763d2976e
621566f8860a57572420b1340feaf60c1baad381
refs/heads/master
<repo_name>byrnane/simple_test<file_sep>/src/store/index.js //libs import Vue from 'vue' import Vuex from 'vuex' //modules import auth from './modules/auth' //plugin init Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' //export store object export default new Vuex.Store({ modules: { auth, }, strict: debug, }) <file_sep>/src/router.js //libs import Vue from 'vue' import VueRouter from 'vue-router' //store import store from './store' //app pages import authPage from './pages/auth-page/auth-page' import secretPage from './pages/secret-page/secret-page' //router plugins Vue.use(VueRouter) const isntAuthenticated = (to, from, next) => { if (!store.getters.isAuthenticated) { next() return } next('/secret') } const isAuthenticated = (to, from, next) => { if (store.getters.isAuthenticated) { next() return } next('/auth') } //routes list const routes = [ { name: 'auth', path: '/auth', component: authPage, beforeEnter: isntAuthenticated, }, { name: 'secret-page', path: '/secret', component: secretPage, beforeEnter: isAuthenticated, }, //служебные роуты { name: 'global_redirect', path: '*', redirect: '/auth', meta: { type: 'service', }, }, ] //export router object export default new VueRouter({ routes, mode: 'history', }) <file_sep>/src/main.js //vendor libs import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import DataTables from 'vue-data-tables' import lang from 'element-ui/lib/locale/lang/en' import locale from 'element-ui/lib/locale' //main App entry point import app from './app' //app router import router from './router' import store from './store/' Vue.use(ElementUI) Vue.use(DataTables) locale.use(lang) //app init new Vue({ store, router, el: '#app', template: '<app/>', components: { app } }); <file_sep>/src/pages/auth-page/script.js // import api from '../../api/api' import {AUTH_REQUEST} from '../../store/actions/auth' export default { name: 'auth-page', data: function () { return { login: '', password: '', } }, methods: { signIn: function () { if (this.login !== '' && this.password !== '') { this.$store.dispatch(AUTH_REQUEST, this.login, this.password) .then(() => { this.$router.push('/secret') }) .catch((error) => { console.log('sign in error') console.log(error) }) } else { alert('login and password required') } }, }, }
cad751b2339d1cb6ef2473d60c092ed3de00f7fb
[ "JavaScript" ]
4
JavaScript
byrnane/simple_test
cfb721d1c31c9249f12564c7b107fd1dd6fb88b3
f3385304fdc28ab716dfa8398ff2d835ac9f302f
refs/heads/master
<file_sep>import boardgamegeek import time from collections import defaultdict import jinja2 import os def render(tpl_path, context): path, filename = os.path.split(tpl_path) return jinja2.Environment( loader=jinja2.FileSystemLoader(path or './') ).get_template(filename).render(context) bgg = boardgamegeek.BGGClient() c = bgg.collection('jtsmith2', exclude_subtype='boardgameexpansion', own=True) game_ids = [] for game in c: game_ids.append(game.id) games = bgg.game_list(game_ids) cats = set() for g in games: for c in g.categories: cats.add('Category: ' + c) players = ['Players: 1', 'Players: 2', 'Players: 3', 'Players: 4', 'Players: 5', 'Players: 6', 'Players: 7', 'Players: 8'] for p in players: cats.add(p) context = { 'games': games, 'cats': sorted(cats) } tex = render('bgg_template.tex', context) file = open('generated_menu.tex','w') file.write(tex) file.close() <file_sep># bgg_collection_printout Get a LaTeX document of your BoardGameGeek collection including tables for all categories.
3788db1066772e620da1b0a33458781a64ed9bdd
[ "Markdown", "Python" ]
2
Python
jtsmith2/bgg_collection_printout
46e79dfcde036fa777680db2498bcd5e6b71799e
d9ae209eac81145e96ec3a106d6a1041fdb3b0ee
refs/heads/master
<repo_name>yoliset/ejercicio-17-7js<file_sep>/README.md # ejercicio-7 Ejercicio - 7 *Inicio: posNeg ## Ingreso datos - a - b - negative ## Proceso - Si ayb uno es negativo y otro positivo .Excepto si el parámetro Negative es TRUE - Mostrar 1 // "Solo si ambos son negativos" - Si no caso contrario mostrar 0 // fin si *Fin* <file_sep>/main.js var posNeg = function(a, b, negative) { negative = Boolean(negative); if (negative == true) { if (a<0 && b<0) { return 1; } else { return 0; } } else { if ((a>0&&b<0) || (a<0&&b>0)) { return 1; } else { return 0; } } }; var evaluar = function () { var a= parseInt(document.getElementById("a").value); var b = parseInt(document.getElementById("b").value); var negative = parseInt(document.getElementById("negative").value); //console.log(a, b, negative) var salida = posNeg(a, b, negative); $('#salida').val(salida); }
8e131aee57b73aa1ce0ab245b9249dc5511b4f76
[ "Markdown", "JavaScript" ]
2
Markdown
yoliset/ejercicio-17-7js
cd73b245ab1e798251caa2a007e988940ea89cbc
e175a98050c184172195a9f2466e1838876c4b17
refs/heads/master
<repo_name>nemcek/Pokemon-3D<file_sep>/src/objects/Scene.cpp // // Created by Martin on 22. 11. 2015. // #include "src/objects/Scene.hpp" Scene::Scene() { } Scene::Scene(MasterRendererPtr masterRenderer, std::vector<LightPtr> lights, glm::mat4 projection, CameraPtr camera) { this->masterRenderer = masterRenderer; this->lights = lights; this->projection = projection; this->camera = camera; } void Scene::loadObject(MeshPtr mesh) { this->objects.push_back(mesh); } void Scene::loadGround(GroundPtr ground) { this->grounds.push_back(ground); } SceneType Scene::animate(float delta) { std::list<MeshPtr> toBeDeleted; auto i = std::begin(objects); while (i != std::end(objects)) { auto objectLoop = i->get(); SceneType sType = objectLoop->animate(*this, delta); if (sType != this->sceneType) return sType; ++i; } this->skybox->animate(delta); camera->move(); for (auto guiLoop : this->guis) { guiLoop->animate(); } i = std::begin(objects); while (i != std::end(objects)) { auto obj = i->get(); if (obj->needsDeletion) { obj->needsDeletion = false; i = objects.erase(i); } else ++i; } return sceneType; } void Scene::update() { return; } void Scene::render() { for (auto meshLoop : this->objects) { masterRenderer->processMesh(meshLoop); } for (auto groundLoop : this->grounds) { masterRenderer->processGround(groundLoop); } for (auto wrapperLoop : this->wrappers) { masterRenderer->processWrapper(wrapperLoop); } for (auto guiLoop : this->guis) { masterRenderer->processGui(guiLoop); } masterRenderer->render(this->projection, this->camera->getViewMatrix(), this->lights); } void Scene::clean() { this->masterRenderer->clean(); } void Scene::loadWrapper(MeshWrapperPtr wrapper) { this->wrappers.push_back(wrapper); this->masterRenderer->processWrapper(wrapper); } void Scene::loadGui(GuiPtr gui) { this->guis.push_back(gui); this->masterRenderer->processGui(gui); } void Scene::loadSkybox(SkyboxPtr skybox) { this->skybox = skybox; this->masterRenderer->processSkybox(skybox); } void Scene::loadMasterRenderer(MasterRendererPtr masterRenderer) { this->masterRenderer = masterRenderer; } void Scene::loadLights(std::vector<LightPtr> lights) { this->lights = lights; } void Scene::loadLight(LightPtr light) { this->lights.push_back(light); } void Scene::loadCamera(CameraPtr camera) { this->camera = camera; } void Scene::loadProjection(glm::mat4 projection) { this->projection = projection; } void Scene::loadGrounds(std::vector<GroundPtr> grounds) { for (auto groundLoop : grounds) { loadGround(groundLoop); } } bool Scene::isTPressed() { return this->inputManager->isTPressed(); } bool Scene::isWPressed() { return this->inputManager->isWPressed(); }<file_sep>/src/camera/ThirdPersonCamera.h // // Created by Martin on 16. 11. 2015. // #ifndef POKEMON3D_THIRDPERSONCAMERA_H #define POKEMON3D_THIRDPERSONCAMERA_H #include "src/objects/MainCharacter.h" #include "src/managers/InputManager.hpp" #include "src/camera/Camera.hpp" class ThirdPersonCamera : public Camera { private: glm::vec3 position; glm::vec3 *followTargetPosition; float *followTargetRotX; float *followTargetRotY; float *followTargetRotZ; float pitch; float yaw; float distance; float angle; MovableCharacterPtr movableCharacter; InputManager *inputManager; void calculateZoom(); void calculatePitch(); void calculateAngle(); float calculateHorizontalDistance(); float calculateVerticalDistance(); void calculateCameraPosition(float horizntalDistance, float verticalDistance); void initPosition(); void initPosition(glm::vec3 position); public: ThirdPersonCamera(MovableCharacterPtr movableCharacter, GLFWwindow * window, InputManager *inputManaget); void move() override; glm::mat4 getViewMatrix() override; void setFollowTarget(glm::vec3 *targetPositionVec, float *targetRotX, float *targetRotY, float *targetRotZ) override; void setFollowTarget(MovableCharacterPtr followTarget) override; void setPosition(glm::vec3 position) override; }; typedef std::shared_ptr<ThirdPersonCamera> ThirdPersonCameraPtr; #endif //POKEMON3D_THIRDPERSONCAMERA_H <file_sep>/src/objects/StreetLamp.hpp // // Created by Martin on 28. 11. 2015. // #ifndef POKEMON3D_STREETLAMP_HPP #define POKEMON3D_STREETLAMP_HPP #include "src/objects/Terrain.h" #include "src/objects/Light.hpp" #include "src/loaders/Loader.hpp" class StreetLamp : public Terrain { public: LightPtr light; // Light *light; StreetLamp(LoaderPtr loader, glm::vec3 position); }; typedef std::shared_ptr<StreetLamp> StreetLampPtr; #endif //POKEMON3D_STREETLAMP_HPP <file_sep>/src/loaders/Loader.cpp // // Created by Martin on 22. 11. 2015. // #include <iostream> #include "Loader.hpp" #include "FileLoader.h" Loader::Loader(GLuint programId) { this->programId = programId; } RawModelPtr Loader::initLoading() { auto rawModel = RawModelPtr(new RawModel()); // Activate the program glUseProgram(this->programId); // Generate a vertex array object glGenVertexArrays(1, &rawModel->vao); glBindVertexArray(rawModel->vao); return rawModel; } void Loader::clean() { // Complete the vertex array object glBindVertexArray(0); } RawModelPtr Loader::load(std::vector<GLfloat> vertex_buffer, std::vector<GLfloat> texcoord_buffer, std::vector<GLuint> index_data, std::vector<GLfloat> normals_data) { auto rawModel = initLoading(); setVertexPositions(rawModel, vertex_buffer); setTextureCoords(rawModel, texcoord_buffer, 2); setIndices(rawModel, index_data); setNormals(rawModel, normals_data); clean(); return rawModel; } RawModelPtr Loader::load(std::vector<GLfloat> vertex_buffer, std::vector<GLfloat> texcoord_buffer, int size) { auto rawModel = initLoading(); setVertexPositions(rawModel, vertex_buffer, size); setTextureCoords(rawModel, texcoord_buffer, size); rawModel->mesh_vertex_count = vertex_buffer.size() / size; clean(); return rawModel; } void Loader::setVertexPositions(RawModelPtr rawModel, std::vector<GLfloat> vertex_buffer) { setVertexPositions(rawModel, vertex_buffer, 3); } void Loader::setVertexPositions(RawModelPtr rawModel, std::vector<GLfloat> vertex_buffer, int size) { // Generate and upload a buffer with vertex positions to GPU glGenBuffers(1, &rawModel->vbo); glBindBuffer(GL_ARRAY_BUFFER, rawModel->vbo); glBufferData(GL_ARRAY_BUFFER, vertex_buffer.size() * sizeof(GLfloat), vertex_buffer.data(), GL_STATIC_DRAW); // Bind the buffer to "Position" attribute in program GLint position_attrib = glGetAttribLocation(this->programId, "Position"); glEnableVertexAttribArray(position_attrib); glVertexAttribPointer(position_attrib, size, GL_FLOAT, GL_FALSE, 0, 0); } void Loader::setTextureCoords(RawModelPtr rawModel, std::vector<GLfloat> texcoord_buffer, int size) { // Generate and upload a buffer with texture coordinates to GPU glGenBuffers(1, &rawModel->tbo); glBindBuffer(GL_ARRAY_BUFFER, rawModel->tbo); glBufferData(GL_ARRAY_BUFFER, texcoord_buffer.size() * sizeof(GLfloat), texcoord_buffer.data(), GL_STATIC_DRAW); // Bind the buffer to "TexCoord" attribute in program if (texcoord_buffer.size() > 0) { GLint texcoord_attrib = glGetAttribLocation(this->programId, "TexCoord"); glEnableVertexAttribArray(texcoord_attrib); glVertexAttribPointer(texcoord_attrib, size, GL_FLOAT, GL_FALSE, 0, 0); } else { std::cout << "Warning: OBJ file has no texture coordinates!" << std::endl; } } void Loader::setIndices(RawModelPtr rawModel, std::vector<GLuint> index_data) { // Generate and upload a buffer with indices to GPU glGenBuffers(1, &rawModel->ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rawModel->ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_data.size() * sizeof(GLuint), index_data.data(), GL_STATIC_DRAW); } void Loader::setNormals(RawModelPtr rawModel, std::vector<GLfloat> normals_data) { glGenBuffers(1, &rawModel->nbo); glBindBuffer(GL_ARRAY_BUFFER, rawModel->nbo); glBufferData(GL_ARRAY_BUFFER, normals_data.size() * sizeof(GLfloat), normals_data.data(), GL_STATIC_DRAW ); if (normals_data.size() > 0) { GLint normal_attrib = glGetAttribLocation(this->programId, "Normal"); glEnableVertexAttribArray(normal_attrib); glVertexAttribPointer(normal_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); } else { std::cout << "object has no normals!" << std::endl; } } GLuint Loader::loadTexture(const std::string &image_file) { // Create new texture object GLuint texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); // Set mipmaps glGenerateMipmap(GL_TEXTURE_2D); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, -0.4f); FileLoader::TGAFILE_t tgafile; FileLoader::LoadTGAFile(image_file.c_str(), &tgafile); std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8)); int imageType = (tgafile.bitCount / 8) == 3 ? GL_RGB : GL_RGBA; glTexImage2D(GL_TEXTURE_2D, 0, imageType, tgafile.imageWidth, tgafile.imageHeight, 0, imageType, GL_UNSIGNED_BYTE, buffer.data()); return texture_id; } GLuint Loader::loadCubeMap(std::vector<std::string> files) { GLuint textureId; glGenTextures(1, &textureId); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, textureId); for (int i = 0; i < files.size(); i++) { FileLoader::TGAFILE_t tgafile; FileLoader::LoadTGAFile(files[i].c_str(), &tgafile); std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8)); int imageType = (tgafile.bitCount / 8) == 3 ? GL_RGB : GL_RGBA; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, imageType, tgafile.imageWidth, tgafile.imageHeight, 0, imageType, GL_UNSIGNED_BYTE, buffer.data()); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return textureId; }<file_sep>/src/objects/Mesh.cpp #include <src/loaders/tiny_obj_loader.h> #include <loaders/tiny_obj_loader.h> #include "src/objects/Mesh.h" #include "Scene.hpp" Mesh::Mesh(const std::string &image_file) { this->texturedModel = TexturedModelPtr(new TexturedModel()); this->texturedModel->rawModel = RawModelPtr(new RawModel()); this->initTexture(image_file); this->position = glm::vec3(0.0f); this->rotX = 0.0f; this->rotY = 0.0f; this->rotZ = 0.0f; this->scale = 1.0f; this->radius = calculateRadius(); } Mesh::Mesh(TexturedModelPtr texturedModel, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) { this->texturedModel = texturedModel; this->position = position; this->rotX = rotX; this->rotX = rotX; this->rotX = rotX; this->scale = scale; this->radius = calculateRadius(); } Mesh::Mesh(std::shared_ptr<Mesh> mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) { this->texturedModel = mesh->texturedModel; this->position = position; this->rotX = rotX; this->rotY = rotY; this->rotZ = rotZ; this->scale = scale; this->center_point = mesh->center_point; this->radius = calculateRadius(); } Mesh::Mesh(LoaderPtr loader, const std::string &obj_file ,const std::string &image_file) { this->texturedModel = TexturedModelPtr(new TexturedModel()); this->loader = loader; //this->texturedModel->rawModel = new RawModel(); this->initTexture(image_file); this->initGeometry(obj_file); this->position = glm::vec3(0.0f); this->rotX = 0.0f; this->rotY = 0.0f; this->rotZ = 0.0f; this->scale = 1.0f; this->radius = calculateRadius(); } Mesh::Mesh(LoaderPtr loader, const std::string & obj_file, const std::string &image_file, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) { this->texturedModel = TexturedModelPtr(new TexturedModel()); this->loader = loader; //this->texturedModel->rawModel = new RawModel(); this->initGeometry(obj_file); this->initTexture(image_file); this->position = position; this->rotX = rotX; this->rotY = rotY; this->rotZ = rotZ; this->scale = scale; this->radius = calculateRadius(); } Mesh::Mesh(LoaderPtr loader, const std::string & obj_file, const std::string &image_file, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) { this->texturedModel = TexturedModelPtr(new TexturedModel()); this->loader = loader; //this->texturedModel->rawModel = new RawModel(); this->initGeometry(obj_file); this->initTexture(image_file); this->position = position; this->rotX = rotX; this->rotY = rotY; this->rotZ = rotZ; this->scale = scale; this->texturedModel->texture->reflectivity = reflectivity; this->texturedModel->texture->shineDamper = shineDamper; this->radius = calculateRadius(); } void Mesh::initGeometry(const std::string &obj_file) { // Load OBJ file std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; tinyobj::center_point_t center_point = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; std::string err = tinyobj::LoadObj(shapes, materials, obj_file.c_str(), &center_point); this->center_point = center_point; if (!err.empty()) { std::cerr << err << std::endl; std::cerr << "Failed to load OBJ file " << obj_file << "!" << std::endl; return; } tinyobj::mesh_t mesh = shapes[0].mesh; this->texturedModel->rawModel = this->loader->load(mesh.positions, mesh.texcoords, mesh.indices, mesh.normals); this->texturedModel->rawModel->mesh_indices_count = (int) mesh.indices.size(); } // Load a new image from a raw RGB file directly into OpenGL memory void Mesh::initTexture(const std::string &image_file) { // Create new texture object GLuint texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); this->texturedModel->texture = TexturePtr(new Texture(texture_id)); // Set mipmaps glGenerateMipmap(GL_TEXTURE_2D); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, -0.4f); FileLoader::TGAFILE_t tgafile; FileLoader::LoadTGAFile(image_file.c_str(), &tgafile); std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8)); int imageType = (tgafile.bitCount / 8) == 3 ? GL_RGB : GL_RGBA; glTexImage2D(GL_TEXTURE_2D, 0, imageType, tgafile.imageWidth, tgafile.imageHeight, 0, imageType, GL_UNSIGNED_BYTE, buffer.data()); } void Mesh::render() { // // Activate the program // glUseProgram(this->program_id); // // // Bind the texture to "Texture" uniform in program // GLint texture_attrib = glGetUniformLocation(this->program_id, "Texture"); // glUniform1i(texture_attrib, 0); // glActiveTexture(GL_TEXTURE0 + 0); // glBindTexture(GL_TEXTURE_2D, this->texture_id); // // // Upload model matrix to GPU // GLint model_uniform = glGetUniformLocation(this->program_id, "ModelMatrix"); // glUniformMatrix4fv(model_uniform, 1, GL_FALSE, glm::value_ptr(this->matrix)); // // // Draw object // glBindVertexArray(this->vao); // glDrawElements(GL_TRIANGLES, this->mesh_indices_count, GL_UNSIGNED_INT, 0); // glBindVertexArray(NULL); } center_t Mesh::calculateCenter() { return center_t {( this->center_point.X_min + this->center_point.X_max ) / 2.0f, ( this->center_point.Y_min + this->center_point.Y_max ) / 2.0f, ( this->center_point.Z_min + this->center_point.Z_max ) / 2.0f }; } glm::mat4 Mesh::createTransformationMatrix() { this->texturedModel->matrix = Transformations::createTransformationMatrix(this->position, this->rotX, this->rotY, this->rotZ, this->scale); return this->texturedModel->matrix; } glm::vec3 Mesh::getCenter() { return glm::vec3(this->texturedModel->matrix[3].x, this->center.y, this->texturedModel->matrix[3].z); } SceneType Mesh::animate(Scene &scene, float delta) { return scene.sceneType; } float Mesh::calculateRadius() { center_t c = calculateCenter(); if (this->center_point.X_max - c.x < this->center_point.Z_max - c.z) { return (this->center_point.Z_max - c.z) * scale; } else { return (this->center_point.X_max - c.x) * scale; } } void Mesh::setPosition(glm::vec3 position) { this->position = position; } void Mesh::setRotation(glm::vec3 rotation) { this->rotX = rotation.x; this->rotY = rotation.y; this->rotZ = rotation.z; } void Mesh::setScale(float scale) { this->scale = scale; }<file_sep>/src/objects/StreetLamp.cpp // // Created by Martin on 28. 11. 2015. // #include "src/objects/StreetLamp.hpp" StreetLamp::StreetLamp(LoaderPtr loader, glm::vec3 position) : Terrain(loader, "models/objects/StreetLamp.obj", "models/textures/StreetLamp.tga", position, 0.0f, 0.0f, 0.0f, 0.7f) { this->light = LightPtr(new Light(glm::vec3(position.x, position.y + 5.0f, position.z), glm::vec3(2.1f, 2.0f, 1.0f), glm::vec3(1.0f, 0.02f, 0.002f))); } //LightPtr StreetLamp::light;<file_sep>/src/shaders/StaticShader.hpp // // Created by Martin on 16. 11. 2015. // #ifndef POKEMON3D_STATICSHADER_H #define POKEMON3D_STATICSHADER_H #include "src/shaders/ShaderProgram.hpp" #include "src/objects/Light.hpp" class StaticShader : public ShaderProgram { private: const int number_of_lights = 4; GLint modelMatrix; GLint texture; GLint projection; GLint view; GLint *lightPosition; GLint *lightColor; GLint *attenuation; GLint reflectivity; GLint shineDamper; GLint skyColor; GLint useFakeLighting; public: StaticShader(); void bindAttributes() override; void getAllUniformLocations() override; void loadModelMatrix(glm::mat4 matrix); void loadTextureUni(GLint texture_id); void loadProjectionMatrix(glm::mat4 projection); void loadViewMatrix(glm::mat4 view); void loadLights(std::vector<LightPtr> lights); void loadShining(float reflectivity, float shineDamper); void loadSkyColor(glm::vec3 skyColor); void loadUseFakeLighting(bool useFakeLigting); }; typedef std::shared_ptr<StaticShader> StaticShaderPtr; #endif //POKEMON3D_STATICSHADER_H <file_sep>/src/objects/Attack.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_ATTACK_HPP #define POKEMON3D_ATTACK_HPP #include "src/objects/MovableCharacter.hpp" #include "src/enums/Enums.hpp" class Pokemon; class Attack : public MovableCharacter { private: float movementSpeed = 3.33f; float rotateSpeed = 40.0f; float startingZpos; public: float knockbackForce = 0.2f; float collisionDelay = 0.0f; Attack(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Attack(TexturedModelPtr, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float movementSpeed, float rotationSpeed); Attack(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float movementSpeed, float rotationSpeed); SceneType move(Scene &scene, float delta); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<Attack> AttackPtr; #endif //POKEMON3D_ATTACK_HPP <file_sep>/src/camera/Arcball.cpp // // Arcball.cpp // Arcball // // Created by <NAME> on 12/03/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #include "src/camera/Arcball.h" /** * Constructor. * @param roll_speed the speed of rotation */ Arcball::Arcball( int window_width, int window_height, GLfloat roll_speed, bool x_axis, bool y_axis ) { this->windowWidth = window_width; this->windowHeight = window_height; this->mouseEvent = 0; this->rollSpeed = roll_speed; this->angle = 0.0f; this->camAxis = glm::vec3(0.0f, 1.0f, 0.0f); this->xAxis = x_axis; this->yAxis = y_axis; this->first_move = true; this->enabled = false; } /** * Convert the mouse cursor coordinate on the window (i.e. from (0,0) to (windowWidth, windowHeight)) * into normalized screen coordinate (i.e. (-1, -1) to (1, 1) */ glm::vec3 Arcball::toScreenCoord( double x, double y ) { glm::vec3 coord(0.0f); if( xAxis ) coord.x = (2 * x - windowWidth ) / windowWidth; if( yAxis ) coord.y = -(2 * y - windowHeight) / windowHeight; /* Clamp it to border of the windows, comment these codes to allow rotation when cursor is not over window */ coord.x = glm::clamp( coord.x, -1.0f, 1.0f ); coord.y = glm::clamp( coord.y, -1.0f, 1.0f ); float length_squared = coord.x * coord.x + coord.y * coord.y; if( length_squared <= 1.0 ) coord.z = sqrt( 1.0 - length_squared ); else coord = glm::normalize( coord ); return coord; } /** * Check whether we should start the mouse event * Event 0: when no tracking occured * Event 1: at the start of tracking, recording the first cursor pos * Event 2: tracking of subsequent cursor movement */ void Arcball::mouseButtonCallback( GLFWwindow * window, int button, int action, int ){ if ( action == GLFW_PRESS && button == GLFW_MOUSE_BUTTON_LEFT ) { mouseEvent = 1; enabled = true; } else { mouseEvent = 0; enabled = false; } } void Arcball::cursorCallback( GLFWwindow *, double x, double y ){ if( mouseEvent == 0 ) { return; } else if( mouseEvent == 1 && first_move ) { /* Start of trackball, remember the first position */ prevPos = toScreenCoord( x, y ); mouseEvent = 2; first_move = false; return; } /* Tracking the subsequent */ currPos = toScreenCoord( x, y ); /* Calculate the angle in radians, and clamp it between 0 and 90 degrees */ // angle = acos( std::min(1.0f, glm::dot(prevPos, currPos) )); /* Cross product to get the rotation axis, but it's still in camera coordinate */ camAxis = glm::cross( prevPos, currPos ); } /** * Create rotation matrix within the camera coordinate, * multiply this matrix with view matrix to rotate the camera */ glm::mat4 Arcball::createViewRotationMatrix() { return glm::rotate( glm::degrees(angle) * rollSpeed, camAxis ); } glm::mat4 Arcball::createViewRotationMatrix(glm::mat4 mat) { return glm::rotate( mat, glm::degrees(angle) * rollSpeed, camAxis ); } /** * Create rotation matrix within the world coordinate, * multiply this matrix with model matrix to rotate the object */ glm::mat4 Arcball::createModelRotationMatrix( glm::mat4& view_matrix ){ glm::vec3 axis = glm::inverse(glm::mat3(view_matrix)) * camAxis; return glm::rotate( glm::degrees(angle) * rollSpeed, axis ); }<file_sep>/src/skybox/SkyboxRenderer.cpp // // Created by Martin on 28. 11. 2015. // #include "src/skybox/SkyboxRenderer.hpp" SkyboxRenderer::SkyboxRenderer(SkyboxShaderPtr shader) { this->shader = shader; } void SkyboxRenderer::render(SkyboxPtr skybox, glm::mat4 viewMatrix, glm::mat4 projectionMatrix, glm::vec3 fogColor) { shader->start(); shader->loadProjectionMatrix(projectionMatrix); shader->loadViewMatrix(viewMatrix, skybox->rotation); shader->loadFogColor(fogColor); glBindVertexArray(skybox->cube->vao); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->textureId); glDrawArrays(GL_TRIANGLES, 0, skybox->cube->mesh_vertex_count); glBindVertexArray(0); shader->stop(); }<file_sep>/src/camera/Arcball.h // // Arcball.h // Arcball // // Created by <NAME> on 12/03/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef __Arcball__Arcball__ #define __Arcball__Arcball__ #include <iostream> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtc/matrix_inverse.hpp> #include "glm/ext.hpp" class Arcball { private: int windowWidth; int windowHeight; int mouseEvent; GLfloat rollSpeed; GLfloat angle ; glm::vec3 prevPos; glm::vec3 currPos; glm::vec3 camAxis; bool first_move; bool xAxis; bool yAxis; public: bool enabled; Arcball( int window_width, int window_height, GLfloat roll_speed = 1.0f, bool x_axis = true, bool y_axis = true ); glm::vec3 toScreenCoord( double x, double y ); void mouseButtonCallback( GLFWwindow * window, int button, int action, int mods ); void cursorCallback( GLFWwindow *, double x, double y ); glm::mat4 createViewRotationMatrix(); glm::mat4 createViewRotationMatrix(glm::mat4); glm::mat4 createModelRotationMatrix( glm::mat4& view_matrix ); }; #endif /* defined(__Arcball__Arcball__) */<file_sep>/src/animations/Keyframe.hpp // // Created by Martin on 7. 12. 2015. // #ifndef POKEMON3D_KEYFRAME_HPP #define POKEMON3D_KEYFRAME_HPP #include <memory> #include <glm/glm.hpp> class Keyframe { public: Keyframe(float time, glm::vec3 rot); Keyframe(float time, glm::vec3 pos, glm::vec3 rot); ~Keyframe(); glm::vec3 position; glm::vec3 rotation; float time; bool useObjectsPosition = false; }; typedef std::shared_ptr<Keyframe> KeyframePtr; #endif //POKEMON3D_KEYFRAME_HPP <file_sep>/src/objects/OtherCharacter.hpp // // Created by Martin on 19. 11. 2015. // #ifndef POKEMON3D_OTHERCHARACTER_HPP #define POKEMON3D_OTHERCHARACTER_HPP #include "src/objects/MovableCharacter.hpp" class OtherCharacter : public MovableCharacter { private: float runSpeed = 10.0; float turnSpeed = 160.0f; void generateMovement(); public: OtherCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); OtherCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<OtherCharacter> OtherCharacterPtr; #endif //POKEMON3D_OTHERCHARACTER_HPP <file_sep>/src/models/RawModel.cpp // // Created by Martin on 22. 11. 2015. // #include "src/models/RawModel.hpp" RawModel::RawModel() { }<file_sep>/src/gui/GuiTexture.hpp // // Created by Martin on 23. 11. 2015. // #ifndef POKEMON3D_GUITEXTURE_HPP #define POKEMON3D_GUITEXTURE_HPP #include <memory> #include <glm/glm.hpp> class GuiTexture { public: int textureId; glm::vec2 position; glm::vec2 scale; GuiTexture(int textureId, glm::vec2 position, glm::vec2 scale); }; typedef std::shared_ptr<GuiTexture> GuiTexturePtr; #endif //POKEMON3D_GUITEXTURE_HPP <file_sep>/src/objects/Pokemon.cpp // // Created by Martin on 30. 11. 2015. // #include <loaders/tiny_obj_loader.h> #include "src/objects/Pokemon.hpp" #include "Scene.hpp" Pokemon::Pokemon(unsigned short id, LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart) : MainCharacter(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, inputManager) { this->id = id; this->attackObj = AttackPtr(new Attack(loader, attack_obj_file, attack_image_name, this->position, 0.0f, 0.0f, 0.0f, 0.05)); this->canAttack = canAttackAtStart; this->startingPos = position; } Pokemon::Pokemon(unsigned short id, LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart) : MainCharacter(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper, inputManager) { this->id = id; this->attackObj = AttackPtr(new Attack(loader, attack_obj_file, attack_image_name, this->position, 0.0f, 0.0f, 0.0f, 0.05)); this->canAttack = canAttackAtStart; this->startingPos = position; } Pokemon::Pokemon(unsigned short id, LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart) : MainCharacter(loader, mesh, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper, inputManager) { this->id = id; this->attackObj = AttackPtr(new Attack(loader, attack_obj_file, attack_image_name, this->position, 0.0f, 0.0f, 0.0f, 0.05)); this->canAttack = canAttackAtStart; this->startingPos = position; } SceneType Pokemon::animate(Scene &scene, float delta) { if (scene.sceneType == SceneType::BATTLE_SCEEN) { attackDelay += delta; if (attackDelay > 5.0f) canAttack = true; for (auto objectLoop : scene.objects) { if (objectLoop.get() == this) continue; auto att = std::dynamic_pointer_cast<Attack>(objectLoop); if (!att) { continue; } else { if (att->collisionDelay > 0.5f ) { if (collidedWith(objectLoop)) { objectLoop->needsDeletion = true; attackDelay = 0.0f; this->currentHp -= 1; if (this->currentHp <= 0) return SceneType::MAIN_SCEEN; this->position.z += startingPos.z < 0.0f ? -att->knockbackForce : att->knockbackForce; } } } } if (scene.isTPressed() && canAttack) { canAttack = false; attack(scene); } } if (scene.sceneType == SceneType::MAIN_SCEEN) { if (this->animation != nullptr) { this->animation->animate(delta); this->position = this->animation->position; this->rotX = this->animation->rotation.x; this->rotY = this->animation->rotation.y; this->rotZ = this->animation->rotation.z; } } createTransformationMatrix(); return scene.sceneType; } void Pokemon::checkInputs() { } void Pokemon::attack(Scene &scene) { int count = (int)Math::random(1.0f, 10.0f); generateAttacks(count, scene); } void Pokemon::generateAttacks(int count, Scene &scene) { // this->attacks.clear(); for (int i = 0; i < count; i++) { auto localAttack = AttackPtr(new Attack(attackObj, position, attackObj->rotX, attackObj->rotY, attackObj->rotZ, attackObj->scale, Math::random(3.0f, 4.0f), Math::random(0.0f, 180.0f))); localAttack->position.z = this->position.z - this->radius; localAttack->position.y = Math::random(this->center_point.Y_min * scale, this->center_point.Y_max * scale); localAttack->position.x = Math::random(this->center_point.X_min * scale, this->center_point.X_max * scale); scene.objects.push_back(localAttack); } // return attacks; } <file_sep>/src/repository/PokemonRepository.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_POKEMONREPOSITORY_HPP #define POKEMON3D_POKEMONREPOSITORY_HPP #include "src/objects/Pokemon.hpp" #include "src/repository/Repository.hpp" class PokemonRepository : public Repository { private: std::vector<PokemonPtr> pokemons; public: PokemonRepository(); PokemonPtr findPokemon(unsigned short id); void add(PokemonPtr pokemon); }; typedef std::shared_ptr<PokemonRepository> PokemonRepositoryPtr; #endif //POKEMON3D_POKEMONREPOSITORY_HPP <file_sep>/src/wrappers/GrassWrapper.hpp // // Created by Martin on 8. 12. 2015. // #ifndef POKEMON3D_GRASSWRAPPER_HPP #define POKEMON3D_GRASSWRAPPER_HPP #include "src/objects/Grass.hpp" #include "src/animations/Animation.hpp" class GrassWrapper { private: GrassPtr mainGrass; AnimationPtr grassAnimation; LoaderPtr loader; void initGrassAnimation(); public: GrassWrapper(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); GrassWrapper(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); void generateGrass(glm::vec2 bottomLeft, glm::vec2 topRight); std::vector<GrassPtr> grassParts; }; typedef std::shared_ptr<GrassWrapper> GrassWrapperPtr; #endif //POKEMON3D_GRASSWRAPPER_HPP <file_sep>/src/objects/PlayerPokemon.hpp // // Created by Martin on 7. 12. 2015. // #ifndef POKEMON3D_MAINPOKEMON_HPP #define POKEMON3D_MAINPOKEMON_HPP #include "src/objects/Pokemon.hpp" class PlayerPokemon : public Pokemon { private: public: PlayerPokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); PlayerPokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); PlayerPokemon(unsigned short id, LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<PlayerPokemon> PlayerPokemonPtr; #endif //POKEMON3D_MAINPOKEMON_HPP <file_sep>/src/objects/OtherCharacter.cpp // // Created by Martin on 19. 11. 2015. // #include "src/objects/OtherCharacter.hpp" #include "Scene.hpp" OtherCharacter::OtherCharacter(LoaderPtr loader, const std::string & obj_file, const std::string &image_file, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : MovableCharacter(loader, obj_file, image_file, position, rotX, rotY, rotZ, scale) { } OtherCharacter::OtherCharacter(LoaderPtr loader, const std::string &obj_file, const std::string &image_file, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : MovableCharacter(loader, obj_file, image_file, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper) { } SceneType OtherCharacter::animate(Scene &scene, float delta) { generateMovement(); move(scene, delta); createTransformationMatrix(); return scene.sceneType; } void OtherCharacter::generateMovement() { if (rand()) { int moveForward = rand() % 3; switch (moveForward) { case 0: currentSpeed = runSpeed; break; case 1: // currentSpeed = -runSpeed; // break; case 2: currentSpeed = 0.0f; } int rotate = rand() % 3; switch (rotate) { case 0: currentTurnSpeed = turnSpeed; break; case 1: currentTurnSpeed = -turnSpeed; break; case 2: currentTurnSpeed = 0.0f; } } }<file_sep>/src/gui/GuiShader.cpp // // Created by Martin on 23. 11. 2015. // #include "src/gui/GuiShader.hpp" GuiShader::GuiShader() : ShaderProgram("src/shaders/vert_gui.glsl", "src/shaders/frag_gui.glsl") { getAllUniformLocations(); // bindAttributes(); } void GuiShader::getAllUniformLocations() { this->matrix = getUniformLocation("ModelMatrix"); this->texture = getUniformLocation("Texture"); } void GuiShader::loadModelMatrix(glm::mat4 matrix) { loadMatrix(this->matrix, matrix); } void GuiShader::bindAttributes() { bindAttribute(0, "Position"); } void GuiShader::loadTextureUni(GLint texture_id) { loadTexture(this->texture, texture_id); } <file_sep>/src/textures/TerrainTexturePack.hpp // // Created by Martin on 19. 11. 2015. // #ifndef POKEMON3D_TERRAINTEXTUREPACK_HPP #define POKEMON3D_TERRAINTEXTUREPACK_HPP #include "src/textures/TerrainTexture.hpp" class TerrainTexturePack { private: public: TerrainTexturePtr backgroundTexture; TerrainTexturePtr rTexture; TerrainTexturePtr gTexture; TerrainTexturePtr bTexture; // TerrainTexture *backgroundTexture; // TerrainTexture *rTexture; // TerrainTexture *gTexture; // TerrainTexture *bTexture; TerrainTexturePack(TerrainTexturePtr backgroundTexture, TerrainTexturePtr rTexture, TerrainTexturePtr gTexture, TerrainTexturePtr bTexture); }; typedef std::shared_ptr<TerrainTexturePack> TerrainTexturePackPtr; #endif //POKEMON3D_TERRAINTEXTUREPACK_HPP <file_sep>/src/shaders/GroundShader.cpp // // Created by Martin on 17. 11. 2015. // #include "src/shaders/GroundShader.hpp" GroundShader::GroundShader() : ShaderProgram("src/shaders/vert_ground.glsl", "src/shaders/frag_ground.glsl") { getAllUniformLocations(); } void GroundShader::bindAttributes() { this->bindAttribute(0, "FragmentColor"); } void GroundShader::getAllUniformLocations() { this->modelMatrix = getUniformLocation("ModelMatrix"); this->texture = getUniformLocation("Texture"); this->projection = getUniformLocation("ProjectionMatrix"); this->view = getUniformLocation("ViewMatrix"); this->reflectivity = getUniformLocation("reflectivity"); this->shineDamper = getUniformLocation("shineDamper"); this->skyColor = getUniformLocation("skyColor"); this->backgroundTexture = getUniformLocation("BackgroundTexture"); this->rTexture = getUniformLocation("RTexture"); this->gTexture = getUniformLocation("GTexture"); this->bTexture = getUniformLocation("BTexture"); this->blendMap = getUniformLocation("BlendMap"); this->lightPosition = new int[number_of_lights]; this->lightColor = new int[number_of_lights]; this->attenuation = new int[number_of_lights]; for (int i = 0; i < number_of_lights; i++) { this->lightPosition[i] = getUniformLocation("lightPosition[" + std::to_string(i) + "]"); this->lightColor[i] = getUniformLocation("lightColor[" + std::to_string(i) + "]"); this->attenuation[i] = getUniformLocation("attenuation[" + std::to_string(i) + "]"); } } void GroundShader::loadModelMatrix(glm::mat4 matrix) { loadMatrix(this->modelMatrix, matrix); } void GroundShader::loadTextureUni(GLint texture_id) { loadTexture(this->texture, texture_id); } void GroundShader::loadProjectionMatrix(glm::mat4 projection) { loadMatrix(this->projection, projection); } void GroundShader::loadViewMatrix(glm::mat4 view) { loadMatrix(this->view, view); } void GroundShader::loadLights(std::vector<LightPtr> lights) { for (int i = 0; i < number_of_lights; i++) { if (i < lights.size()) { loadVector(this->lightPosition[i], lights[i]->position); loadVector(this->lightColor[i], lights[i]->color); loadVector(this->attenuation[i], lights[i]->attenuation); } else { loadVector(this->lightPosition[i], glm::vec3(0.0f)); loadVector(this->lightColor[i], glm::vec3(0.0f)); loadVector(this->attenuation[i], glm::vec3(1.0f, 0.0f, 0.0f)); } } } void GroundShader::loadSkyColor(glm::vec3 skyColor) { loadVector(this->skyColor, skyColor); } void GroundShader::connectTextureUnits() { loadInt(this->backgroundTexture, 0); loadInt(this->rTexture, 1); loadInt(this->gTexture, 2); loadInt(this->bTexture, 3); loadInt(this->blendMap, 4); } void GroundShader::loadShining(float reflectivity, float shineDamper) { loadFloat(this->reflectivity, reflectivity); loadFloat(this->shineDamper, shineDamper); }<file_sep>/src/scenes/BattleScene.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_BATTLESCENE_HPP #define POKEMON3D_BATTLESCENE_HPP #include "src/objects/Scene.hpp" #include "src/objects/PlayerPokemon.hpp" #include "src/objects/EnemyPokemon.hpp" #include "src/repository/Repository.hpp" class BattleScene : public Scene { private: glm::vec3 cameraPosition = glm::vec3(0.0f); float cameraRotX = 0.0f; float cameraRotY = 180.0f; float cameraRotZ = 0.0f; PokemonData playersPokemonData { 0, glm::vec3(0.0f, 180.0f, 0.0f), glm::vec3(0.0f, 0.0f, 5.0f), 0.15f, 20 }; PokemonData enemyPokemonData { 0, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -5.0f), 0.15f, 20 }; PokemonPtr playersPokemon; PokemonPtr enemyPokemon; std::vector<AttackPtr> attacks; void preparePokemon(PokemonPtr pokemon, PokemonData *pokemonData); void initLights(); public: BattleScene(MasterRendererPtr masterRenderer, CameraPtr camera, LoaderPtr loader, InputManager *inputManager, PlayerPokemonPtr playersPokemon, EnemyPokemonPtr enemyPokemon, std::vector<GroundPtr> grounds, SkyboxPtr skybox); void update() override; }; #endif //POKEMON3D_BATTLESCENE_HPP <file_sep>/src/objects/Grass.hpp // // Created by Martin on 8. 12. 2015. // #ifndef POKEMON3D_GRASS_HPP #define POKEMON3D_GRASS_HPP #include "src/objects/Terrain.h" #include "src/animations/Animation.hpp" #include "src/enums/Enums.hpp" class Grass : public Terrain { private: std::vector<std::shared_ptr<Grass>> grassParts; float stepTime = 0.0f; public: Grass(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Grass(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); Grass(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Grass(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); SceneType animate(Scene &scene, float delta) override; void initAnimation(); bool useAnimation; bool isAnimating = false; AnimationPtr animation; }; typedef std::shared_ptr<Grass> GrassPtr; #endif //POKEMON3D_GRASS_HPP <file_sep>/src/repository/Repository.cpp // // Created by Martin on 30. 11. 2015. // #include "src/repository/Repository.hpp" Repository::Repository() { }<file_sep>/src/objects/MainCharacter.cpp // // Created by Martin on 15. 11. 2015. // #include "src/objects/MainCharacter.h" #include "Scene.hpp" MainCharacter::MainCharacter(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager) : MovableCharacter(loader, object_name, file_name, position, rotX, rotY, rotZ, scale) { this->inputManager = inputManager; } MainCharacter::MainCharacter(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager) : MovableCharacter(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper) { this->inputManager = inputManager; } MainCharacter::MainCharacter(LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager) : MovableCharacter(mesh, position, rotX, rotY, rotZ, scale) { this->inputManager = inputManager; } SceneType MainCharacter::animate(Scene &scene, float delta) { checkInputs(); move(scene, delta); createTransformationMatrix(); return scene.sceneType; } void MainCharacter::checkInputs() { if (inputManager->isWPressed()) { currentSpeed = runSpeed; } else if (inputManager->isSPressed()) { currentSpeed = -runSpeed; } else { currentSpeed = 0.0f; } if (inputManager->isAPressed()) { currentTurnSpeed = turnSpeed; } else if (inputManager->isDPressed()) { currentTurnSpeed = -turnSpeed; } else { currentTurnSpeed = 0.0f; } }<file_sep>/CMakeLists.txt # This CMake script is mainly designed for CLion IDE and QTCreator projects on Windows # It should find bundled binary dependencies automatically when using MinGW # On Linux and Mac the dependencies (glm, glew, glfw) need to be installed manually cmake_minimum_required ( VERSION 3.1 ) project( Pokemon3D CXX ) # # CONFIGURATION # # Basic CMake settings set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/_install) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake) set(CMAKE_CXX_STANDARD 11) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # Warnings for Debug mode option(USE_STRICT_COMPILE_WARNINGS "Use strict compilation warnings in debug mode." ON) if (USE_STRICT_COMPILE_WARNINGS) # Assuming Clang and GCC set(STRICT_COMPILE_WARNINGS "-Wpedantic -Wall -Wfloat-equal -Wextra -Wsign-promo -Wsign-compare -Wconversion -Wno-sign-conversion -Wno-unused-parameter") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${STRICT_COMPILE_WARNINGS}") endif () # Make sure GLM uses radians add_definitions ( -DGLM_FORCE_RADIANS ) # Add custom target for installation in CLion add_custom_target(run_install COMMAND ${CMAKE_MAKE_PROGRAM} install) # Use generate_shader function to vonvert .glsl sources to C++ headers include(shaders) # # DEPENDENCIES # # Set up external dependencies for Wwindows users if ( MINGW ) set ( CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${CMAKE_SOURCE_DIR}/dependencies/mingw/include/" ) set ( CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${CMAKE_SOURCE_DIR}/dependencies/mingw/lib/" ) endif () # Find dependencies find_package ( GLFW3 REQUIRED ) find_package ( GLEW REQUIRED ) find_package ( GLM REQUIRED ) find_package ( OpenGL REQUIRED ) # Set default installation destination if (NOT CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "../_install") endif () file(GLOB pokemon_main "src/*.cpp") file(GLOB pokemon_camera "src/camera/*.cpp") file(GLOB pokemon_loaders "src/loaders/*.cpp") file(GLOB pokemon_objects "src/objects/*.cpp") file(GLOB pokemon_shaders "src/shaders/*.cpp") file(GLOB pokemon_engine "src/engine/*.cpp") file(GLOB pokemon_textures "src/textures/*.cpp") file(GLOB pokemon_models "src/models/*.cpp") file(GLOB pokemon_wrappers "src/wrappers/*.cpp") file(GLOB pokemon_extensions "src/extensions/*.cpp") file(GLOB pokemon_managers "src/managers/*.cpp") file(GLOB pokemon_gui "src/gui/*.cpp") file(GLOB pokemon_skybox "src/skybox/*.cpp") file(GLOB pokemon_repository "src/repository/*.cpp") file(GLOB pokemon_scenes "src/scenes/*.cpp") file(GLOB pokemon_animations "src/animations/*.cpp") file(GLOB pokemon_enums "src/enums/*.cpp") file(GLOB pokemon_shaders_programs "src/shaders/*.glsl") # Include header directories include_directories ( src ${GLFW_INCLUDE_DIRS} ${GLEW_INCLUDE_DIRS} ${GLM_INCLUDE_DIRS} ${OPENGL_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) # Prepare libraries for linking set ( LIBRARIES ${OPENGL_LIBRARIES} ${GLFW_LIBRARIES} ${GLEW_LIBRARIES} libpokemon3d) # Pokemon3D library add_library(libpokemon3d STATIC ${pokemon_camera} ${pokemon_loaders} ${pokemon_objects} ${pokemon_shaders} ${pokemon_engine} ${pokemon_textures} ${pokemon_models} ${pokemon_wrappers} ${pokemon_extensions} ${pokemon_managers} ${pokemon_gui} ${pokemon_skybox} ${pokemon_repository} ${pokemon_scenes} ${pokemon_animations} ${pokemon_enums}) target_link_libraries(libpokemon3d ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES}) # # TARGETS # # gl_pokemon set ( POKEMON3D_SRC src/gl_pokemon.cpp ${pokemon_camera} ${pokemon_loaders} ${pokemon_objects} ${pokemon_shaders} ${pokemon_engine} ${pokemon_textures} ${pokemon_models} ${pokemon_wrappers} ${pokemon_extensions} ${pokemon_managers} ${pokemon_gui} ${pokemon_skybox} ${pokemon_repository} ${pokemon_scenes} ${pokemon_animations} ${pokemon_enums}) generate_shaders( POKEMON3D_SHADERS src/shaders/frag_ground.glsl src/shaders/vert_ground.glsl src/shaders/frag_pokemon.glsl src/shaders/vert_pokemon.glsl src/shaders/frag_texture.glsl src/shaders/vert_texture.glsl src/shaders/vert_gui.glsl src/shaders/frag_gui.glsl src/shaders/vert_skybox.glsl src/shaders/frag_skybox.glsl) add_executable ( Pokemon3D ${POKEMON3D_SRC} ${POKEMON3D_SHADERS}) target_link_libraries( Pokemon3D ${LIBRARIES} ) install ( TARGETS Pokemon3D DESTINATION . ) #install ( FILES shaders/gl_pokemon.vert shaders/gl_pokemon.frag models/objects/Pokecenter.obj models/objects/Trainer.rgb cursor.obj DESTINATION . ) # ADD YOUR PROJECT HERE #add_executable( my_project my_project.cpp my_project_other.cpp ) #target_link_libraries( my_project ${LIBRARIES} ) #install ( TARGETS my_project DESTINATION . ) #install ( FILES my_project.file my_project.vert my_project.frag DESTINATION . ) # # INSTALLATION # install(DIRECTORY models DESTINATION .) install(FILES ${pokemon_shaders_programs} DESTINATION src/shaders) # Install dlls to destination when on Windows if ( MINGW ) install ( FILES ${GLFW_LIBRARIES} ${GLEW_LIBRARIES} DESTINATION . ) # Install dlls into binary dir for development and debugging file ( COPY ${GLFW_LIBRARIES} ${GLEW_LIBRARIES} DESTINATION ${CMAKE_BINARY_DIR} ) endif () <file_sep>/src/textures/TerrainTexture.cpp // // Created by Martin on 19. 11. 2015. // #include "src/textures/TerrainTexture.hpp" TerrainTexture::TerrainTexture(int texture_id) { this->textureId = texture_id; }<file_sep>/src/objects/Terrain.h // // Created by Martin on 14. 11. 2015. // #ifndef PPGSO_ENVIROMENT_H #define PPGSO_ENVIROMENT_H #include "src/objects/Mesh.h" #include "src/enums/Enums.hpp" using namespace std; class Terrain: public Mesh { private: public: Terrain(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Terrain(LoaderPtr loader, const std::string & object_name, const std::string & file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); Terrain(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Terrain(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<Terrain> TerrainPtr; #endif //PPGSO_ENVIROMENT_H<file_sep>/src/gui/Healthbar.cpp // // Created by Martin on 25. 11. 2015. // #include "src/gui/Healthbar.hpp" Healthbar::Healthbar(const std::string &fillImage, const std::string &borderImage, LoaderPtr loader, HealthbarPosition position) : Gui() { init(loader, position, fillImage, borderImage); this->guiTextures.push_back(fill); this->guiTextures.push_back(border); this->pokemon = pokemon; this->lastHp = pokemon->maxHp; this->oneHealthProtion = this->fill->scale.x / pokemon->maxHp; } Healthbar::Healthbar(PokemonPtr pokemon, const std::string &fillImage, const std::string &borderImage, LoaderPtr loader, HealthbarPosition position) : Gui() { init(loader, position, fillImage, borderImage); this->guiTextures.push_back(fill); this->guiTextures.push_back(border); this->pokemon = pokemon; this->lastHp = pokemon->maxHp; this->oneHealthProtion = this->fill->scale.x / pokemon->maxHp; } void Healthbar::takeDamage(int damage) { float damageToTake = damage * this->oneHealthProtion; float xScale = fill->scale.x; float xPos = fill->position.x; // prevents from going to negative health if (xScale <= 0 || xScale - damageToTake <= 0) { fill->scale = glm::vec2(0.0f, fill->scale.y); return; } fill->scale = glm::vec2(xScale - damageToTake, fill->scale.y); fill->position = glm::vec2(xPos - damageToTake, fill->position.y); } bool Healthbar::animate() { this->takeDamage(this->lastHp - pokemon->currentHp); this->lastHp = pokemon->currentHp; } void Healthbar::init(LoaderPtr loader, HealthbarPosition position, const std::string &fillImage, const std::string &borderImage) { if (position == HealthbarPosition::BOTTOM_RIGHT) { this->fill = GuiTexturePtr(new GuiTexture(loader->loadTexture(fillImage), glm::vec2(0.65f, -0.75f), glm::vec2(0.25f, 0.025f))); this->border = GuiTexturePtr(new GuiTexture(loader->loadTexture(borderImage), glm::vec2(0.59f, -0.75f), glm::vec2(0.36f, 0.6))); } else if (position == HealthbarPosition::TOP_LEFT) { this->fill = GuiTexturePtr(new GuiTexture(loader->loadTexture(fillImage), glm::vec2(-0.53f, 0.75f), glm::vec2(0.25f, 0.025f))); this->border = GuiTexturePtr(new GuiTexture(loader->loadTexture(borderImage), glm::vec2(-0.59f, 0.75f), glm::vec2(0.36f, 0.6))); } }<file_sep>/src/loaders/FileLoader.h // // Created by Martin on 14. 11. 2015. // #ifndef PPGSO_FILELOADER_H #define PPGSO_FILELOADER_H #include <stdio.h> #include <stdlib.h> class FileLoader { public: typedef struct { unsigned char imageTypeCode; short int imageWidth; short int imageHeight; unsigned char bitCount; unsigned char *imageData; } TGAFILE_t; static bool LoadTGAFile(const char *, TGAFILE_t *); }; #endif //PPGSO_FILELOADER_H<file_sep>/src/shaders/GroundShader.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_GROUNDSHADER_H #define POKEMON3D_GROUNDSHADER_H #include "src/shaders/ShaderProgram.hpp" #include "src/objects/Light.hpp" class GroundShader : public ShaderProgram { private: const int number_of_lights = 4; GLint modelMatrix; GLint texture; GLint projection; GLint view; GLint *lightPosition; GLint *lightColor; GLint *attenuation; GLint skyColor; GLint reflectivity; GLint shineDamper; public: GLint backgroundTexture; GLint rTexture; GLint gTexture; GLint bTexture; GLint blendMap; GroundShader(); void bindAttributes() override; void getAllUniformLocations() override; void loadModelMatrix(glm::mat4 matrix); void loadTextureUni(GLint texture_id); void loadProjectionMatrix(glm::mat4 projection); void loadViewMatrix(glm::mat4 view); void loadLights(std::vector<LightPtr> lights); void loadSkyColor(glm::vec3 skyColor); void connectTextureUnits(); void loadShining(float reflectivity, float shineDamper); }; typedef std::shared_ptr<GroundShader> GroundShaderPtr; #endif //POKEMON3D_GROUNDSHADER_H<file_sep>/src/wrappers/GrassWrapper.cpp // // Created by Martin on 8. 12. 2015. // #include "src/wrappers/GrassWrapper.hpp" GrassWrapper::GrassWrapper(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) { this->loader = loader; this->mainGrass = GrassPtr(new Grass(loader, object_name, file_name, position, rotX, rotY, rotZ, scale)); initGrassAnimation(); } GrassWrapper::GrassWrapper(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) { this->loader = loader; this->mainGrass = GrassPtr(new Grass(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper)); initGrassAnimation(); } void GrassWrapper::generateGrass(glm::vec2 bottomLeft, glm::vec2 topRight) { for (int z = bottomLeft.y; z <= topRight.y; z++) { for (int x = bottomLeft.x; x < topRight.x; x++) { float rotation = Math::random(0.0f, 359.9f); float size = Math::random(0.5f, 1.5f); GrassPtr grass = GrassPtr(new Grass(loader, "models/objects/Grass.obj", "models/textures/Grass.tga", glm::vec3(GLfloat(x), 0.0f, GLfloat(z)), 0.0f, rotation, 0.0f, size, this->mainGrass->texturedModel->texture->reflectivity, this->mainGrass->texturedModel->texture->shineDamper)); grass->texturedModel->texture->hasTransparency = true; grass->texturedModel->texture->useFakeLighting = true; grass->animation = this->grassAnimation; grass->useAnimation = false; this->grassParts.push_back(grass); } } } void GrassWrapper::initGrassAnimation() { grassAnimation = AnimationPtr(new Animation()); grassAnimation->add(KeyframePtr(new Keyframe(0, glm::vec3(0.0f)))); grassAnimation->add(KeyframePtr(new Keyframe(1, glm::vec3(90.0f, 0.0f, 0.0f)))); grassAnimation->add(KeyframePtr(new Keyframe(2, glm::vec3(0.0f)))); grassAnimation->repeat = false; }<file_sep>/src/extensions/Transformations.cpp // // Created by Martin on 18. 11. 2015. // #include "src/extensions/Transformations.hpp" glm::mat4 Transformations::createTransformationMatrix(glm::vec3 position, float rotX, float rotY, float rotZ, float scale) { glm::mat4 matrix; matrix = glm::translate(matrix, position); matrix = glm::rotate(matrix, glm::radians(rotX), glm::vec3(1.0f, 0.0f, 0.0f)); matrix = glm::rotate(matrix, glm::radians(rotY), glm::vec3(0.0f, 1.0f, 0.0f)); matrix = glm::rotate(matrix, glm::radians(rotZ), glm::vec3(0.0f, 0.0f, 1.0f)); matrix = glm::scale(matrix, glm::vec3(scale)); return matrix; } glm::mat4 Transformations::createTransformationMatrix(glm::vec2 position, glm::vec2 scale) { glm::mat4 matrix; matrix = glm::translate(matrix, glm::vec3(position, 0.0f)); matrix = glm::scale(matrix, glm::vec3(scale.x, scale.y, 0.0f)); return matrix; } float Transformations::getScaleFactor(glm::mat4 matrix) { return glm::sqrt(matrix[0].x * matrix[0].x + matrix[1].x * matrix[1].x + matrix[2].x * matrix[2].x); } glm::vec3 Transformations::getPosition(glm::mat4 matrix) { return glm::vec3(matrix[3].x, matrix[3].y, matrix[3].z); } <file_sep>/src/skybox/Skybox.cpp // // Created by Martin on 29. 11. 2015. // #include "src/skybox/Skybox.hpp" Skybox::Skybox(LoaderPtr loader) { this->cube = loader->load(this->vertices, this->vertices, 3); this->textureId = loader->loadCubeMap(this->file_paths); } void Skybox::animate(float delta) { this->rotation += rotationSpeed * delta; } <file_sep>/src/objects/MovableCharacter.cpp // // Created by Martin on 19. 11. 2015. // #include "src/objects/MovableCharacter.hpp" #include "Scene.hpp" #include "Grass.hpp" MovableCharacter::MovableCharacter(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Mesh(loader, object_name, file_name, position, rotX, rotY, rotZ, scale) { } MovableCharacter::MovableCharacter(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : Mesh(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper) { } MovableCharacter::MovableCharacter(TexturedModelPtr texturedModel, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Mesh(texturedModel, position, rotX, rotY, rotZ, scale) { } MovableCharacter::MovableCharacter(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Mesh(mesh, position, rotX, rotY, rotZ, scale) { } void MovableCharacter::increasePosition(float dX, float dY, float dZ) { this->position.x += dX; this->position.y += dY; this->position.z += dZ; } void MovableCharacter::increaseRotation(float rX, float rY, float rZ) { this->rotX += rX; this->rotY += rY; this->rotZ += rZ; } void MovableCharacter::move(Scene &scene, float delta) { glm::vec3 prevRot = glm::vec3(rotX, rotY, rotZ); glm::vec3 prevPos = this->position; // rotate around Y axis increaseRotation(0.0f, currentTurnSpeed * delta, 0.0f); // calculate distance depending from rotation float distance = currentSpeed * delta; float dx = distance * glm::sin(glm::radians(rotY)); float dz = distance * glm::cos(glm::radians(rotY)); // move increasePosition(dx, 0.0f, dz); if (collided(scene)) { this->position = prevPos; this->rotX = prevRot.x; this->rotY = prevRot.y; this->rotZ = prevRot.z; return; } } bool MovableCharacter::collided(Scene &scene) { for (auto objectLoop : scene.objects) { if (objectLoop.get() == this) continue; auto grass = std::dynamic_pointer_cast<Grass>(objectLoop); if (grass) { if (collidedWith(grass)) { if (!grass->isAnimating) { grass->initAnimation(); grass->useAnimation = true; return false; } } continue; } if (collidedWith(objectLoop)) return true; } for (auto wrapperLoop : scene.wrappers) { for (auto matrixLoop : wrapperLoop->matrixes) { if (collidedWith(matrixLoop, wrapperLoop->mesh->radius)) { return true; } } } return false; } bool MovableCharacter::collidedWith(MeshPtr mesh) { if (glm::distance(this->position, mesh->position) < this->radius + mesh->radius) { return true; } return false; } bool MovableCharacter::collidedWith(glm::mat4 matrix, float radius) { if (glm::distance(this->position, Transformations::getPosition(matrix)) < this->radius + (radius * Transformations::getScaleFactor(matrix))) { return true; } return false; }<file_sep>/cmake/shaders.cmake function(generate_shaders out_headers) set(result) foreach (src ${ARGN}) get_filename_component(name ${src} NAME_WE) set(src_file "${CMAKE_CURRENT_SOURCE_DIR}/${src}") set(out_file "${CMAKE_CURRENT_BINARY_DIR}/${name}.h") add_custom_command(OUTPUT ${out_file} COMMAND ${CMAKE_COMMAND} -DSRC_FILE=${src_file} -DSYMBOL=${name} -DOUT_FILE=${out_file} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/bin2c.cmake DEPENDS ${src} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Creating header for shader ${src}" VERBATIM ) list(APPEND result ${out_file}) endforeach () set(${out_headers} "${result}" PARENT_SCOPE) endfunction()<file_sep>/src/managers/SceneManager.cpp // // Created by Martin on 29. 11. 2015. // #include "src/managers/SceneManager.hpp" SceneManager::SceneManager(GLFWwindow *window, InputManager *inputManager) { this->inputManager = inputManager; init(window, inputManager); initStartingScene(); } void SceneManager::render() { this->currentScene->render(); } void SceneManager::animate(float delta) { this->currentScene->update(); SceneType sceneType = this->currentScene->animate(delta); if (sceneType != this->currentScene->sceneType) changeScene(sceneType); } void SceneManager::clean() { this->currentScene->clean(); } void SceneManager::changeScene(SceneType sceneType) { Scene *newScene; if (sceneType == SceneType::MAIN_SCEEN) { if (mainScene == nullptr) { newScene = new MainScene(this->masterRenderer, this->camera, this->loader, this->pokemonRepository, this->grounds, this->skybox, this->trees, this->mainCharacter, this->terrains, this->inputManager); } else { newScene = mainScene; } } else if (sceneType == SceneType::BATTLE_SCEEN) { PokemonPtr playerPokemon = this->pokemonRepository->findPokemon(25); PlayerPokemonPtr playerPokemonPtr = PlayerPokemonPtr(new PlayerPokemon(playerPokemon->id, loader, playerPokemon, playerPokemon->position, playerPokemon->rotX, playerPokemon->rotY, playerPokemon->rotZ, playerPokemon->scale, playerPokemon->texturedModel->texture->reflectivity, playerPokemon->texturedModel->texture->shineDamper, this->inputManager, "models/objects/Pikachu.obj", "models/textures/Pikachu.tga")); PokemonPtr enemyPokemon = this->pokemonRepository->findPokemon(7); EnemyPokemonPtr enemyPokemonPtr = EnemyPokemonPtr(new EnemyPokemon(enemyPokemon->id, loader, enemyPokemon, enemyPokemon->position, enemyPokemon->rotX, enemyPokemon->rotY, enemyPokemon->rotZ, enemyPokemon->scale, enemyPokemon->texturedModel->texture->reflectivity, enemyPokemon->texturedModel->texture->shineDamper, this->inputManager, "models/objects/Squirtle.obj", "models/textures/Squirtle.tga")); newScene = new BattleScene(this->masterRenderer, this->camera, this->loader, this->inputManager, playerPokemonPtr, enemyPokemonPtr, this->grounds, this->skybox); } this->previousScene = this->currentScene; this->currentScene = newScene; } void SceneManager::init(GLFWwindow *window, InputManager *inputManager) { initShaders(); initLoaders(); initRenderers(); glfwGetWindowSize(window, &screen_width, &screen_height); this->pokemonRepository = PokemonRepositoryPtr(new PokemonRepository()); this->initMainCharacter(inputManager); this->initPokemons(inputManager); this->initGrounds(this->staticShader->programId); this->initWrappers(); this->initCamera(window, inputManager); this->initTerrain(this->loader); this->initSkybox(this->loader); } void SceneManager::initStartingScene() { changeScene(SceneType::MAIN_SCEEN); } void SceneManager::initShaders() { this->staticShader = StaticShaderPtr(new StaticShader()); this->groundShader = GroundShaderPtr(new GroundShader()); this->guiShader = GuiShaderPtr(new GuiShader()); this->skyboxShader = SkyboxShaderPtr(new SkyboxShader()); } void SceneManager::initLoaders() { this->loader = LoaderPtr(new Loader(staticShader->programId)); this->guiLoader = LoaderPtr(new Loader(guiShader->programId)); } void SceneManager::initRenderers() { this->meshRenderer = MeshRendererPtr(new MeshRenderer(staticShader)); this->groundRenderer = GroundRendererPtr(new GroundRenderer(groundShader)); this->guiRenderer = GuiRendererPtr(new GuiRenderer(guiShader, guiLoader)); this->skyboxRenderer = SkyboxRendererPtr(new SkyboxRenderer(skyboxShader)); this->masterRenderer = MasterRendererPtr(new MasterRenderer(meshRenderer, groundRenderer, guiRenderer, skyboxRenderer)); } void SceneManager::initPokemons(InputManager *inputManager) { auto squirtle = PokemonPtr(new Pokemon( 7, this->loader, "models/objects/Squirtle.obj", "models/textures/Squirtle.tga", glm::vec3(-20.0f, 0.0f, -24.0f), 0.0f, 0.0f, 0.0f, 0.15f, this->inputManager, "models/objects/Squirtle.obj", "models/textures/Squirtle.tga", false )); this->pokemonRepository->add(squirtle); this->pokemons.push_back(squirtle); auto pikachu = PokemonPtr(new Pokemon( 25, this->loader, "models/objects/Pikachu.obj", "models/textures/Pikachu.tga", glm::vec3(5.0f, 0.0f, -100.0f), 0.0f, 0.0f, 0.0f, 0.15f, this->inputManager, "models/objects/Pikachu.obj", "models/textures/Pikachu.tga", true )); this->pokemonRepository->add(pikachu); this->pokemons.push_back(pikachu); } void SceneManager::initGrounds(GLuint programId) { auto backgroundTexture = TerrainTexturePtr(new TerrainTexture(loader->loadTexture("models/textures/Ground_grass3.tga"))); auto rTexture = TerrainTexturePtr(new TerrainTexture(loader->loadTexture("models/textures/Ground.tga"))); auto gTexture = TerrainTexturePtr(new TerrainTexture(loader->loadTexture("models/textures/GrassFlowers.tga"))); auto bTexture = TerrainTexturePtr(new TerrainTexture(loader->loadTexture("models/textures/Path.tga"))); auto blendMap = TerrainTexturePtr(new TerrainTexture(loader->loadTexture("models/textures/BlendMap.tga"))); this->terrainTextures.push_back(backgroundTexture); this->terrainTextures.push_back(rTexture); this->terrainTextures.push_back(gTexture); this->terrainTextures.push_back(bTexture); this->terrainTextures.push_back(blendMap); auto texturePack = TerrainTexturePackPtr(new TerrainTexturePack(backgroundTexture, rTexture, gTexture, bTexture)); this->terrainTexturePack = texturePack; auto ground1 = GroundPtr(new Ground(programId, 0, 0, "models/textures/Ground_grass3.tga", texturePack, blendMap)); auto ground2 = GroundPtr(new Ground(programId, 1, 0, "models/textures/Ground_grass3.tga", texturePack, blendMap)); auto ground3 = GroundPtr(new Ground(programId, 0, 1, "models/textures/Ground_grass3.tga", texturePack, blendMap)); auto ground4 = GroundPtr(new Ground(programId, 1, 1, "models/textures/Ground_grass3.tga", texturePack, blendMap)); this->grounds.push_back(ground1); this->grounds.push_back(ground2); this->grounds.push_back(ground3); this->grounds.push_back(ground4); } void SceneManager::initWrappers() { auto treesWrapper = MeshWrapperPtr(new MeshWrapper(loader, "models/objects/Tree2.obj", "models/textures/Tree2.tga", 300, glm::vec3(50.0f, 75.0f, 1.0f))); auto treesWrapper2 = MeshWrapperPtr(new MeshWrapper(loader, "models/objects/Tree.obj", "models/textures/Tree.tga", 300, glm::vec3(4.0f, 2.0f, 100.f))); this->grassWrapper = GrassWrapperPtr(new GrassWrapper(loader, "models/objects/Grass.obj", "models/textures/Grass.tga", glm::vec3(0.0f), 0.0f, 0.0f, 0.0f, 1.0f)); this->trees.push_back(treesWrapper); this->trees.push_back(treesWrapper2); } void SceneManager::initMainCharacter(InputManager *inputManager) { this->mainCharacter = MainCharacterPtr(new MainCharacter( loader, "models/objects/Trainer.obj", "models/textures/Trainer.tga", glm::vec3(0.0f), 0.0f, 180.0f, 0.0f, 0.1f, 0.2f, 50.0f, inputManager )); } void SceneManager::initCamera(GLFWwindow *window, InputManager *inputManager) { this->camera = CameraPtr(new ThirdPersonCamera(mainCharacter, window, inputManager)); } void SceneManager::initSkybox(LoaderPtr loader) { this->skybox = SkyboxPtr(new Skybox(loader)); } void SceneManager::initTerrain(LoaderPtr loader) { this->terrains.push_back(TerrainPtr(new Terrain( loader, "models/objects/Pokecenter.obj", "models/textures/Pokecenter.tga", glm::vec3(30.0f, 0.0f, -50.0f), 0.0f, 180.0f, 0.0f, 20.0f, 1.0f, 50.0f ))); grassWrapper->generateGrass(glm::vec2(5.0f, 5.0f), glm::vec2(25.0f, 35.0f)); for (auto grassLoop : grassWrapper->grassParts) { this->terrains.push_back(grassLoop); } // grassWrapper->grassParts.clear(); // // grassWrapper->generateGrass(glm::vec2(55.0f, 10.0f), glm::vec2(105.0f, 100.0f)); // // for (auto grassLoop : grassWrapper->grassParts) { // this->terrains.push_back(grassLoop); // } } <file_sep>/src/engine/GroundRenderer.cpp // // Created by Martin on 17. 11. 2015. // #include "src/engine/GroundRenderer.hpp" GroundRenderer::GroundRenderer(GroundShaderPtr shader) { this->shader = shader; this->shader->connectTextureUnits(); }; void GroundRenderer::render(std::vector<GroundPtr> grounds, glm::mat4 projection, glm::mat4 view) { for ( std::vector<GroundPtr>::iterator it = grounds.begin(); it != grounds.end(); it++ ) { prepareGround(*it, projection, view); bindTextures(*it); prepareInstance(*it); glBindVertexArray((*it)->mesh->texturedModel->rawModel->vao); glDrawElements(GL_TRIANGLES, (*it)->mesh->texturedModel->rawModel->mesh_indices_count, GL_UNSIGNED_INT, 0); unbindMesh(); } } void GroundRenderer::render(MeshPtr mesh, glm::mat4 projection, glm::mat4 view) { shader->loadProjectionMatrix(projection); shader->loadViewMatrix(view); shader->loadTextureUni(mesh->texturedModel->texture->textureId); shader->loadModelMatrix(mesh->texturedModel->matrix); glBindVertexArray(mesh->texturedModel->rawModel->vao); glDrawElements(GL_TRIANGLES, mesh->texturedModel->rawModel->mesh_indices_count, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void GroundRenderer::prepareGround(GroundPtr model, glm::mat4 projection, glm::mat4 view) { shader->loadProjectionMatrix(projection); shader->loadViewMatrix(view); //shader->loadTextureUni(model->mesh->texturedModel->texture->textureId); } void GroundRenderer::unbindMesh() { glBindVertexArray(0); } void GroundRenderer::prepareInstance(GroundPtr ground ) { loadModelMatrix(ground); } void GroundRenderer::loadModelMatrix(GroundPtr ground) { ground->mesh->position = glm::vec3(ground->x, 0.0f, ground->z); ground->mesh->rotX = 0; ground->mesh->rotY = 0; ground->mesh->rotZ = 0; ground->mesh->scale = 1.0f; shader->loadModelMatrix(ground->mesh->createTransformationMatrix()); } void GroundRenderer::bindTextures(GroundPtr ground) { auto texturePack = ground->texturePack; glUniform1i(shader->backgroundTexture, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, texturePack->backgroundTexture->textureId); glUniform1i(shader->rTexture, 1); glActiveTexture(GL_TEXTURE1 + 0); glBindTexture(GL_TEXTURE_2D, texturePack->rTexture->textureId); glUniform1i(shader->gTexture, 2); glActiveTexture(GL_TEXTURE2 + 0); glBindTexture(GL_TEXTURE_2D, texturePack->gTexture->textureId); glUniform1i(shader->bTexture, 3); glActiveTexture(GL_TEXTURE3 + 0); glBindTexture(GL_TEXTURE_2D, texturePack->bTexture->textureId); glUniform1i(shader->blendMap, 4); glActiveTexture(GL_TEXTURE4 + 0); glBindTexture(GL_TEXTURE_2D, ground->blendMap->textureId); shader->loadShining(ground->reflectivity, ground->shineDamper); }<file_sep>/src/skybox/Skybox.hpp // // Created by Martin on 29. 11. 2015. // #ifndef POKEMON3D_SKYBOX_HPP #define POKEMON3D_SKYBOX_HPP #include <vector> #include <string> #include "src/loaders/Loader.hpp" #include "src/models/RawModel.hpp" class Skybox { private: const float size = 500.0f; std::vector<float> vertices = { -size, size, -size, -size, -size, -size, size, -size, -size, size, -size, -size, size, size, -size, -size, size, -size, -size, -size, size, -size, -size, -size, -size, size, -size, -size, size, -size, -size, size, size, -size, -size, size, size, -size, -size, size, -size, size, size, size, size, size, size, size, size, size, -size, size, -size, -size, -size, -size, size, -size, size, size, size, size, size, size, size, size, size, -size, size, -size, -size, size, -size, size, -size, size, size, -size, size, size, size, size, size, size, -size, size, size, -size, size, -size, -size, -size, -size, -size, -size, size, size, -size, -size, size, -size, -size, -size, -size, size, size, -size, size }; std::vector<std::string> file_paths = { "models/textures/left.tga", "models/textures/right.tga", "models/textures/top.tga", "models/textures/bottom.tga", "models/textures/back.tga", "models/textures/front.tga" }; const float rotationSpeed = 0.3f; public: GLint textureId; RawModelPtr cube; // RawModel *cube; float rotation = 0.0f; Skybox(LoaderPtr loader); void animate(float delta); }; typedef std::shared_ptr<Skybox> SkyboxPtr; #endif //POKEMON3D_SKYBOX_HPP <file_sep>/src/objects/Attack.cpp // // Created by Martin on 30. 11. 2015. // #include "src/objects/Attack.hpp" #include "Scene.hpp" Attack::Attack(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : MovableCharacter(loader, object_name, file_name, position, rotX, rotY, rotZ, scale) { this->startingZpos = position.z; } Attack::Attack(TexturedModelPtr texturedModel, glm::vec3 position, float rotX, float rotY, float rotZ, float scale , float movementSpeed, float rotationSpeed) : MovableCharacter(texturedModel, position, rotX, rotY, rotZ, scale) { this->movementSpeed = movementSpeed; this->rotateSpeed = rotationSpeed; this->startingZpos = position.z; } Attack::Attack(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale , float movementSpeed, float rotationSpeed) : MovableCharacter(mesh, position, rotX, rotY, rotZ, scale) { this->movementSpeed = movementSpeed; this->rotateSpeed = rotationSpeed; this->startingZpos = position.z; } SceneType Attack::animate(Scene &scene, float delta) { return move(scene, delta); } SceneType Attack::move(Scene &scene, float delta) { collisionDelay += delta; if (position.z < -20.0f || position.z > 20.0f) this->needsDeletion = true; position.z += startingZpos > 0.0f ? -movementSpeed * delta : movementSpeed * delta; rotZ += rotateSpeed *delta; return scene.sceneType; }<file_sep>/src/objects/MainCharacter.h // // Created by Martin on 15. 11. 2015. // #ifndef POKEMON3D_MAINCHARACTER_H #define POKEMON3D_MAINCHARACTER_H #include "MovableCharacter.hpp" #include "src/enums/Enums.hpp" class MainCharacter: public MovableCharacter { private: protected: InputManager *inputManager; float runSpeed = 20.0f; float turnSpeed = 160.0f; void checkInputs(); public: MainCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager); MainCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager); MainCharacter(LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<MainCharacter> MainCharacterPtr; #endif //POKEMON3D_MAINCHARACTER_H <file_sep>/src/extensions/Transformations.hpp // // Created by Martin on 18. 11. 2015. // #ifndef POKEMON3D_TRANSFORMATIONS_HPP #define POKEMON3D_TRANSFORMATIONS_HPP #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> class Transformations { public: static glm::mat4 createTransformationMatrix(glm::vec3 position, float rotX, float rotY, float rotZ, float scale); static glm::mat4 createTransformationMatrix(glm::vec2 position, glm::vec2 scale); static float getScaleFactor(glm::mat4 matrix); static glm::vec3 getPosition(glm::mat4 matrix); }; #endif //POKEMON3D_TRANSFORMATIONS_HPP <file_sep>/src/loaders/Loader.hpp // // Created by Martin on 22. 11. 2015. // #ifndef POKEMON3D_LOADER_HPP #define POKEMON3D_LOADER_HPP #include <memory> #include <vector> #include <stdio.h> #include <GL/glew.h> #include "src/models/RawModel.hpp" #include "src/loaders/FileLoader.h" class Loader { private: GLuint programId; void setVertexPositions(RawModelPtr rawModel, std::vector<GLfloat> vertex_buffer); void setVertexPositions(RawModelPtr rawModel, std::vector<GLfloat> vertex_buffer, int size); void setTextureCoords(RawModelPtr rawModel, std::vector<GLfloat> texcoord_buffer, int size); void setIndices(RawModelPtr rawModel, std::vector<GLuint> index_data); void setNormals(RawModelPtr rawModel, std::vector<GLfloat> normals_data); RawModelPtr initLoading(); void clean(); public: Loader(GLuint programId); RawModelPtr load(std::vector<GLfloat> vertex_buffer, std::vector<GLfloat> texcoord_buffer, std::vector<GLuint> index_data, std::vector<GLfloat> normals_data); RawModelPtr load(std::vector<GLfloat> vertex_buffer, std::vector<GLfloat> texcoord_buffer, int size); GLuint loadTexture(const std::string &image_file); GLuint loadCubeMap(std::vector<std::string> files); }; typedef std::shared_ptr<Loader> LoaderPtr; #endif //POKEMON3D_LOADER_HPP <file_sep>/src/repository/PokemonRepository.cpp // // Created by Martin on 30. 11. 2015. // #include "src/repository/PokemonRepository.hpp" PokemonRepository::PokemonRepository() { } PokemonPtr PokemonRepository::findPokemon(unsigned short id) { for (auto pokemonLoop : this->pokemons) { if (pokemonLoop->id == id) return pokemonLoop; } return nullptr; } void PokemonRepository::add(PokemonPtr pokemon) { this->pokemons.push_back(pokemon); } <file_sep>/src/gui/GuiShader.hpp // // Created by Martin on 23. 11. 2015. // #ifndef POKEMON3D_GUISHADER_HPP #define POKEMON3D_GUISHADER_HPP #include <glm/glm.hpp> #include "src/shaders/ShaderProgram.hpp" class GuiShader : public ShaderProgram { private: GLint matrix; GLint texture; public: GuiShader(); void loadModelMatrix(glm::mat4 matix); void getAllUniformLocations() override; void bindAttributes() override; void loadTextureUni(GLint texture_id); }; typedef std::shared_ptr<GuiShader> GuiShaderPtr; #endif //POKEMON3D_GUISHADER_HPP <file_sep>/src/textures/Texture.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_TEXTURE_H #define POKEMON3D_TEXTURE_H #include <memory> class Texture { private: public: int textureId; float reflectivity = 0.5f; float shineDamper = 50.0f; bool hasTransparency = false; bool useFakeLighting = false; Texture(int textureId); }; typedef std::shared_ptr<Texture> TexturePtr; #endif //POKEMON3D_TEXTURE_H <file_sep>/src/gui/Healthbar.hpp // // Created by Martin on 25. 11. 2015. // #ifndef POKEMON3D_HEALTHBAR_HPP #define POKEMON3D_HEALTHBAR_HPP #include "src/gui/Gui.hpp" #include "src/objects/Pokemon.hpp" enum HealthbarPosition { BOTTOM_RIGHT, TOP_LEFT }; class Healthbar : public Gui { private: std::vector<GLfloat> vertex_buffer = {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f}; std::vector<GLfloat> texcoord_buffer = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; float oneHealthProtion; float lastHp; GuiTexturePtr fill; GuiTexturePtr border; PokemonPtr pokemon; void init(LoaderPtr loader, HealthbarPosition position, const std::string &fillImage, const std::string &borderImage); public: Healthbar(const std::string &fillImage, const std::string &borderImage, LoaderPtr loader, HealthbarPosition position); Healthbar(PokemonPtr pokemon, const std::string &fillImage, const std::string &borderImage, LoaderPtr loader, HealthbarPosition position); void takeDamage(int damage); bool animate() override; }; typedef std::shared_ptr<Healthbar> HealthbarPtr; #endif //POKEMON3D_HEALTHBAR_HPP <file_sep>/src/engine/MasterRenderer.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_MASTERRENDERER_H #define POKEMON3D_MASTERRENDERER_H #include <map> #include <list> #include "src/shaders/StaticShader.hpp" #include "MeshRenderer.hpp" #include "src/objects/Mesh.h" #include "src/engine/GroundRenderer.hpp" #include "src/objects/Light.hpp" #include "src/wrappers/MeshWrapper.hpp" #include "src/gui/GuiRenderer.hpp" #include "src/skybox/SkyboxRenderer.hpp" class MasterRenderer { private: glm::vec3 skyColor = glm::vec3(0.5444f, 0.62f, 0.69f); glm::vec3 fogColor = glm::vec3(0.5444f, 0.62f, 0.69f); StaticShaderPtr staticShader; GroundShaderPtr groundShader; GuiShaderPtr guiShader; SkyboxShaderPtr skyboxShader; MeshRendererPtr renderer; GroundRendererPtr groundRenderer; GuiRendererPtr guiRenderer; SkyboxRendererPtr skyboxRenderer; std::vector<MeshPtr> meshes; std::vector<GroundPtr> grounds; std::vector<MeshWrapperPtr> wrappers; std::vector<GuiPtr> guis; SkyboxPtr skybox; void prepare(); public: MasterRenderer(MeshRendererPtr renderer, GroundRendererPtr groundRenderer, GuiRendererPtr guiRenderer, SkyboxRendererPtr skyboxRenderer); void clean(); void render(glm::mat4 projection, glm::mat4 camera, std::vector<LightPtr> lights); void processMesh(MeshPtr mesh); void processGround(GroundPtr ground); void processWrapper(MeshWrapperPtr wrapper); void processGui(GuiPtr gui); void processSkybox(SkyboxPtr skybox); static void enableCulling(); static void disableCulling(); }; typedef std::shared_ptr<MasterRenderer> MasterRendererPtr; #endif //POKEMON3D_MASTERRENDERER_H <file_sep>/src/camera/Camera.hpp // // Created by Martin on 29. 11. 2015. // #ifndef POKEMON3D_CAMERA_HPP #define POKEMON3D_CAMERA_HPP #include <glm/glm.hpp> #include "src/objects/MovableCharacter.hpp" class Camera { public: Camera(); virtual glm::mat4 getViewMatrix() = 0; virtual void move() = 0; // virtual void setFollowTarget(MovableCharacterPtr movableCharacter) = 0; virtual void setFollowTarget(glm::vec3 *targetPositionVec, float *targetRotX, float *targetRotY, float *targetRotZ) = 0; virtual void setFollowTarget(MovableCharacterPtr followTarget) = 0; virtual void setPosition(glm::vec3 position) = 0; }; typedef std::shared_ptr<Camera> CameraPtr; #endif //POKEMON3D_CAMERA_HPP <file_sep>/src/engine/MeshRenderer.cpp // // Created by Martin on 16. 11. 2015. // #include "src/engine/MeshRenderer.hpp" #include "MasterRenderer.hpp" MeshRenderer::MeshRenderer(StaticShaderPtr shader) { this->shader = shader; }; void MeshRenderer::render(std::vector<MeshPtr> meshes, glm::mat4 projection, glm::mat4 view) { for ( std::vector<MeshPtr>::iterator it = meshes.begin(); it != meshes.end(); it++ ) { render(*it, projection, view); } } void MeshRenderer::render(MeshPtr mesh, glm::mat4 projection, glm::mat4 view) { if (mesh->texturedModel->texture->hasTransparency) MasterRenderer::disableCulling(); shader->loadUseFakeLighting(mesh->texturedModel->texture->useFakeLighting); loadTexturedModel(mesh->texturedModel, projection, view); loadVAO(mesh->texturedModel); loadMatrixAndDraw(mesh->createTransformationMatrix(), mesh->texturedModel->rawModel->mesh_indices_count); unbindMesh(); } void MeshRenderer::render(std::vector<MeshWrapperPtr> wrappers, glm::mat4 projection, glm::mat4 view) { for (std::vector<MeshWrapperPtr>::iterator it = wrappers.begin(); it != wrappers.end(); it++) { this->render(*it, projection, view); } } void MeshRenderer::render(MeshWrapperPtr wrapper, glm::mat4 projection, glm::mat4 view) { if (wrapper->mesh->texturedModel->texture->hasTransparency) MasterRenderer::disableCulling(); shader->loadUseFakeLighting(wrapper->mesh->texturedModel->texture->useFakeLighting); loadTexturedModel(wrapper->mesh->texturedModel, projection, view); loadVAO(wrapper->mesh->texturedModel); for (std::vector<glm::mat4>::iterator it = wrapper->matrixes.begin(); it != wrapper->matrixes.end(); it++) { loadMatrixAndDraw(*it, wrapper->mesh->texturedModel->rawModel->mesh_indices_count); } unbindMesh(); } void MeshRenderer::loadTexturedModel(TexturedModelPtr model, glm::mat4 projection, glm::mat4 view) { shader->loadProjectionMatrix(projection); shader->loadViewMatrix(view); shader->loadTextureUni(model->texture->textureId); shader->loadShining(model->texture->reflectivity, model->texture->shineDamper); } void MeshRenderer::unbindMesh() { // MasterRenderer::enableCulling(); glBindVertexArray(0); } void MeshRenderer::loadMatrixAndDraw(glm::mat4 matrix, int count) { shader->loadModelMatrix(matrix); glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, 0); } void MeshRenderer::loadVAO(TexturedModelPtr model) { glBindVertexArray(model->rawModel->vao); } <file_sep>/src/gui/GuiRenderer.hpp // // Created by Martin on 23. 11. 2015. // #ifndef POKEMON3D_GUIRENDERER_HPP #define POKEMON3D_GUIRENDERER_HPP #include <vector> #include "src/models/RawModel.hpp" #include "src/gui/GuiTexture.hpp" #include "src/gui/GuiShader.hpp" #include "src/extensions/Transformations.hpp" #include "src/gui/Gui.hpp" #include "src/loaders/Loader.hpp" class GuiRenderer { private: RawModelPtr rawModel; // RawModel *rawModel; void loadVAO(RawModelPtr model); void loadMatrix(glm::mat4 matrix); void loadTexture(GuiTexturePtr guiTexture); void unbind(); void render(GuiPtr gui); public: GuiShaderPtr guiShader; // GuiShader *guiShader; GuiRenderer(GuiShaderPtr shader, LoaderPtr loader); void render(std::vector<GuiTexturePtr> guis); void render(std::vector<GuiPtr> guis); void clean(); }; typedef std::shared_ptr<GuiRenderer> GuiRendererPtr; #endif //POKEMON3D_GUIRENDERER_HPP <file_sep>/src/objects/Ground.cpp // // Created by Martin on 17. 11. 2015. // #include "src/objects/Ground.hpp" Ground::Ground(GLint program_id, int gridX, int gridZ, const std::string &image_file, TerrainTexturePackPtr texturePack, TerrainTexturePtr blendMap) { this->mesh = MeshPtr(new Mesh(image_file)); this->programId = program_id; this->x = gridX * size; this->z = gridZ * size; this->texturePack = texturePack; this->blendMap = blendMap; this->generateGround(); } void Ground::generateGround() { int count = vertex_count * vertex_count; std::vector<GLfloat> vertices(count * 3); std::vector<GLfloat> normals(count * 3); std::vector<GLfloat> textureCoords(count * 2); std::vector<GLuint> indices(6 * ((int)vertex_count - 1) * ((int)vertex_count - 1)); int vertexPointer = 0; for (int i = 0; i < vertex_count; i++) { for (int j = 0; j < vertex_count; j++) { vertices[vertexPointer * 3] = -(float)j/((float)vertex_count - 1) * size; vertices[vertexPointer * 3 + 1] = 0; vertices[vertexPointer * 3 + 2] = -(float)i/((float)vertex_count - 1) * size; normals[vertexPointer * 3] = 0; normals[vertexPointer * 3 + 1] = 1; normals[vertexPointer * 3 + 2] = 0; textureCoords[vertexPointer * 2] = (float)j/((float)vertex_count - 1); textureCoords[vertexPointer * 2 + 1] = (float)i/((float)vertex_count - 1); vertexPointer++; } } int pointer = 0; for (int gz = 0; gz < vertex_count - 1; gz++) { for (int gx = 0; gx < vertex_count - 1; gx++) { int topLeft = (gz * vertex_count) + gx; int topRight = (topLeft + 1); int bottomLeft = ((gz + 1) * vertex_count) + gx; int bottomRight = (bottomLeft + 1); indices[pointer++] = topLeft; indices[pointer++] = bottomLeft; indices[pointer++] = topRight; indices[pointer++] = topRight; indices[pointer++] = bottomLeft; indices[pointer++] = bottomRight; } } // Activate the program glUseProgram(this->programId); // Generate a vertex array object glGenVertexArrays(1, &this->mesh->texturedModel->rawModel->vao); glBindVertexArray(this->mesh->texturedModel->rawModel->vao); // Generate and upload a buffer with vertex positions to GPU glGenBuffers(1, &this->mesh->texturedModel->rawModel->vbo); glBindBuffer(GL_ARRAY_BUFFER, this->mesh->texturedModel->rawModel->vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLfloat), vertices.data(), GL_STATIC_DRAW); // Bind the buffer to "Position" attribute in program GLint position_attrib = glGetAttribLocation(this->programId, "Position"); glEnableVertexAttribArray(position_attrib); glVertexAttribPointer(position_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); // Generate and upload a buffer with texture coordinates to GPU glGenBuffers(1, &this->mesh->texturedModel->rawModel->tbo); glBindBuffer(GL_ARRAY_BUFFER, this->mesh->texturedModel->rawModel->tbo); glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(GLfloat), textureCoords.data(), GL_STATIC_DRAW); GLint texcoord_attrib = glGetAttribLocation(this->programId, "TexCoord"); glEnableVertexAttribArray(texcoord_attrib); glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); // --- Indices (define which triangles consists of which vertices) --- std::vector<GLuint> index_data; this->mesh->texturedModel->rawModel->mesh_indices_count = 6 * ((int)vertex_count - 1) * ((int)vertex_count - 1); // Generate and upload a buffer with indices to GPU glGenBuffers(1, &this->mesh->texturedModel->rawModel->ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->mesh->texturedModel->rawModel->ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), indices.data(), GL_STATIC_DRAW); glGenBuffers(1, &this->mesh->texturedModel->rawModel->nbo); glBindBuffer(GL_ARRAY_BUFFER, this->mesh->texturedModel->rawModel->nbo); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(GLfloat), normals.data(), GL_STATIC_DRAW ); GLint normal_attrib = glGetAttribLocation(this->programId, "Normal"); glEnableVertexAttribArray(normal_attrib); glVertexAttribPointer(normal_attrib, 3, GL_FLOAT, GL_FALSE, 0, 0); } <file_sep>/src/shaders/ShaderProgram.hpp // // Created by Martin on 16. 11. 2015. // #ifndef POKEMON3D_SHADERPROGRAM_H #define POKEMON3D_SHADERPROGRAM_H #include <memory> #include <vector> #include <iostream> #include <fstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> class ShaderProgram { private: GLint vertexShaderId; GLint fragmentShaderId; GLint loadShader(const std::string &shader_file, GLint type); GLint createProgram(GLint vertex_shader_id, GLint fragment_shader_id); protected: virtual void bindAttributes(); void bindAttribute(int attribute, const std::string &varname); GLint getUniformLocation(const std::string uniformName); virtual void getAllUniformLocations() = 0; void loadFloat(GLint location, float value); void loadVector(GLint location, glm::vec3 vector); void loadBoolean(GLint location, bool value); void loadMatrix(GLint location, glm::mat4 matrix); void loadTexture(GLint location, GLint texture_id); void loadInt(GLint location, int value); public: GLint programId; ShaderProgram(const std::string &vertex_shader_file, const std::string &fragment_shader_file); void start(); void stop(); void clean(); }; typedef std::shared_ptr<ShaderProgram> ShaderProgramPtr; #endif //POKEMON3D_SHADERPROGRAM_H <file_sep>/src/objects/MovableCharacter.hpp // // Created by Martin on 19. 11. 2015. // #ifndef POKEMON3D_MOVABLECHARACTER_HPP #define POKEMON3D_MOVABLECHARACTER_HPP #include "src/objects/Mesh.h" class MovableCharacter : public Mesh { private: bool collided(Scene &scene); bool collidedWith(glm::mat4 matrix, float radius); protected: float currentSpeed; float currentTurnSpeed; void move(Scene &scene, float delta); void increasePosition(float dX, float dY, float dZ); void increaseRotation(float rX, float rY, float rZ); bool collidedWith(MeshPtr mesh); public: MovableCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); MovableCharacter(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); MovableCharacter(TexturedModelPtr, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); MovableCharacter(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); }; typedef std::shared_ptr<MovableCharacter> MovableCharacterPtr; #endif //POKEMON3D_MOVABLECHARACTER_HPP <file_sep>/src/gui/GuiTexture.cpp // // Created by Martin on 23. 11. 2015. // #include "src/gui/GuiTexture.hpp" GuiTexture::GuiTexture(int textureId, glm::vec2 position, glm::vec2 scale) { this->textureId = textureId; this->position = position; this->scale = scale; }<file_sep>/src/skybox/SkyboxRenderer.hpp // // Created by Martin on 28. 11. 2015. // #ifndef POKEMON3D_SKYBOXRENDERER_HPP #define POKEMON3D_SKYBOXRENDERER_HPP #include <vector> #include <string> #include "src/models/RawModel.hpp" #include "src/skybox/SkyboxShader.hpp" #include "src/loaders/Loader.hpp" #include "src/skybox/Skybox.hpp" class SkyboxRenderer { private: public: SkyboxShaderPtr shader; // SkyboxShader *shader; SkyboxRenderer(SkyboxShaderPtr shader); void render(SkyboxPtr skybox, glm::mat4 viewMatrix, glm::mat4 projectionMatrix, glm::vec3 fogColor); }; typedef std::shared_ptr<SkyboxRenderer> SkyboxRendererPtr; #endif //POKEMON3D_SKYBOXRENDERER_HPP <file_sep>/src/wrappers/MeshWrapper.cpp // // Created by Martin on 18. 11. 2015. // #include "src/wrappers/MeshWrapper.hpp" MeshWrapper::MeshWrapper(LoaderPtr loader, const std::string &obj_file, const std::string &image_file, int count, glm::vec3 scale) { this->mesh = MeshPtr(new Mesh(loader, obj_file, image_file)); createMatrixes(count, scale); } MeshWrapper::MeshWrapper(LoaderPtr loader, const std::string &obj_file, const std::string &image_file, int count, glm::vec3 scale, float reflectivity, float shineDamper) { this->mesh = MeshPtr(new Mesh(loader, obj_file, image_file)); this->mesh->texturedModel->texture->reflectivity = reflectivity; this->mesh->texturedModel->texture->shineDamper = shineDamper; createMatrixes(count, scale); } void MeshWrapper::createMatrixes(int count, glm::vec3 scale) { for (int i = 0; i < count; i++) { float scaling = (float)(rand() % (int)scale.x + scale.y) / (float)scale.z; glm::mat4 matrix = Transformations::createTransformationMatrix( glm::vec3((float)(rand() % 1000 - 500), 0.0f, (float)(rand() % 1000 - 500)), 0.0f, (float)(rand() % 360), 0.0f, scaling ); this->matrixes.push_back(matrix); } } <file_sep>/src/engine/MasterRenderer.cpp // // Created by Martin on 17. 11. 2015. // #include "src/engine/MasterRenderer.hpp" MasterRenderer::MasterRenderer(MeshRendererPtr renderer, GroundRendererPtr groundRenderer, GuiRendererPtr guiRenderer, SkyboxRendererPtr skyboxRenderer) : staticShader(renderer->shader), renderer(renderer), groundShader(groundRenderer->shader), groundRenderer(groundRenderer), guiRenderer(guiRenderer), guiShader(guiRenderer->guiShader), skyboxRenderer(skyboxRenderer), skyboxShader(skyboxRenderer->shader){ // Enable Z-buffer glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Enable polygon culling // enableCulling(); glFrontFace(GL_CCW); } void MasterRenderer::render(glm::mat4 projection, glm::mat4 camera, std::vector<LightPtr> lights) { prepare(); this->staticShader->start(); this->staticShader->loadSkyColor(skyColor); this->staticShader->loadLights(lights); this->renderer->render(this->meshes, projection, camera); this->renderer->render(this->wrappers, projection, camera); this->staticShader->stop(); this->groundShader->start(); this->groundShader->loadSkyColor(skyColor); this->groundShader->loadLights(lights); this->groundRenderer->render(this->grounds, projection, camera); this->groundShader->stop(); this->skyboxRenderer->render(this->skybox, camera, projection, fogColor); this->guiShader->start(); this->guiRenderer->render(this->guis); this->guiShader->stop(); this->meshes.clear(); this->grounds.clear(); this->wrappers.clear(); this->guis.clear(); } void MasterRenderer::prepare() { // Set gray background glClearColor(skyColor.x, skyColor.y, skyColor.z, 0); // Clear depth and color buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void MasterRenderer::clean() { this->staticShader->clean(); this->groundShader->clean(); this->guiShader->clean(); this->skyboxShader->clean(); } void MasterRenderer::processMesh(MeshPtr mesh) { this->meshes.push_back(mesh); } void MasterRenderer::processGround(GroundPtr ground) { this->grounds.push_back(ground); } void MasterRenderer::processWrapper(MeshWrapperPtr wrapper) { this->wrappers.push_back(wrapper); } void MasterRenderer::processGui(GuiPtr gui) { this->guis.push_back(gui); } void MasterRenderer::processSkybox(SkyboxPtr skybox) { this->skybox = skybox; } void MasterRenderer::enableCulling() { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } void MasterRenderer::disableCulling() { glDisable(GL_CULL_FACE); }<file_sep>/src/objects/Terrain.cpp // // Created by Martin on 14. 11. 2015. // #include "src/objects/Terrain.h" #include "Scene.hpp" Terrain::Terrain(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Mesh(loader, object_name, file_name, position, rotX, rotY, rotZ, scale) { createTransformationMatrix(); } Terrain::Terrain(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : Mesh(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper) { createTransformationMatrix(); } Terrain::Terrain(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Mesh (mesh, position, rotX, rotY, rotZ, scale) { createTransformationMatrix(); } Terrain::Terrain(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : Mesh (mesh, position, rotX, rotY, rotZ, scale) { this->texturedModel->texture->reflectivity = reflectivity; this->texturedModel->texture->shineDamper = shineDamper; createTransformationMatrix(); } SceneType Terrain::animate(Scene &scene, float delta) { return scene.sceneType; }<file_sep>/src/objects/Mesh.h #ifndef _MESH_H_ #define _MESH_H_ #include <iostream> #include <vector> #include <fstream> #include <memory> #include <GL/glew.h> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <GLFW/glfw3.h> #include "src/loaders/tiny_obj_loader.h" #include "src/loaders/FileLoader.h" #include "src/models/TexturedModel.hpp" #include "src/extensions/Transformations.hpp" #include "src/managers/InputManager.hpp" #include "glm/ext.hpp" #include "src/loaders/Loader.hpp" #include "src/extensions/Math.hpp" #include "src/enums/Enums.hpp" class Scene; typedef struct { float x; float y; float z; } center_t; class Mesh { // using namespace nsTexturedModel; private: float calculateRadius(); center_t calculateCenter(); protected: LoaderPtr loader; virtual void initGeometry(const std::string &); virtual void initTexture(const std::string &); public: glm::vec3 center; float rotY; float rotX; float rotZ; float scale; float radius; glm::vec3 position; TexturedModelPtr texturedModel; bool needsDeletion = false; Mesh(const std::string &); Mesh(TexturedModelPtr, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Mesh(std::shared_ptr<Mesh> mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Mesh(LoaderPtr loader, const std::string &, const std::string &); Mesh(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale); Mesh(LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper); virtual void render(); virtual SceneType animate(Scene &scene, float delta); glm::vec3 getCenter(); glm::mat4 createTransformationMatrix(); void setPosition(glm::vec3 position); void setRotation(glm::vec3 rotation); void setScale(float scale); tinyobj::center_point_t center_point; }; typedef std::shared_ptr<Mesh> MeshPtr; #endif<file_sep>/src/managers/InputManager.hpp // // Created by Martin on 19. 11. 2015. // #ifndef POKEMON3D_INPUTMANAGER_HPP #define POKEMON3D_INPUTMANAGER_HPP #include <GLFW/glfw3.h> #include <glm/glm.hpp> class InputManager { private: int *keys; glm::vec3 currentCursorPosition; glm::vec3 lastCursorPosition; int windowWidth; int windowHeight; double previousWheelOffset; double currentWheerlOffset; glm::vec3 toScreenCoord(double x , double y); public: InputManager(int windowWidth, int widowHeight); bool isWPressed(); bool isSPressed(); bool isAPressed(); bool isDPressed(); bool isTPressed(); bool isRightMouseButtonPressed(); bool isLeftMouseButtonPressed(); void mouseButtonCallback( GLFWwindow * window, int button, int action, int mods ); void cursorCallback( GLFWwindow *, double x, double y ); void wheelCallBack( GLFWwindow *, double, double yoffset ); void onKeyPress( GLFWwindow *, int key, int scancode, int action, int mods); float getDistanceY(); float getDistanceX(); double getDistanceZoom(); }; #endif //POKEMON3D_INPUTMANAGER_HPP <file_sep>/src/enums/Enums.hpp // // Created by Martin on 8. 12. 2015. // #ifndef POKEMON3D_ENUMS_HPP #define POKEMON3D_ENUMS_HPP enum SceneType { MAIN_SCEEN, BATTLE_SCEEN }; #endif //POKEMON3D_ENUMS_HPP <file_sep>/src/skybox/SkyboxShader.hpp // // Created by Martin on 28. 11. 2015. // #ifndef POKEMON3D_SKYBOXSHADER_HPP #define POKEMON3D_SKYBOXSHADER_HPP #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "src/shaders/ShaderProgram.hpp" class SkyboxShader : public ShaderProgram { private: GLint projectionMatrix; GLint viewMatrix; GLint fogColor; glm::vec3 rotationVec = glm::vec3(0.0f, 1.0f, 0.0f); public: SkyboxShader(); void loadProjectionMatrix(glm::mat4 matrix); void loadViewMatrix(glm::mat4 matrix, float rotation); void getAllUniformLocations() override; void loadFogColor(glm::vec3 color); glm::mat4 rotate(glm::mat4 matrix, float rotation); }; typedef std::shared_ptr<SkyboxShader> SkyboxShaderPtr; #endif //POKEMON3D_SKYBOXSHADER_HPP <file_sep>/src/objects/EnemyPokemon.cpp // // Created by Martin on 7. 12. 2015. // #include "src/objects/EnemyPokemon.hpp" #include "Scene.hpp" EnemyPokemon::EnemyPokemon(unsigned short id, LoaderPtr loader, const std::string & obj, const std::string & img, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name) : Pokemon(id, loader, obj, img, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper, inputManager, attack_obj_file, attack_image_name, false) { } EnemyPokemon::EnemyPokemon(unsigned short id, LoaderPtr loader, const std::string &obj, const std::string &img, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name) : Pokemon(id, loader, obj, img, position, rotX, rotY, rotZ, scale, inputManager, attack_obj_file, attack_image_name, false) { } EnemyPokemon::EnemyPokemon(unsigned short id, LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name) : Pokemon(id, loader, mesh, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper, inputManager, attack_obj_file, attack_image_name, false) { } SceneType EnemyPokemon::animate(Scene &scene, float delta) { if (scene.sceneType == SceneType::BATTLE_SCEEN) { attackDelay += delta; if (wasAttacked && attackDelay > 3.0f || (!wasAttacked && attackDelay > 13.0f)) { // move back to starting position if (startingPos.z > this->position.z) { if (this->position.z + delta > startingPos.z) this->position = startingPos; else this->position.z += delta; return scene.sceneType; } canAttack = true; } for (auto objectLoop : scene.objects) { if (objectLoop.get() == this) continue; auto att = std::dynamic_pointer_cast<Attack>(objectLoop); if (!att) { continue; } else { if (att->collisionDelay > 0.5f ) { if (collidedWith(objectLoop)) { objectLoop->needsDeletion = true; attackDelay = 0.0f; wasAttacked = true; this->currentHp -= 1; this->position.z -= att->knockbackForce; } } } } if (canAttack) { canAttack = false; wasAttacked = false; attackDelay = 0.0f; attack(scene); } } createTransformationMatrix(); if (this->currentHp <= 0) return SceneType::MAIN_SCEEN; return scene.sceneType; } <file_sep>/src/animations/Animation.hpp // // Created by Martin on 7. 12. 2015. // #ifndef POKEMON3D_ANIMATION_HPP #define POKEMON3D_ANIMATION_HPP #include <vector> #include "src/animations/Keyframe.hpp" class Animation { public: Animation(); ~Animation(); void init(); void add(KeyframePtr keyframe); glm::vec3 lerp(glm::vec3 a, glm::vec3 b, float t); bool animate(float dt); glm::vec3 position, rotation; float animationTime; int i; bool repeat = true; std::vector<KeyframePtr> keyframes; }; typedef std::shared_ptr<Animation> AnimationPtr; #endif //POKEMON3D_ANIMATION_HPP <file_sep>/src/extensions/Math.cpp // // Created by Martin on 6. 12. 2015. // #include "src/extensions/Math.hpp" float Math::random(float min, float max) { return ((max - min) * ((float) rand() / (float) RAND_MAX)) + min; }<file_sep>/src/scenes/MainScene.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_MAINSCENE_HPP #define POKEMON3D_MAINSCENE_HPP #include "src/objects/Scene.hpp" #include "src/repository/PokemonRepository.hpp" #include "src/engine/MasterRenderer.hpp" #include "src/camera/Camera.hpp" #include "src/objects/StreetLamp.hpp" class MainScene : public Scene { private: std::vector<PokemonData> pokemonData = { PokemonData { 7, glm::vec3(0.0f), glm::vec3(-20.0f, 0.0f, -24.0f), 0.15f, 100, nullptr }, PokemonData { 25, glm::vec3(0.0f), glm::vec3(15.0f, 0.0f, 0.0f), 0.15f, 100, nullptr } }; public: MainScene(MasterRendererPtr masterRenderer, CameraPtr camera, LoaderPtr loader, PokemonRepositoryPtr pokemonRepository, std::vector<GroundPtr> grounds, SkyboxPtr skybox, std::vector<MeshWrapperPtr> trees, MainCharacterPtr mainCharacter, std::vector<TerrainPtr> terrains, InputManager *inputManager); }; #endif //POKEMON3D_MAINSCENE_HPP <file_sep>/src/gl_pokemon.cpp // Example of: // - More than one object (loaded from OBJ file) // - Keyboard events (press A to start/stop animation) // - Mouse events // - Orthographic camera projection #include <iostream> #include <vector> #include <fstream> #include <cmath> #define GLM_SWIZZLE #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <src/loaders/FileLoader.h> #include "src/objects/Mesh.h" #include "src/camera/Arcball.h" #include "src/objects/Terrain.h" #include "src/objects/MainCharacter.h" #include "src/camera/ThirdPersonCamera.h" #include "src/shaders/StaticShader.hpp" #include "src/engine/MasterRenderer.hpp" #include "src/wrappers/MeshWrapper.hpp" #include "src/managers/InputManager.hpp" #include "src/objects/OtherCharacter.hpp" #include "src/objects/Scene.hpp" #include "src/gui/GuiRenderer.hpp" #include "src/gui/Healthbar.hpp" #include "src/objects/StreetLamp.hpp" #include "src/skybox/SkyboxRenderer.hpp" #include "src/managers/SceneManager.hpp" int SCREEN_WIDTH = 1600; int SCREEN_HEIGHT = 900; int keys[1024]; GLfloat fov = 45.0f; ThirdPersonCamera *personCam = NULL;//nsThirdPersonCamera::ThirdPersonCamera(NULL, NULL); std::list<Mesh> meshes; InputManager *inputManager = NULL; std::vector<MovableCharacter *> movableCharacters; SceneManager *sceneManager; int movableCharacterIndex = 0; bool poll = true; float lastFrameTime; float delta; Healthbar *healthbar; void InitializeGeometry(GLuint program_id) { // Generate a vertex array object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Setup geometry std::vector<GLfloat> vertex_buffer { // x, y 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f }; // Generate a vertex buffer object GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertex_buffer.size() * sizeof(GLfloat), vertex_buffer.data(), GL_STATIC_DRAW); // Setup vertex array lookup auto position_attrib = glGetAttribLocation(program_id, "Position"); glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(position_attrib); // Generate another vertex buffer object for texture coordinates std::vector<GLfloat> texcoord_buffer { // u, v 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; GLuint tbo; glGenBuffers(1, &tbo); glBindBuffer(GL_ARRAY_BUFFER, tbo); glBufferData(GL_ARRAY_BUFFER, texcoord_buffer.size() * sizeof(GLfloat), texcoord_buffer.data(), GL_STATIC_DRAW); auto texcoord_attrib = glGetAttribLocation(program_id, "TexCoord"); glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(texcoord_attrib); } GLuint ShaderProgram(const std::string &vertex_shader_file, const std::string &fragment_shader_file) { // Create shaders auto vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); auto fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); auto result = GL_FALSE; auto info_length = 0; // Load shader code std::ifstream vertex_shader_stream(vertex_shader_file); std::string vertex_shader_code((std::istreambuf_iterator<char>(vertex_shader_stream)), std::istreambuf_iterator<char>()); std::ifstream fragment_shader_stream(fragment_shader_file); std::string fragment_shader_code((std::istreambuf_iterator<char>(fragment_shader_stream)), std::istreambuf_iterator<char>()); // Compile vertex shader std::cout << "Compiling Vertex Shader ..." << std::endl; auto vertex_shader_code_ptr = vertex_shader_code.c_str(); glShaderSource(vertex_shader_id, 1, &vertex_shader_code_ptr, NULL); glCompileShader(vertex_shader_id); // Check vertex shader log glGetShaderiv(vertex_shader_id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { glGetShaderiv(vertex_shader_id, GL_INFO_LOG_LENGTH, &info_length); std::string vertex_shader_log((unsigned int)info_length, ' '); glGetShaderInfoLog(vertex_shader_id, info_length, NULL, &vertex_shader_log[0]); std::cout << vertex_shader_log << std::endl; } // Compile fragment shader std::cout << "Compiling Fragment Shader ..." << std::endl; auto fragment_shader_code_ptr = fragment_shader_code.c_str(); glShaderSource(fragment_shader_id, 1, &fragment_shader_code_ptr, NULL); glCompileShader(fragment_shader_id); // Check fragment shader log glGetShaderiv(fragment_shader_id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { glGetShaderiv(fragment_shader_id, GL_INFO_LOG_LENGTH, &info_length); std::string fragment_shader_log((unsigned long)info_length, ' '); glGetShaderInfoLog(fragment_shader_id, info_length, NULL, &fragment_shader_log[0]); std::cout << fragment_shader_log << std::endl; } // Create and link the program std::cout << "Linking Shader Program ..." << std::endl; auto program_id = glCreateProgram(); glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glBindFragDataLocation(program_id, 0, "FragmentColor"); glLinkProgram(program_id); // Check program log glGetProgramiv(program_id, GL_LINK_STATUS, &result); if (result == GL_FALSE) { glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_length); std::string program_log((unsigned long)info_length, ' '); glGetProgramInfoLog(program_id, info_length, NULL, &program_log[0]); std::cout << program_log << std::endl; } glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return program_id; } void UpdateProjection(GLuint program_id, bool is_perspective, glm::mat4 camera) { glUseProgram(program_id); // Create projection matrix glm::mat4 Projection; if (is_perspective) { // Perspective projection matrix (field of view, aspect ratio, near plane distance, far plane distance) Projection = glm::perspective(fov, GLfloat(SCREEN_WIDTH) / GLfloat(SCREEN_HEIGHT), 0.1f, 10000.0f); } else { // Orthographic projection matrix (left, right, bottom, top, near plane distance, far plane distance) Projection = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1000.0f, 1000.0f); } // Send projection matrix value to program auto projection_uniform = glGetUniformLocation(program_id, "ProjectionMatrix"); glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, glm::value_ptr(Projection)); // Send view matrix value to program auto view_uniform = glGetUniformLocation(program_id, "ViewMatrix"); glUniformMatrix4fv(view_uniform, 1, GL_FALSE, glm::value_ptr(camera)); } void InitializeGLState() { // Enable Z-buffer glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // Enable polygon culling //glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); } glm::vec3 toScreenCoord( double x, double y ) { glm::vec3 coord(0.0f); coord.x = (float) (2.0f * x - (float)SCREEN_HEIGHT) / (float)SCREEN_WIDTH; coord.y = (float) -(2.0f * y - (float)SCREEN_HEIGHT) / (float)SCREEN_WIDTH; /* Clamp it to border of the windows, comment these codes to allow rotation when cursor is not over window */ coord.x = glm::clamp( coord.x, -1.0f, 1.0f ); coord.y = glm::clamp( coord.y, -1.0f, 1.0f ); float length_squared = coord.x * coord.x + coord.y * coord.y; if( length_squared <= 1.0 ) coord.z = sqrt( 1.0f - length_squared ); else coord = glm::normalize( coord ); return coord; } int health = 100; float oneHealthPortion = -1; void OnKeyPress(GLFWwindow* window, int key, int scancode, int action, int mods) { inputManager->onKeyPress(window, key, scancode, action, mods); if (key == GLFW_KEY_B && action == GLFW_PRESS) { sceneManager->changeScene(SceneType::BATTLE_SCEEN); poll = false; } if (key == GLFW_KEY_R && action == GLFW_PRESS && sceneManager->currentScene->sceneType == SceneType::BATTLE_SCEEN) { sceneManager->changeScene(SceneType::MAIN_SCEEN); } } // Mouse move event handler void OnMouseMove(GLFWwindow* window, double xpos, double ypos) { inputManager->cursorCallback(window, xpos, ypos); } void OnMouseScroll(GLFWwindow* window, double xoffset, double yoffset) { inputManager->wheelCallBack(window, xoffset, yoffset); } void OnMouseButtonClick(GLFWwindow* window, int button, int action, int mods) { inputManager->mouseButtonCallback(window, button, action, mods); } float getCurrentTime() { return (float) (glfwGetTime() * 1000.0f); } void createLoadingScreen(const std::string &file_name, GLFWwindow *window) { auto program_id = ShaderProgram("src/shaders/vert_texture.glsl", "src/shaders/frag_texture.glsl"); glUseProgram(program_id); InitializeGeometry(program_id); FileLoader::TGAFILE_t tgafile; FileLoader::LoadTGAFile(file_name.c_str(), &tgafile); std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8)); GLuint texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); // Set mipmaps glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1500, 843, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer.data()); auto texture_attrib = glGetUniformLocation(program_id, "Texture"); glUniform1i(texture_attrib, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, texture_id); glClearColor(.5f,.5f,.5f,0); // Clear depth and color buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw triangles using the program glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glfwSwapBuffers(window); //glfwPollEvents(); } GLint loadTexture(const std::string &file) { // Create new texture object GLuint texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); // Set mipmaps glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); FileLoader::TGAFILE_t tgafile; FileLoader::LoadTGAFile(file.c_str(), &tgafile); std::vector<char> buffer(tgafile.imageData, tgafile.imageData + tgafile.imageWidth * tgafile.imageHeight * (tgafile.bitCount / 8)); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tgafile.imageWidth, tgafile.imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer.data()); return texture_id; } int main() { srand(time(NULL)); // Initialize GLFW if (!glfwInit()) { std::cerr << "Failed to initialize GLFW!" << std::endl; return EXIT_FAILURE; } // Setup OpenGL context glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Try to create a window GLFWwindow *window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Pokemon 3D", glfwGetPrimaryMonitor(), NULL); if (window == NULL) { std::cerr << "Failed to open GLFW window, your graphics card is probably only capable of OpenGL 2.1" << std::endl; glfwTerminate(); return EXIT_FAILURE; } // get size of maximazed window glfwGetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT); // Finalize window setup glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = GL_TRUE; glewInit(); if (!glewIsSupported("GL_VERSION_3_3")) { std::cerr << "Failed to initialize GLEW with OpenGL 3.3!" << std::endl; glfwTerminate(); return EXIT_FAILURE; } inputManager = new InputManager(SCREEN_WIDTH, SCREEN_HEIGHT); createLoadingScreen("models/textures/LoadingScreen.tga", window); sceneManager = new SceneManager(window, inputManager); // Add keyboard and mouse handlers glfwSetKeyCallback(window, OnKeyPress); glfwSetCursorPosCallback(window, OnMouseMove); glfwSetScrollCallback(window, OnMouseScroll); glfwSetMouseButtonCallback(window, OnMouseButtonClick); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Hide mouse cursor while (!glfwWindowShouldClose(window)) { glfwPollEvents(); sceneManager->animate(delta); sceneManager->render(); // Display result glfwSwapBuffers(window); float currentFrameTime = getCurrentTime(); delta = (currentFrameTime - lastFrameTime) / 1000.0f; lastFrameTime = currentFrameTime; } // Clean up sceneManager->clean(); glfwTerminate(); return EXIT_SUCCESS; } <file_sep>/src/engine/MeshRenderer.hpp // // Created by Martin on 16. 11. 2015. // #ifndef POKEMON3D_RENDERER_H #define POKEMON3D_RENDERER_H #include <list> #include "src/objects/Mesh.h" #include "src/shaders/StaticShader.hpp" #include "src/wrappers/MeshWrapper.hpp" class MeshRenderer { private: void loadTexturedModel(TexturedModelPtr model, glm::mat4 projection, glm::mat4 view); void loadMatrixAndDraw(glm::mat4, int count); void unbindMesh(); void render(MeshWrapperPtr wrapper, glm::mat4 projection, glm::mat4 view); void loadVAO(TexturedModelPtr model); public: StaticShaderPtr shader; // StaticShader *shader; MeshRenderer(StaticShaderPtr shader); void render(std::vector<MeshPtr> meshes, glm::mat4 projection, glm::mat4 view); void render(MeshPtr mesh, glm::mat4 projection, glm::mat4 view); void render(std::vector<MeshWrapperPtr> wrappers, glm::mat4 projection, glm::mat4 matrix); }; typedef std::shared_ptr<MeshRenderer> MeshRendererPtr; #endif //POKEMON3D_RENDERER_H <file_sep>/README.md # Pokemon-3D Pokemon 3D created in OpenGL as a project which was part of the course Principles of Computer Graphics and Image Processing 2015 at FIIT STU BA in 2015 / 2016. <file_sep>/src/managers/SceneManager.hpp // // Created by Martin on 29. 11. 2015. // #ifndef POKEMON3D_SCENEMANAGER_HPP #define POKEMON3D_SCENEMANAGER_HPP #include "src/objects/Scene.hpp" #include "src/scenes/MainScene.hpp" #include "src/scenes/BattleScene.hpp" #include "src/objects/Terrain.h" #include "src/objects/OtherCharacter.hpp" #include "src/objects/StreetLamp.hpp" #include "src/gui/Healthbar.hpp" #include "src/objects/MainCharacter.h" #include "src/objects/Ground.hpp" #include "src/objects/Light.hpp" #include "src/textures/TerrainTexturePack.hpp" #include "src/repository/PokemonRepository.hpp" #include "src/wrappers/GrassWrapper.hpp" class SceneManager { private: std::vector<TerrainPtr > terrains; std::vector<GroundPtr> grounds; std::vector<GuiPtr> guis; StaticShaderPtr staticShader; GroundShaderPtr groundShader; CameraPtr camera; std::vector<TerrainTexturePtr > terrainTextures; TerrainTexturePackPtr terrainTexturePack; std::vector<MeshWrapperPtr> trees; glm::mat4 projection; std::vector<StreetLampPtr> lamps; MeshRendererPtr meshRenderer; GroundRendererPtr groundRenderer; LoaderPtr guiLoader; LoaderPtr loader; GuiShaderPtr guiShader; GuiRendererPtr guiRenderer; SkyboxShaderPtr skyboxShader; SkyboxRendererPtr skyboxRenderer; SkyboxPtr skybox; MasterRendererPtr masterRenderer; MainCharacterPtr mainCharacter; InputManager *inputManager; GrassWrapperPtr grassWrapper; Scene *mainScene = nullptr; Scene *previousScene; PokemonRepositoryPtr pokemonRepository; std::vector<PokemonPtr> pokemons; int screen_width; int screen_height; void initStartingScene(); void initPokemons(InputManager *inputManager); void initGrounds(GLuint programId); void initWrappers(); void initMainCharacter(InputManager *inputManager); void initCamera(GLFWwindow *window, InputManager *inputManager); void initSkybox(LoaderPtr loader); void initTerrain(LoaderPtr loader); void initShaders(); void initLoaders(); void initRenderers(); void init(GLFWwindow *window, InputManager *inputManager); public: SceneManager(GLFWwindow *window, InputManager *inputManager); void render(); void animate(float delta); void clean(); void changeScene(SceneType sceneType); Scene *currentScene; }; #endif //POKEMON3D_SCENEMANAGER_HPP <file_sep>/src/scenes/BattleScene.cpp // // Created by Martin on 30. 11. 2015. // #include <gui/Healthbar.hpp> #include "src/scenes/BattleScene.hpp" BattleScene::BattleScene(MasterRendererPtr masterRenderer, CameraPtr camera, LoaderPtr loader, InputManager *inputManager, PlayerPokemonPtr playersPokemon, EnemyPokemonPtr enemyPokemon, std::vector<GroundPtr> grounds, SkyboxPtr skybox) { this->sceneType = SceneType::BATTLE_SCEEN; this->projection = glm::perspective(45.0f, GLfloat(1600) / GLfloat(900), 0.1f, 750.0f); this->inputManager = inputManager; this->playersPokemon = playersPokemon; this->enemyPokemon = enemyPokemon; preparePokemon(playersPokemon, &this->playersPokemonData); preparePokemon(enemyPokemon, &this->enemyPokemonData); initLights(); camera->setFollowTarget(&cameraPosition, &cameraRotX, &cameraRotY, &cameraRotZ); this->loadCamera(camera); this->loadMasterRenderer(masterRenderer); this->loadProjection(this->projection); this->loadObject(playersPokemon); this->loadObject(enemyPokemon); this->loadSkybox(skybox); this->loadGrounds(grounds); this->loadGui(HealthbarPtr(new Healthbar(playersPokemon,"models/textures/HealthbarFill.tga", "models/textures/Healthbar.tga" , loader, HealthbarPosition::BOTTOM_RIGHT))); this->loadGui(HealthbarPtr(new Healthbar(enemyPokemon,"models/textures/HealthbarFill.tga", "models/textures/Healthbar.tga" , loader, HealthbarPosition::TOP_LEFT))); } void BattleScene::preparePokemon(PokemonPtr pokemon, PokemonData *pokemonData) { pokemon->setPosition(pokemonData->position); pokemon->startingPos = pokemonData->position; pokemon->setRotation(pokemonData->rotation); pokemon->setScale(pokemonData->scale); pokemon->maxHp = pokemonData->maxHp; pokemon->currentHp = pokemonData->maxHp; } void BattleScene::initLights() { auto light1 = LightPtr(new Light(glm::vec3(-20.0f, 50.0f, 50.0f), glm::vec3(0.7f))); auto light2 = LightPtr(new Light(glm::vec3(30.0f, 50.0f, -40.0f), glm::vec3(0.7f))); this->loadLight(light1); this->loadLight(light2); } void BattleScene::update() { // if (this->inputManager->isTPressed()) { // this->playersPokemon->attack(*this); // } }<file_sep>/src/models/RawModel.hpp // // Created by Martin on 22. 11. 2015. // #ifndef POKEMON3D_RAWMODEL_HPP #define POKEMON3D_RAWMODEL_HPP #include <memory> #include <GL/glew.h> class RawModel { public: GLuint vbo, tbo; GLuint ibo; GLuint vao; GLuint nbo; int mesh_indices_count; int mesh_vertex_count; RawModel(); }; typedef std::shared_ptr<RawModel> RawModelPtr; #endif //POKEMON3D_RAWMODEL_HPP <file_sep>/src/extensions/Math.hpp // // Created by Martin on 6. 12. 2015. // #ifndef POKEMON3D_MATH_HPP #define POKEMON3D_MATH_HPP #include <stdlib.h> class Math { public: static float random(float min, float max); }; #endif //POKEMON3D_MATH_HPP <file_sep>/src/shaders/StaticShader.cpp // // Created by Martin on 16. 11. 2015. // #include "StaticShader.hpp" StaticShader::StaticShader() : ShaderProgram("src/shaders/vert_pokemon.glsl", "src/shaders/frag_pokemon.glsl") { getAllUniformLocations(); } void StaticShader::bindAttributes() { this->bindAttribute(0, "FragmentColor"); this->bindAttribute(2, "Normal"); } void StaticShader::getAllUniformLocations() { this->modelMatrix = getUniformLocation("ModelMatrix"); this->texture = getUniformLocation("Texture"); this->projection = getUniformLocation("ProjectionMatrix"); this->view = getUniformLocation("ViewMatrix"); this->reflectivity = getUniformLocation("reflectivity"); this->shineDamper = getUniformLocation("shineDamper"); this->skyColor = getUniformLocation("skyColor"); this->useFakeLighting = getUniformLocation("useFakeLighting"); this->lightPosition = new int[number_of_lights]; this->lightColor = new int[number_of_lights]; this->attenuation = new int[number_of_lights]; for (int i = 0; i < number_of_lights; i++) { this->lightPosition[i] = getUniformLocation("lightPosition[" + std::to_string(i) + "]"); this->lightColor[i] = getUniformLocation("lightColor[" + std::to_string(i) + "]"); this->attenuation[i] = getUniformLocation("attenuation[" + std::to_string(i) + "]"); } } void StaticShader::loadModelMatrix(glm::mat4 matrix) { loadMatrix(this->modelMatrix, matrix); } void StaticShader::loadTextureUni(GLint texture_id) { loadTexture(this->texture, texture_id); } void StaticShader::loadProjectionMatrix(glm::mat4 projection) { loadMatrix(this->projection, projection); } void StaticShader::loadViewMatrix(glm::mat4 view) { loadMatrix(this->view, view); } void StaticShader::loadLights(std::vector<LightPtr> lights) { for (int i = 0; i < number_of_lights; i++) { if (i < lights.size()) { loadVector(this->lightPosition[i], lights[i]->position); loadVector(this->lightColor[i], lights[i]->color); loadVector(this->attenuation[i], lights[i]->attenuation); } else { loadVector(this->lightPosition[i], glm::vec3(0.0f)); loadVector(this->lightColor[i], glm::vec3(0.0f)); loadVector(this->attenuation[i], glm::vec3(1.0f, 0.0f, 0.0f)); } } } void StaticShader::loadShining(float reflectivity, float shineDamper) { loadFloat(this->reflectivity, reflectivity); loadFloat(this->shineDamper, shineDamper); } void StaticShader::loadSkyColor(glm::vec3 skyColor) { loadVector(this->skyColor, skyColor); } void StaticShader::loadUseFakeLighting(bool useFakeLigting) { loadBoolean(this->useFakeLighting, useFakeLigting); }<file_sep>/src/gui/GuiRenderer.cpp // // Created by Martin on 23. 11. 2015. // #include "src/gui/GuiRenderer.hpp" GuiRenderer::GuiRenderer(GuiShaderPtr shader, LoaderPtr loader) { std::vector<GLfloat> vertex_buffer = {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f}; std::vector<GLfloat> texcoord_buffer = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; auto guiRawModel = loader->load(vertex_buffer, texcoord_buffer, 2); this->rawModel = guiRawModel; this->guiShader = shader; } void GuiRenderer::render(std::vector<GuiTexturePtr> guis) { this->guiShader->start(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); loadVAO(this->rawModel); for (std::vector<GuiTexturePtr>::iterator guiLoop = guis.begin(); guiLoop != guis.end(); guiLoop++) { loadTexture(*guiLoop); loadMatrix(Transformations::createTransformationMatrix((*guiLoop)->position, (*guiLoop)->scale)); glDrawArrays(GL_TRIANGLE_STRIP, 0, this->rawModel->mesh_vertex_count); } glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); unbind(); this->guiShader->stop(); } void GuiRenderer::render(std::vector<GuiPtr> guis) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); loadVAO(this->rawModel); for (auto guiLoop : guis) { render(guiLoop); } glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); unbind(); } void GuiRenderer::render(GuiPtr gui) { for (auto guiTextureLoop : gui->guiTextures) { loadTexture(guiTextureLoop); loadMatrix(Transformations::createTransformationMatrix((guiTextureLoop)->position, (guiTextureLoop)->scale)); glDrawArrays(GL_TRIANGLE_STRIP, 0, this->rawModel->mesh_vertex_count); } } void GuiRenderer::loadVAO(RawModelPtr model) { glBindVertexArray(model->vao); } void GuiRenderer::loadMatrix(glm::mat4 matrix) { guiShader->loadModelMatrix(matrix); } void GuiRenderer::loadTexture(GuiTexturePtr guiTexture) { guiShader->loadTextureUni(guiTexture->textureId); } void GuiRenderer::unbind() { glBindVertexArray(0); } void GuiRenderer::clean() { this->guiShader->clean(); } <file_sep>/src/managers/InputManager.cpp // // Created by Martin on 19. 11. 2015. // #include "src/managers/InputManager.hpp" InputManager::InputManager(int windowWidth, int windowHeight) { this->keys = new int[1024]{0}; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->previousWheelOffset = 0.0f; this->currentWheerlOffset = 0.0f; } bool InputManager::isWPressed() { return keys[GLFW_KEY_W]; } bool InputManager::isSPressed() { return keys[GLFW_KEY_S]; } bool InputManager::isAPressed() { return keys[GLFW_KEY_A]; } bool InputManager::isDPressed() { return keys[GLFW_KEY_D]; } bool InputManager::isTPressed() { return keys[GLFW_KEY_T]; } void InputManager::wheelCallBack(GLFWwindow *, double, double yoffset) { this->currentWheerlOffset -= yoffset; } void InputManager::cursorCallback(GLFWwindow *, double x, double y) { if (keys[GLFW_MOUSE_BUTTON_LEFT] || keys[GLFW_MOUSE_BUTTON_RIGHT]) { this->currentCursorPosition = toScreenCoord(x, y); } } void InputManager::mouseButtonCallback(GLFWwindow *window, int button, int action, int mods) { if ((button == GLFW_MOUSE_BUTTON_LEFT || button == GLFW_MOUSE_BUTTON_RIGHT) && action == GLFW_PRESS) { double x, y; glfwGetCursorPos(window, &x, &y); this->lastCursorPosition = toScreenCoord(x, y); if (button == GLFW_MOUSE_BUTTON_LEFT) { keys[GLFW_MOUSE_BUTTON_LEFT] = true; } else { keys[GLFW_MOUSE_BUTTON_RIGHT] = true; } } else { keys[GLFW_MOUSE_BUTTON_LEFT] = false; keys[GLFW_MOUSE_BUTTON_RIGHT] = false; } } glm::vec3 InputManager::toScreenCoord( double x, double y ) { glm::vec3 coord(0.0f); coord.x = (2 * x - windowWidth ) / windowWidth; coord.y = -(2 * y - windowHeight) / windowHeight; /* Clamp it to border of the windows, comment these codes to allow rotation when cursor is not over window */ coord.x = glm::clamp( coord.x, -1.0f, 1.0f ); coord.y = glm::clamp( coord.y, -1.0f, 1.0f ); float length_squared = coord.x * coord.x + coord.y * coord.y; if( length_squared <= 1.0 ) coord.z = sqrt( 1.0 - length_squared ); else coord = glm::normalize( coord ); return coord; } void InputManager::onKeyPress(GLFWwindow *window, int key, int , int action, int ) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; } } bool InputManager::isRightMouseButtonPressed() { return this->keys[GLFW_MOUSE_BUTTON_RIGHT]; } bool InputManager::isLeftMouseButtonPressed() { return this->keys[GLFW_MOUSE_BUTTON_LEFT]; } float InputManager::getDistanceX() { return this->lastCursorPosition.x - this->currentCursorPosition.x; } float InputManager::getDistanceY() { return this->lastCursorPosition.y - this->currentCursorPosition.y; } double InputManager::getDistanceZoom() { double retVal = this->previousWheelOffset - currentWheerlOffset; this->previousWheelOffset = currentWheerlOffset; return retVal; }<file_sep>/src/skybox/SkyboxShader.cpp // // Created by Martin on 28. 11. 2015. // #include "src/skybox/SkyboxShader.hpp" SkyboxShader::SkyboxShader() : ShaderProgram("src/shaders/vert_skybox.glsl", "src/shaders/frag_skybox.glsl") { getAllUniformLocations(); } void SkyboxShader::getAllUniformLocations() { this->projectionMatrix = getUniformLocation("ProjectionMatrix"); this->viewMatrix = getUniformLocation("ViewMatrix"); this->fogColor = getUniformLocation("fogColor"); } void SkyboxShader::loadProjectionMatrix(glm::mat4 matrix) { loadMatrix(this->projectionMatrix, matrix); } void SkyboxShader::loadViewMatrix(glm::mat4 matrix, float rotation) { matrix[3].x = 0; matrix[3].y = 0; matrix[3].z = 0; matrix = rotate(matrix, rotation); loadMatrix(this->viewMatrix, matrix); } void SkyboxShader::loadFogColor(glm::vec3 color) { loadVector(this->fogColor, color); } glm::mat4 SkyboxShader::rotate(glm::mat4 matrix, float rotation) { return glm::rotate(matrix, glm::radians(rotation), this->rotationVec); }<file_sep>/cmake/bin2c.cmake # Convert any file to a C++ string function(bin2c INFILE VARNAME OUTFILE) file(READ ${INFILE} HEXFILE HEX) string(LENGTH ${HEXFILE} XRSLEN) set(HEXPOS 0) file(WRITE ${OUTFILE} "/* generated from ${INFILE}; do not edit */\n" "#include <string>\n" "const std::string ${VARNAME} {") while (${HEXPOS} LESS ${XRSLEN}) math(EXPR LPOS "${HEXPOS} % 32") if (NOT ${LPOS}) file(APPEND ${OUTFILE} "\n") endif () string(SUBSTRING ${HEXFILE} ${HEXPOS} 2 HEXBYTE) file(APPEND ${OUTFILE} "0x${HEXBYTE}") math(EXPR HEXPOS "${HEXPOS} + 2") if (${HEXPOS} LESS ${XRSLEN}) file(APPEND ${OUTFILE} ",") endif () endwhile () file(APPEND ${OUTFILE} "};\n") endfunction() bin2c("${SRC_FILE}" "${SYMBOL}" "${OUT_FILE}")<file_sep>/src/camera/Camera.cpp // // Created by Martin on 29. 11. 2015. // #include "src/camera/Camera.hpp" Camera::Camera() { }<file_sep>/src/objects/Pokemon.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_POKEMON_HPP #define POKEMON3D_POKEMON_HPP #include <random> #include "src/objects/MainCharacter.h" #include "src/objects/Attack.hpp" #include "src/animations/Animation.hpp" class Pokemon : public MainCharacter { protected: // TODO: v MainCharacter zmenit funkciu checkInput() na virtualnu a vytvorit novu class Player pre hlavnu postavu void checkInputs(); void generateAttacks(int count, Scene &scene); AttackPtr attackObj; float attackDelay = 0.0f; bool canAttack = true; bool wasAttacked = false; public: unsigned short id; Pokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart); Pokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart); Pokemon(unsigned short id, LoaderPtr loader, MeshPtr, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name, bool canAttackAtStart); SceneType animate(Scene &scene, float delta) override; void attack(Scene &scene); int maxHp = 1; int currentHp = 1; glm::vec3 startingPos; AnimationPtr animation; ~Pokemon(){} }; typedef std::shared_ptr<Pokemon> PokemonPtr; #endif //POKEMON3D_POKEMON_HPP <file_sep>/src/animations/Animation.cpp // // Created by Martin on 7. 12. 2015. // #include "src/animations/Animation.hpp" Animation::Animation(){ } void Animation::init(){ i = 0; animationTime = 0; } void Animation::add(KeyframePtr keyframe){ keyframes.push_back(keyframe); } glm::vec3 Animation::lerp(glm::vec3 a, glm::vec3 b, float t){ if(t > 1){ t = 1; } return a * (1 - t) + b * t; } bool Animation::animate(float dt){ if(i + 1 >= keyframes.size()){ if (repeat) init(); else return false; } float t = animationTime / (keyframes[i+1]->time - keyframes[i]->time); if (!keyframes[i]->useObjectsPosition) position = lerp(keyframes[i]->position, keyframes[i + 1]->position, t); rotation = lerp(keyframes[i]->rotation, keyframes[i + 1]->rotation, t); animationTime += dt; if(animationTime > (keyframes[i + 1]->time - keyframes[i]->time)+dt){ i++; animationTime = 0; if (!keyframes[i]->useObjectsPosition) position = keyframes[i]->position; } return true; } Animation::~Animation(){}<file_sep>/src/objects/Scene.hpp // // Created by Martin on 22. 11. 2015. // #ifndef POKEMON3D_SCENE_HPP #define POKEMON3D_SCENE_HPP #include <list> #include "src/objects/Mesh.h" #include "src/objects/Ground.hpp" #include "src/engine/MasterRenderer.hpp" #include "src/camera/ThirdPersonCamera.h" #include "src/wrappers/MeshWrapper.hpp" #include "src/gui/Gui.hpp" #include "src/skybox/Skybox.hpp" #include "src/camera/Camera.hpp" #include "src/enums/Enums.hpp" class Scene { private: std::vector<GroundPtr> grounds; MasterRendererPtr masterRenderer; std::vector<LightPtr> lights; CameraPtr camera; SkyboxPtr skybox; protected: glm::mat4 projection; InputManager *inputManager; public: // std::vector<Mesh *> objects; std::list<MeshPtr> objects; std::vector<MeshWrapperPtr> wrappers; std::vector<GuiPtr> guis; SceneType sceneType; MainCharacterPtr mainCharacter; Scene(); Scene(MasterRendererPtr masterRenderer, std::vector<LightPtr> lights, glm::mat4 projection, CameraPtr camera); // void loadObject(Mesh *mesh); void loadObject(MeshPtr meshPtr); void loadGround(GroundPtr ground); virtual void update(); SceneType animate(float delta); void render(); void clean(); void loadWrapper(MeshWrapperPtr wrapper); void loadGui(GuiPtr gui); void loadSkybox(SkyboxPtr skybox); void loadMasterRenderer(MasterRendererPtr masterRenderer); void loadLights(std::vector<LightPtr> lights); void loadLight(LightPtr light); void loadCamera(CameraPtr camera); void loadProjection(glm::mat4 projection); void loadGrounds(std::vector<GroundPtr> grounds); bool isTPressed(); bool isWPressed(); virtual ~Scene() {}; }; typedef std::shared_ptr<Scene> ScenePtr; #endif //POKEMON3D_SCENE_HPP <file_sep>/src/gui/Gui.hpp // // Created by Martin on 25. 11. 2015. // #ifndef POKEMON3D_GUI_HPP #define POKEMON3D_GUI_HPP #include <vector> #include <string> #include <vector> #include <GL/glew.h> #include "src/gui/GuiTexture.hpp" #include "src/loaders/Loader.hpp" class Gui { public: std::vector<GuiTexturePtr> guiTextures; // std::vector<GuiTexture *> guiTextures; Gui(); virtual bool animate(); }; typedef std::shared_ptr<Gui> GuiPtr; #endif //POKEMON3D_GUI_HPP <file_sep>/src/wrappers/MeshWrapper.hpp // // Created by Martin on 18. 11. 2015. // #ifndef POKEMON3D_MESHWRAPPER_H #define POKEMON3D_MESHWRAPPER_H #include "src/objects/Mesh.h" class MeshWrapper { private: GLuint programId; void createMatrixes(int count, glm::vec3 scale); public: MeshPtr mesh; // Mesh *mesh; std::vector<glm::mat4> matrixes; MeshWrapper(LoaderPtr loader, const std::string &obj_file, const std::string &image_file, int count, glm::vec3 scale); MeshWrapper(LoaderPtr loader, const std::string &obj_file, const std::string &image_file, int count, glm::vec3 scale, float reflectivity, float shineDamper); }; typedef std::shared_ptr<MeshWrapper> MeshWrapperPtr; #endif //POKEMON3D_MESHWRAPPER_H <file_sep>/src/objects/EnemyPokemon.hpp // // Created by Martin on 7. 12. 2015. // #ifndef POKEMON3D_ENEMYPOKEMON_HPP #define POKEMON3D_ENEMYPOKEMON_HPP #include "src/objects/Pokemon.hpp" class EnemyPokemon : public Pokemon { private: public: EnemyPokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); EnemyPokemon(unsigned short id, LoaderPtr loader, const std::string &, const std::string &, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); EnemyPokemon(unsigned short id, LoaderPtr loader, MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper, InputManager *inputManager, const std::string &attack_obj_file, const std::string &attack_image_name); SceneType animate(Scene &scene, float delta) override; }; typedef std::shared_ptr<EnemyPokemon> EnemyPokemonPtr; #endif //POKEMON3D_ENEMYPOKEMON_HPP <file_sep>/src/scenes/MainScene.cpp // // Created by Martin on 30. 11. 2015. // #include "src/scenes/MainScene.hpp" MainScene::MainScene(MasterRendererPtr masterRenderer, CameraPtr camera, LoaderPtr loader, PokemonRepositoryPtr pokemonRepository, std::vector<GroundPtr> grounds, SkyboxPtr skybox, std::vector<MeshWrapperPtr> trees, MainCharacterPtr mainCharacter, std::vector<TerrainPtr> terrains, InputManager *inputManager) : Scene() { AnimationPtr animation = AnimationPtr(new Animation()); animation->add(KeyframePtr(new Keyframe(0, glm::vec3(15.0f, 0.0f, 0.0f), glm::vec3(0.0f)))); animation->add(KeyframePtr(new Keyframe(1, glm::vec3(15.0f, 0.0f, 2.5f), glm::vec3(0.0f)))); animation->add(KeyframePtr(new Keyframe(2, glm::vec3(10.0f, 0.0f, 2.5f), glm::vec3(0.0f, 90.0f, 0.0f)))); animation->add(KeyframePtr(new Keyframe(3, glm::vec3(10.0f, 0.0f, -2.5f), glm::vec3(0.0f, 65.0f, 0.0f)))); animation->add(KeyframePtr(new Keyframe(4, glm::vec3(15.0f, 0.0f, -2.5f), glm::vec3(0.0f, 270.0f, 0.0f)))); animation->add(KeyframePtr(new Keyframe(5, glm::vec3(15.0f, 0.0f, 0.0f), glm::vec3(0.0f, 360.0f, 0.0f)))); this->pokemonData[1].animation = animation; this->inputManager = inputManager; this->sceneType = SceneType::MAIN_SCEEN; this->projection = glm::perspective(45.0f, GLfloat(1600) / GLfloat(900), 0.1f, 750.0f); this->loadMasterRenderer(masterRenderer); this->loadCamera(camera); this->loadProjection(this->projection); // load main character this->loadObject(mainCharacter); camera->setFollowTarget(mainCharacter); this->mainCharacter = mainCharacter; // load pokemons with specified data for (auto pokemonDataLoop : this->pokemonData) { auto pokemon = pokemonRepository->findPokemon(pokemonDataLoop.id); pokemon->setPosition(pokemonDataLoop.position); pokemon->setRotation(pokemonDataLoop.rotation); pokemon->setScale(pokemonDataLoop.scale); pokemon->animation = pokemonDataLoop.animation; this->loadObject(pokemon); } // load grounds for (auto groundLoop : grounds) { this->loadGround(groundLoop); } // load trees for (auto treeLoop : trees) { this->loadWrapper(treeLoop); } auto light1 = LightPtr(new Light(glm::vec3(50.0f, 50.0f, 50.0f), glm::vec3(0.9f))); auto lamp1 = StreetLampPtr(new StreetLamp(loader, glm::vec3(50.0f, 0.0f, 0.0f))); auto lamp2 = StreetLampPtr(new StreetLamp(loader, glm::vec3(-100.0f, 0.0f, 50.0f))); auto lamp3 = StreetLampPtr(new StreetLamp(loader, glm::vec3(-50.0f, 0.0f, -100.0f))); this->loadLight(light1); this->loadLight(lamp1->light); this->loadLight(lamp2->light); this->loadLight(lamp3->light); this->loadObject(lamp1); this->loadObject(lamp2); this->loadObject(lamp3); this->loadProjection(glm::perspective(45.0f, GLfloat(1600) / GLfloat(900), 0.1f, 750.0f)); // load terrains for (auto terrainLoop : terrains) { this->loadObject(terrainLoop); } this->loadSkybox(skybox); } <file_sep>/src/objects/Light.cpp // // Created by Martin on 17. 11. 2015. // #include "src/objects/Light.hpp" Light::Light(glm::vec3 position, glm::vec3 color) { this->position = position; this->color = color; this->attenuation = glm::vec3(1.0f, 0.0f, 0.0f); } Light::Light(glm::vec3 position, glm::vec3 color, glm::vec3 attenuation) { this->position = position; this->color = color; this->attenuation = attenuation; } <file_sep>/src/textures/TerrainTexturePack.cpp // // Created by Martin on 19. 11. 2015. // #include "src/textures/TerrainTexturePack.hpp" TerrainTexturePack::TerrainTexturePack(TerrainTexturePtr backgroundTexture, TerrainTexturePtr rTexture, TerrainTexturePtr gTexture, TerrainTexturePtr bTexture) { this->backgroundTexture = TerrainTexturePtr(backgroundTexture); this->rTexture = TerrainTexturePtr(rTexture); this->gTexture = TerrainTexturePtr(gTexture); this->bTexture = TerrainTexturePtr(bTexture); } <file_sep>/src/textures/Texture.cpp // // Created by Martin on 17. 11. 2015. // #include "src/textures/Texture.hpp" Texture::Texture(int textureId) { this->textureId = textureId; } <file_sep>/src/textures/TerrainTexture.hpp // // Created by Martin on 19. 11. 2015. // #ifndef POKEMON3D_TERRAINTEXTURE_HPP #define POKEMON3D_TERRAINTEXTURE_HPP #include <memory> class TerrainTexture { public: int textureId; TerrainTexture(int texture_id); }; typedef std::shared_ptr<TerrainTexture> TerrainTexturePtr; #endif //POKEMON3D_TERRAINTEXTURE_HPP <file_sep>/src/animations/Keyframe.cpp // // Created by Martin on 7. 12. 2015. // #include "src/animations/Keyframe.hpp" Keyframe::Keyframe(float time, glm::vec3 rot) { this->time = time; rotation = rot; useObjectsPosition = true; } Keyframe::Keyframe(float t, glm::vec3 pos, glm::vec3 rot){ time = t; position = pos; rotation = rot; } Keyframe::~Keyframe(){}<file_sep>/src/objects/Grass.cpp // // Created by Martin on 8. 12. 2015. // #include "src/objects/Grass.hpp" #include "Scene.hpp" Grass::Grass(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Terrain(loader, object_name, file_name, position, rotX, rotY, rotZ, scale) { } Grass::Grass(LoaderPtr loader, const std::string &object_name, const std::string &file_name, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : Terrain(loader, object_name, file_name, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper) { } Grass::Grass(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale) : Terrain(mesh, position, rotX, rotY, rotZ, scale){ } Grass::Grass(MeshPtr mesh, glm::vec3 position, float rotX, float rotY, float rotZ, float scale, float reflectivity, float shineDamper) : Terrain(mesh, position, rotX, rotY, rotZ, scale, reflectivity, shineDamper){ } SceneType Grass::animate(Scene &scene, float delta) { stepTime += delta; if (this->useAnimation) { if (!this->animation->animate(delta)) isAnimating = false; else { this->rotX = this->animation->rotation.x; isAnimating = true; } } if (glm::distance(this->position, scene.mainCharacter->position) < this->radius + scene.mainCharacter->radius) { // if (stepTime > 3.0f) { // stepTime = 0.0f; int chance = (int) Math::random(0.0f, 100.0f); if (chance == 99) return SceneType::BATTLE_SCEEN; // } } // createTransformationMatrix(); return scene.sceneType; } void Grass::initAnimation() { this->animation->init(); }<file_sep>/src/objects/Ground.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_GROUND_H #define POKEMON3D_GROUND_H #include "src/objects/Mesh.h" #include "src/textures/TerrainTexturePack.hpp" class Ground { private: const float size = 800; const float vertex_count = 128; void generateGround(); public: MeshPtr mesh; float x; float z; TerrainTexturePackPtr texturePack; TerrainTexturePtr blendMap; float reflectivity = 0.1f; float shineDamper = 50.0f; GLuint programId; Ground(GLint program_id, int gridX, int gridZ, const std::string &image_file, TerrainTexturePackPtr texturePack, TerrainTexturePtr blendMap); }; typedef std::shared_ptr<Ground> GroundPtr; #endif //POKEMON3D_GROUND_H <file_sep>/src/objects/Light.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_LIGHT_H #define POKEMON3D_LIGHT_H #include <memory> #include <glm/glm.hpp> class Light { private: public: glm::vec3 position; glm::vec3 color; glm::vec3 attenuation; Light(glm::vec3 position, glm::vec3 color); Light(glm::vec3 position, glm::vec3 color, glm::vec3 attenuation); }; typedef std::shared_ptr<Light> LightPtr; #endif //POKEMON3D_LIGHT_H <file_sep>/src/models/TexturedModel.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_TEXTUREDMODEL_H #define POKEMON3D_TEXTUREDMODEL_H #include <memory> #include "src/textures/Texture.hpp" #include "src/models/RawModel.hpp" #include <glm/glm.hpp> class TexturedModel { private: public: glm::mat4 matrix; RawModelPtr rawModel; // RawModel *rawModel; TexturePtr texture; // nsTexture::Texture *texture; TexturedModel(); }; typedef std::shared_ptr<TexturedModel> TexturedModelPtr; #endif //POKEMON3D_TEXTUREDMODEL_H <file_sep>/src/gui/Gui.cpp // // Created by Martin on 25. 11. 2015. // #include "src/gui/Gui.hpp" Gui::Gui() { } bool Gui::animate() { return true; }<file_sep>/src/engine/GroundRenderer.hpp // // Created by Martin on 17. 11. 2015. // #ifndef POKEMON3D_GROUNDRENDERER_H #define POKEMON3D_GROUNDRENDERER_H #include <src/objects/Ground.hpp> #include "src/shaders/GroundShader.hpp" #include "src/objects/Mesh.h" class GroundRenderer { private: void prepareGround(GroundPtr model, glm::mat4 projection, glm::mat4 view); void unbindMesh(); void prepareInstance(GroundPtr ground); void render(MeshPtr mesh, glm::mat4 projection, glm::mat4 view); void loadModelMatrix(GroundPtr ground); void bindTextures(GroundPtr ground); public: GroundShaderPtr shader; // GroundShader *shader; GroundRenderer(GroundShaderPtr shader); void render(std::vector<GroundPtr> grounds, glm::mat4 projection, glm::mat4 view); }; typedef std::shared_ptr<GroundRenderer> GroundRendererPtr; #endif //POKEMON3D_GROUNDRENDERER_H<file_sep>/src/camera/ThirdPersonCamera.cpp // // Created by Martin on 16. 11. 2015. // #include "src/camera/ThirdPersonCamera.h" ThirdPersonCamera::ThirdPersonCamera(MovableCharacterPtr movableCharacter, GLFWwindow * window, InputManager *inputManager) : movableCharacter(movableCharacter){ this->initPosition(); this->inputManager = inputManager; } void ThirdPersonCamera::calculateZoom() { this->distance -= this->inputManager->getDistanceZoom(); } void ThirdPersonCamera::calculatePitch() { if (this->inputManager->isRightMouseButtonPressed()) { float pitchChange = this->inputManager->getDistanceY(); this->pitch -= pitchChange; if (this->pitch > 179.0f) { this->pitch = 179.0f; } else if (this->pitch < 1.0f) { this->pitch = 1.0f; } } } void ThirdPersonCamera::calculateAngle() { if (this->inputManager->isLeftMouseButtonPressed()) { float angleChanged = this->inputManager->getDistanceX(); this->angle -= angleChanged; } } void ThirdPersonCamera::move() { calculateZoom(); calculatePitch(); calculateAngle(); calculateZoom(); float horDist = calculateHorizontalDistance(); float vertDist = calculateVerticalDistance(); calculateCameraPosition(horDist, vertDist); this->yaw = 180 - (*followTargetRotY + angle); } float ThirdPersonCamera::calculateHorizontalDistance() { return distance * glm::cos(glm::radians(this->pitch)); } float ThirdPersonCamera::calculateVerticalDistance() { return distance * glm::sin(glm::radians(this->pitch)); } void ThirdPersonCamera::calculateCameraPosition(float horizontalDistance, float verticalDistance) { float theta = *followTargetRotY + angle; float offsetX = horizontalDistance * glm::sin(glm::radians(theta)); float offsetZ = horizontalDistance * glm::cos(glm::radians(theta)); // position.x = movableCharacter->position.x - offsetX; // position.z = movableCharacter->position.z - offsetZ; position.x = followTargetPosition->x - offsetX; position.z = followTargetPosition->z - offsetZ; // position.y = movableCharacter->position.y + verticalDistance; position.y = followTargetPosition->y + verticalDistance; } glm::mat4 ThirdPersonCamera::getViewMatrix() { glm::mat4 viewMatrix; viewMatrix = glm::rotate(viewMatrix, glm::radians(this->pitch), glm::vec3(1.0f, 0.0f, 0.0f)); viewMatrix = glm::rotate(viewMatrix, glm::radians(this->yaw), glm::vec3(0.0f, 1.0f, 0.0f)); viewMatrix = glm::translate(viewMatrix, glm::vec3(-this->position.x, -this->position.y, -this->position.z)); return viewMatrix; } void ThirdPersonCamera::setFollowTarget(MovableCharacterPtr followTarget) { setFollowTarget(&followTarget->position, &followTarget->rotX, &followTarget->rotY, &followTarget->rotZ); } void ThirdPersonCamera::setFollowTarget(glm::vec3 *targetPositionVec, float *targetRotX, float *targetRotY, float *targetRotZ) { this->followTargetRotX = targetRotX; this->followTargetRotY = targetRotY; this->followTargetRotZ = targetRotZ; this->followTargetPosition = targetPositionVec; this->initPosition(*this->followTargetPosition); } void ThirdPersonCamera::initPosition() { initPosition(this->movableCharacter->position); } void ThirdPersonCamera::initPosition(glm::vec3 position) { this->pitch = 20.0f; this->angle = 0.0f; this->distance = 10.0f; this->position = position + glm::vec3(0.0f, this->pitch, this->distance); } void ThirdPersonCamera::setPosition(glm::vec3 position) { initPosition(position); } <file_sep>/src/repository/Repository.hpp // // Created by Martin on 30. 11. 2015. // #ifndef POKEMON3D_REPOSITORY_HPP #define POKEMON3D_REPOSITORY_HPP #include <memory> #include <glm/glm.hpp> #include "src/animations/Animation.hpp" typedef struct PokemonData { unsigned short id; glm::vec3 rotation; glm::vec3 position; float scale; int maxHp; AnimationPtr animation; } PokemonData; class Repository { public: Repository(); }; typedef std::shared_ptr<Repository> RepositoryPtr; #endif //POKEMON3D_REPOSITORY_HPP <file_sep>/src/models/TexturedModel.cpp // // Created by Martin on 17. 11. 2015. // #include <src/loaders/tiny_obj_loader.h> #include "src/models/TexturedModel.hpp" TexturedModel::TexturedModel() { } // shared resources //RawModelPtr TexturedModel::rawModel; //TexturePtr TexturedModel::texture; <file_sep>/src/shaders/ShaderProgram.cpp // // Created by Martin on 16. 11. 2015. // #include "src/shaders/ShaderProgram.hpp" ShaderProgram::ShaderProgram(const std::string &vertex_shader_file, const std::string &fragment_shader_file) { this->vertexShaderId = loadShader(vertex_shader_file, GL_VERTEX_SHADER); this->fragmentShaderId = loadShader(fragment_shader_file, GL_FRAGMENT_SHADER); // Create and link the program // this->programId = glCreateProgram(); // glAttachShader(programId, vertexShaderId); // glAttachShader(programId, fragmentShaderId); // glBindFragDataLocation(programId, 0, "FragmentColor"); // bindAttributes(); // glLinkProgram(programId); this->programId = createProgram(vertexShaderId, fragmentShaderId); } void ShaderProgram::bindAttributes() {}; void ShaderProgram::start() { glUseProgram(programId); } void ShaderProgram::stop() { glUseProgram(0); } void ShaderProgram::clean() { stop(); glDetachShader(programId, vertexShaderId); glDetachShader(programId, fragmentShaderId); glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); glDeleteProgram(programId); } void ShaderProgram::bindAttribute(int attribute, const std::string &varname) { glBindAttribLocation(programId, attribute, varname.c_str()); } GLint ShaderProgram::getUniformLocation(const std::string uniformName) { return glGetUniformLocation(programId, uniformName.c_str()); } void ShaderProgram::loadFloat(GLint location, float value) { glUniform1f(location, value); } void ShaderProgram::loadInt(GLint location, int value) { glUniform1i(location, value); } void ShaderProgram::loadVector(GLint location, glm::vec3 vector) { glUniform3f(location, vector.x, vector.y, vector.z); } void ShaderProgram::loadMatrix(GLint location, glm::mat4 matrix) { glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(matrix)); } void ShaderProgram::loadBoolean(GLint location, bool value) { float load; if (value) load = 1; else load = 0; glUniform1f(location, load); } void ShaderProgram::loadTexture(GLint location, GLint texture_id) { // Bind the texture to "Texture" uniform in program glUniform1i(location, 0); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, texture_id); } GLint ShaderProgram::loadShader(const std::string &shader_file, GLint type) { // Create shaders auto shader_id = glCreateShader(type); auto result = GL_FALSE; auto info_length = 0; // Load shader code std::ifstream shader_stream(shader_file); std::string shader_code((std::istreambuf_iterator<char>(shader_stream)), std::istreambuf_iterator<char>()); // Compile shader std::cout << "Compiling Shader ..." << shader_file << std::endl; auto shader_code_ptr = shader_code.c_str(); glShaderSource(shader_id, 1, &shader_code_ptr, NULL); glCompileShader(shader_id); // Check vertex shader log glGetShaderiv(shader_id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &info_length); std::string vertex_shader_log((unsigned int)info_length, ' '); glGetShaderInfoLog(shader_id, info_length, NULL, &vertex_shader_log[0]); std::cout << vertex_shader_log << std::endl; } return shader_id; } GLint ShaderProgram::createProgram(GLint vertex_shader_id, GLint fragment_shader_id) { auto result = GL_FALSE; auto info_length = 0; // Create and link the program std::cout << "Linking Shader Program ..." << std::endl; auto program_id = glCreateProgram(); glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glBindFragDataLocation(program_id, 0, "FragmentColor"); glLinkProgram(program_id); // Check program log glGetProgramiv(program_id, GL_LINK_STATUS, &result); if (result == GL_FALSE) { glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &info_length); std::string program_log((unsigned long)info_length, ' '); glGetProgramInfoLog(program_id, info_length, NULL, &program_log[0]); std::cout << program_log << std::endl; } glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return program_id; }
ebe15fa88d9223685ca56b7a40e0736fa7adcf3d
[ "Markdown", "CMake", "C++" ]
104
C++
nemcek/Pokemon-3D
50451f91999fe9168e8f520748e39b7e9099624a
c92983304dbfb4c69f78c2d0823dfcf5c8bbd8e4
refs/heads/master
<file_sep>from __future__ import absolute_import, division, print_function import os import tensorflow as tf from tensorflow import keras ################# # LOAD DATA # ################# (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() train_labels = train_labels[:1000] test_labels = test_labels[:1000] train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0 # <-- NOT SURE WHY THESE ARE RESHAPRED WHEN THEY WEREN'T IN THE IMAGE EXAMPLE, OH WELL WHO CARES, SAME DIFFERENCE I EXCEPT test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0 ########################### # CREATE SIMPLE MODEL # ########################### # Returns a short sequential model def create_model(): model = tf.keras.models.Sequential([ keras.layers.Dense(512, activation=tf.keras.activations.relu, input_shape=(784,)), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation=tf.keras.activations.softmax) ]) model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.sparse_categorical_crossentropy, metrics=['accuracy']) return model # Create a basic model instance model = create_model() model.summary() ########################### # MODEL CHECKPOINTING # ########################### # Checkpointing allows you to use a trained model without having to retrain it, or pick-up training where you left of—in case the training process was interrupted. checkpoint_path = "training_1/cp.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) # Create checkpoint callback cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1) # instantiate model model = create_model() # fit model model.fit(train_images, train_labels, epochs = 10, validation_data = (test_images,test_labels), callbacks = [cp_callback]) # pass callback to training, which saves the model, and creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch: ########################################################################## # CREATE NEW MODEL ONTO WHICH WE WILL DROP LOADED CHECKPOINT WEIGHTS # ########################################################################## # Create fresh model instance. When restoring a model from only weights, you must have a model with the same architecture as the original model. # observe accuracy with random weights, funny that you are able to do this.... when i think about it model = create_model() loss, acc = model.evaluate(test_images, test_labels) print("Untrained model, accuracy: {:5.2f}%".format(100*acc)) ############################################## # LOAD WEIGHTS, VERIFY MODEL PERFORMANCE # ############################################## model.load_weights(checkpoint_path) loss,acc = model.evaluate(test_images, test_labels) print("Restored model, accuracy: {:5.2f}%".format(100*acc)) ################################################################################### # CALLBACK PROVIDES OPTIONS, LETS SAVE EVERY 5 EPOCHS AND PROVIDE CUSTOM NAME # ################################################################################### # include the epoch in the file name. (uses `str.format`) checkpoint_path = "training_2/cp-{epoch:04d}.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) cp_callback = tf.keras.callbacks.ModelCheckpoint( checkpoint_path, verbose=1, save_weights_only=True, # Save weights, every 5-epochs. period=5) model = create_model() model.save_weights(checkpoint_path.format(epoch=0)) model.fit(train_images, train_labels, epochs = 50, callbacks = [cp_callback], validation_data = (test_images,test_labels), verbose=0) latest = tf.train.latest_checkpoint(checkpoint_dir) latest # reload model and verify it works model = create_model() model.load_weights(latest) loss, acc = model.evaluate(test_images, test_labels) print("Restored model, accuracy: {:5.2f}%".format(100*acc)) ################################################################ # MANUALLY SAVE WEIGHTS, RATHER THAN CHECKPOINTING TO SAVE # ################################################################ # Save the weights model.save_weights('./checkpoints/my_checkpoint') # Restore the weights model = create_model() model.load_weights('./checkpoints/my_checkpoint') loss,acc = model.evaluate(test_images, test_labels) print("Restored model, accuracy: {:5.2f}%".format(100*acc)) ################################## # MANUALLY SAVE ENTIRE MODEL # ################################## # This allows you to checkpoint a model and resume training later—from the exact same state—without access to the original code. model = create_model() model.fit(train_images, train_labels, epochs=5) # Save entire model to a HDF5 file model.save('my_model.h5') # Recreate the exact same model, including weights and optimizer. new_model = keras.models.load_model('my_model.h5') new_model.summary() # VERIFY ACCURACY loss, acc = new_model.evaluate(test_images, test_labels) print("Restored model, accuracy: {:5.2f}%".format(100*acc)) # blabla.. some more stuff... who cares right now <file_sep># The purpose of this script is to create a tensorflow model on the same data as my hand-crafted network. # Spoilers, I succeed. from __future__ import absolute_import, division, print_function import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt import os import imageio import pandas as pd print(tf.__version__) ################## # PATH # ################## path = '/users/josh.flori/desktop/images/' m = len([i for i in os.listdir(path) if 'jpg' in i]) ################## # load x/y # ################## X = np.array([imageio.imread(path + str(i) + '.jpg') for i in range(1, m + 1)]) Y = np.array(pd.read_csv('/users/josh.flori/desktop/Y.csv')['Y'].values.tolist()) X.shape Y.shape ########################## # STANDARDIZE DATA # ########################## X = X / 255 ########################## # ASSERTION CHECKING # ########################## assert (X.shape[0] == m) assert (Y.shape[0] == m) ########################## # VISUALIZE DATA # ########################## for i in range(10): print(Y[i]) plt.figure() plt.imshow(X[i]) plt.show() ##################### # RANDOMIZE # ##################### np.random.seed(0) np.random.shuffle(X) np.random.seed(0) np.random.shuffle(Y) ####################### # TRAIN TEST # ####################### train_X, dev_X, test_X = np.split(X, [int(.8 * X.shape[0]), int(.9 * X.shape[0])]) train_Y, dev_Y, test_Y = np.split(Y, [int(.8 * X.shape[0]), int(.9 * X.shape[0])]) ######################## # DEFINE MODEL # ######################## model = keras.Sequential([ keras.layers.Flatten(input_shape=(35, 20, 3)), keras.layers.Dense(50, activation=tf.nn.sigmoid), keras.layers.Dense(50, activation=tf.nn.sigmoid), keras.layers.Dense(50, activation=tf.nn.sigmoid), keras.layers.Dense(2, activation=tf.nn.softmax) ]) ######################## # COMPILE MODEL # ######################## model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ##################### # FIT MODEL # ##################### model.fit(train_X, train_Y, epochs=100, verbose=2, validation_data=(dev_X, dev_Y)) ################################ # EVALUATE ON TEST DATA # ################################ model.evaluate(test_X, test_Y) ######################################### # PRODUCE THE PREDICTIONS, IF NEEDED # ######################################### predictions = model.predict(test_X) predictions.shape np.argmax(predictions[0]) <file_sep>from __future__ import absolute_import, division, print_function import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt """"" To find an appropriate model size, it's best to start with relatively few layers and parameters, then begin increasing the size of the layers or adding new layers until you see diminishing returns on the validation loss. Let's try this on our movie review classification network. """ ##################################################################################### # Rather than using an embedding as in the previous notebook, here we will multi-hot encode the sentences. This model will quickly overfit to the training set. It will be used to demonstrate when overfitting occurs, and how to fight it. # Multi-hot-encoding our lists means turning them into vectors of 0s and 1s. Concretely, this would mean for instance turning the sequence [3, 5] into a 10,000-dimensional vector that would be all-zeros except for indices 3 and 5, which would be ones. ##################################################################################### NUM_WORDS = 10000 (train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS) def multi_hot_sequences(sequences, dimension): # Create an all-zero matrix of shape (len(sequences), dimension) results = np.zeros((len(sequences), dimension)) for i, word_indices in enumerate(sequences): results[i, word_indices] = 1.0 # set specific indices of results[i] to 1s return results # confirmed that even if a sentence contains the same word more than once, that position in the 10,000 still just gets a 1 train_data = multi_hot_sequences(train_data, dimension=NUM_WORDS) test_data = multi_hot_sequences(test_data, dimension=NUM_WORDS) ####################################### # VISUALIZE ONE-HOT REPRESENTATIONS # ####################################### plt.plot(train_data[100]) plt.show() ########################################################### # CREATE OVERFITTED BASELINE MODEL, DECREASE FROM THERE # ########################################################### baseline_model = keras.Sequential([ # `input_shape` is only required here so that `.summary` works. keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(16, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) baseline_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) baseline_model.summary() baseline_history = baseline_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) ########################## # CREATE SMALLER MODEL # ########################## smaller_model = keras.Sequential([ keras.layers.Dense(4, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(4, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) smaller_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) smaller_model.summary() smaller_history = smaller_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) ############################## # CREATE EVEN LARGER MODEL # ############################## bigger_model = keras.models.Sequential([ keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(512, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) bigger_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy','binary_crossentropy']) bigger_model.summary() bigger_history = bigger_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) ################################# # PLOT LOSS ON VARIOUS MODELS # ################################# def plot_history(histories, key='binary_crossentropy'): plt.figure(figsize=(16,10)) for name, history in histories: val = plt.plot(history.epoch, history.history['val_'+key], '--', label=name.title()+' Val') plt.plot(history.epoch, history.history[key], color=val[0].get_color(), label=name.title()+' Train') plt.xlabel('Epochs') plt.ylabel(key.replace('_',' ').title()) plt.legend() plt.xlim([0,max(history.epoch)]) plt.show() plot_history([('baseline', baseline_history), ('smaller', smaller_history), ('bigger', bigger_history)]) ####################### # L2 REGULARIZATION # ####################### # Thus a common way to mitigate overfitting is to put constraints on the complexity of a network by forcing its weights only to take small values, which makes the distribution of weight values more "regular". This is called "weight regularization", and it is done by adding to the loss function of the network a cost associated with having large weights. This cost comes in two flavors: # L1 regularization: proportional to the absolute value of the weights coefficients # L2 regularization: proportional to the square of the value of the weights coefficients. Also called weight decay in the context of neural networks. # regularization is specified in the layers l2_model = keras.models.Sequential([ keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001), activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) l2_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy', 'binary_crossentropy']) l2_model_history = l2_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) ############################ # DROPOUT REGULARIZATION # ############################ dpt_model = keras.models.Sequential([ keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)), keras.layers.Dropout(0.5), keras.layers.Dense(16, activation=tf.nn.relu), keras.layers.Dropout(0.5), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) dpt_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy','binary_crossentropy']) dpt_model_history = dpt_model.fit(train_data, train_labels, epochs=20, batch_size=512, validation_data=(test_data, test_labels), verbose=2) ############################### # PLOT L2 then DROPOUT loss # ############################### plot_history([('baseline', baseline_history), ('l2', l2_model_history)]) plot_history([('baseline', baseline_history), ('dropout', dpt_model_history)]) <file_sep>from __future__ import absolute_import, division, print_function import pathlib import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) ////////////////////////////////////////////////////////////////////////////////////// //////// MAYBE AN OVERVIEW /////////// ////////////////////////////////////////////////////////////////////////////////////// # * Mean Squared Error (MSE) is a common loss function used for regression problems (different loss functions are used for classification problems). # * Similarly, evaluation metrics used for regression differ from classification. A common regression metric is Mean Absolute Error (MAE). # * When numeric input data features have values with different ranges, each feature should be scaled independently to the same range. # * If there is not much training data, one technique is to prefer a small network with few hidden layers to avoid overfitting. # * Early stopping is a useful technique to prevent overfitting. ////////////////////////////////////////////////////////////////////////////////////// ################################################################################## # NOTICE HERE THERE IS NO VALIDATION SET, IT IS CREATED WHEN CALLING MODEL.FIT # ################################################################################## ############### # LOAD DATA # ############### dataset_path = keras.utils.get_file("auto-mpg.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data") column_names = ['MPG','Cylinders','Displacement','Horsepower','Weight', 'Acceleration', 'Model Year', 'Origin'] raw_dataset = pd.read_csv(dataset_path, names=column_names, na_values = "?", comment='\t', sep=" ", skipinitialspace=True) # we want to create a copy per this https://stackoverflow.com/questions/27673231/why-should-i-make-a-copy-of-a-data-frame-in-pandas dataset = raw_dataset.copy() dataset.tail() # see there are some bad values, drop them dataset.isna().sum() dataset = dataset.dropna() # convert to numeric, pop extracts the column, removing it from df. origin = dataset.pop('Origin') # march onward toward dummary variables, pretty cool way of going about this. i need to keep this in mind. i like it... dataset['USA'] = (origin == 1)*1.0 dataset['Europe'] = (origin == 2)*1.0 dataset['Japan'] = (origin == 3)*1.0 dataset.tail() # realllly elegant way of creating traintest on dataframe.... train_dataset = dataset.sample(frac=0.8,random_state=0) test_dataset = dataset.drop(train_dataset.index) ########################### # VISUALLY INSPECT DATA # ########################### sns.pairplot(train_dataset[["MPG", "Cylinders", "Displacement", "Weight"]], diag_kind="kde") plt.show() ################################## # OBSERVE DESCRIPTIVES OF DATA # ################################## train_stats = train_dataset.describe() train_stats.pop("MPG") train_stats = train_stats.transpose() train_stats ###################################### # POP OUT LABELS FROM REST OF DATA # ###################################### train_labels = train_dataset.pop('MPG') test_labels = test_dataset.pop('MPG') #################### # NORMALIZE DATA # #################### def norm(x): return (x - train_stats['mean']) / train_stats['std'] ######################### # APPLY NORMALIZATION # ######################### # so this is a nice little vectorization thing normed_train_data = norm(train_dataset) normed_test_data = norm(test_dataset) # CAUTION!!!! The statistics used to normalize the inputs here (mean and standard deviation) need to be applied to any other data that is fed to the model, along with the one-hot encoding that we did earlier. That includes the test set as well as live data when the model is used in production. ################# # BUILD MODEL # ################# def build_model(): model = keras.Sequential([ layers.Dense(64, activation=tf.nn.relu, input_shape=[len(train_dataset.keys())]), layers.Dense(64, activation=tf.nn.relu), layers.Dense(1) ]) optimizer = tf.keras.optimizers.RMSprop(0.001) model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mean_absolute_error', 'mean_squared_error']) return model model = build_model() model.summary() ################# # TRAIN MODEL # ################# # Display training progress by printing a single dot for each completed epoch class PrintDot(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs): if epoch % 100 == 0: print('') print('.', end='') history = model.fit( normed_train_data, train_labels, epochs=1000, validation_split = 0.2, verbose=0, callbacks=[PrintDot()]) ################################# # QUIK-INSPECT FINAL LEARNING # ################################# hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch hist.tail() ################### # PLOST HISTORY # ################### def plot_history(history): hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Abs Error [MPG]') plt.plot(hist['epoch'], hist['mean_absolute_error'], label='Train Error') plt.plot(hist['epoch'], hist['val_mean_absolute_error'], label = 'Val Error') plt.ylim([0,5]) plt.legend() plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Square Error [$MPG^2$]') plt.plot(hist['epoch'], hist['mean_squared_error'], label='Train Error') plt.plot(hist['epoch'], hist['val_mean_squared_error'], label = 'Val Error') plt.ylim([0,20]) plt.legend() plt.show() plot_history(history) #################################################################### # VALIDATION STOPS IMPROVING EARLY, SO WE CAN USE EARLY STOPPING # #################################################################### model = build_model() # The patience parameter is the amount of epochs to check for improvement early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10) history = model.fit(normed_train_data, train_labels, epochs=EPOCHS, validation_split = 0.2, verbose=0, callbacks=[early_stop, PrintDot()]) plot_history(history) ############################ # GENERALIZE TO TEST SET # ############################ loss, mae, mse = model.evaluate(normed_test_data, test_labels, verbose=0) # IT GENERALIZES WELL print("Testing set Mean Abs Error: {:5.2f} MPG".format(mae)) ########################### # VISUALIZE PREDICTIONS # ########################### test_predictions = model.predict(normed_test_data).flatten() plt.scatter(test_labels, test_predictions) plt.xlabel('True Values [MPG]') plt.ylabel('Predictions [MPG]') plt.axis('equal') plt.axis('square') plt.xlim([0,plt.xlim()[1]]) plt.ylim([0,plt.ylim()[1]]) _ = plt.plot([-100, 100], [-100, 100]) plt.show() ################################## # VISUALIZE ERROR DISTRIBUTION # ################################## error = test_predictions - test_labels plt.hist(error, bins = 25) plt.xlabel("Prediction Error [MPG]") _ = plt.ylabel("Count") plt.show() <file_sep># TensorFlow-Training This repo is for tensorflow training.
020a1ce8da1f1184c43a768f94ab22848e24ee85
[ "Markdown", "Python" ]
5
Python
josh-flori/TensorFlow-Training
7e460c440980f92d62ef55d972c30d4687316491
a37f4540664b0b16e37bbebf09ea728c0c97f807
refs/heads/master
<file_sep>import java.io.*; import java.util.*; public class Hallway extends Room implements Serializable { private int lamp; private int window; private int closet; private int atticPanel; private int statue; private boolean hallwayVisited; private boolean lampOn; private boolean windowOpen; private boolean isScouted; private boolean panelOpen; private boolean closetOpen; private boolean closetFightComplete; private boolean panelFightComplete; private boolean finalFightComplete; private List<String> hallwayKeywords = new ArrayList<String>(); private static String[] lampActions = {"examine" , "punch", "turn on", "turn off"}; private static String[] windowActions = {"examine" , "open", "close", "jump out", "look out"}; private static String[] closetActions = {"examine" , "open", "close", "listen", "knock", "look inside"}; private static String[] panelActions = {"examine" , "open", "close", "look inside"}; private static String[] statueActions = {"examine" , "punch", "kick", "imitate", "smell"}; Hallway(){ super(); this.lamp = 0; this.window = 0; this.closet = 0; this.atticPanel = 0; this.statue = 0; } Hallway(int roomID, String roomName, String roomDescription, String roomUniques, int northDoor, int southDoor, int eastDoor, int westDoor, int lamp, int window, int closet, int atticPanel, int statue){ super(roomID, roomName, roomDescription, roomUniques, northDoor, southDoor, eastDoor, westDoor); this.lamp = lamp; this.window = window; this.closet = closet; this.atticPanel = atticPanel; this.statue = statue; this.lampOn = false; this.windowOpen = false; this.panelOpen = false; this.closetOpen = false; this.isScouted = false; this.closetFightComplete = false; this.panelFightComplete = false; this.finalFightComplete = false; this.hallwayVisited = false; } public void setLamp(int lamp){ this.lamp = lamp; } public void setWindow(int window){ this.window = window; } public void setCloset(int closet){ this.closet = closet; } public void setAtticPanel(int atticPanel){ this.atticPanel = atticPanel; } public void setStatue(int statue){ this.statue = statue; } public int getCloset(){ return this.closet; } public int getAtticPanel(){ return this.atticPanel; } public int getStatue(){ return this.statue; } public int getLamp(){ return this.lamp; } public int getWindow(){ return this.window; } public void setHallwayVisited(Boolean visit){ this.hallwayVisited = visit; } public Boolean getHallwayVisited(){ return this.hallwayVisited; } public Boolean getFinalFight(){ return this.finalFightComplete; } public void addKeyword(String keyword){ this.hallwayKeywords.add(keyword); } public void findKeyword(Player player, String keyword) throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException{ boolean isFound = false; for(int i = 0; i < this.hallwayKeywords.size();i++){ if(this.hallwayKeywords.get(i).toLowerCase().startsWith(keyword)){ this.performAction(player, keyword); isFound = true; } } if(!isFound){ System.out.println("The game does not recognize the word, " + keyword + "!"); } } public void performAction(Player player, String keyword) throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException{ boolean userChoice; boolean center = false; String userAction; if(keyword.startsWith("walk to l") && this.lamp == 1){ userAction = IR5.getString("\nYou walk up to the lamp. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayLampActions(); found = true; } for(int i = 0; i < lampActions.length; i++){ if(userAction.equals(lampActions[i])){ if(lampActions[i].equals("examine")){ System.out.println("\nIt's a pony shaped lamp!"); found = true; }else if(lampActions[i].equals("punch")){ System.out.println("\nYou're scared to break something that seems somewhat valuable."); System.out.println("You wouldn't want any bad karma coming your way!"); found = true; }else if(lampActions[i].equals("turn on")){ if(this.lampOn){ System.out.println("\nThis lamp is already turned on!"); found = true; }else if(!this.lampOn){ System.out.println("\nYou turn on the lamp!"); found = true; this.lampOn = true; } }else if(lampActions[i].equals("turn off")){ if(this.lampOn){ System.out.println("\nYou turn the lamp off!"); this.lampOn = false; found = true; }else if(!this.lampOn){ System.out.println("\nThis lamp is already off!"); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("c")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to w") && this.window == 1 && this.getRoomID() == 2){ userAction = IR5.getString("\nYou walk up to the window. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("c")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayWindowActions(); found = true; } for(int i = 0; i < windowActions.length; i++){ if(userAction.equals(windowActions[i])){ if(windowActions[i].equals("examine")){ System.out.println("\nIt's a window on the north side of the room. It looks like it could be opened or closed."); found = true; }else if(windowActions[i].equals("open")){ if(this.windowOpen){ System.out.println("\nThis window is already open.."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou open the window!"); this.windowOpen = true; found = true; } }else if(windowActions[i].equals("close")){ if(this.windowOpen){ System.out.println("\nYou close the window."); this.windowOpen = false; found = true; }else if(!this.windowOpen){ System.out.println("\nThis window is already closed."); found = true; } }else if(windowActions[i].equals("jump out")){ if(this.windowOpen){ System.out.println("\nYou decide to jump out the window.."); System.out.println("As you are jumping out, your foot gets tripped up on the window ceil."); System.out.println("You fall two stories landing on your head causing instant death..."); Menus.displayGameOver(player); center = true; found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't jump out of a closed window!"); found = true; } }else if(windowActions[i].equals("look out")){ if(this.windowOpen){ System.out.println("\nYou look outside the window and search all around."); System.out.println("You see nothing in the distance."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't see much through this closed window."); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to w") && this.window == 1 && this.getRoomID() == 5){ userAction = IR5.getString("\nYou walk up to the window. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayWindowActions(); found = true; } for(int i = 0; i < windowActions.length; i++){ if(userAction.equals(windowActions[i])){ if(windowActions[i].equals("examine")){ System.out.println("\nIt's a window on the west side of the room. It looks like it could be opened or closed."); found = true; }else if(windowActions[i].equals("open")){ if(this.windowOpen){ System.out.println("\nThis window is already open.."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou open the window!"); this.windowOpen = true; found = true; } }else if(windowActions[i].equals("close")){ if(this.windowOpen){ System.out.println("\nYou shut the window."); this.windowOpen = false; found = true; }else if(!this.windowOpen){ System.out.println("\nThis window is already closed!"); found = true; } }else if(windowActions[i].equals("jump out")){ if(windowOpen && !isScouted){ System.out.println("\nYou get ready to jump out the window.. you take a few steps back.." ); System.out.println("As you run towards the window you hear noises down below.."); System.out.println("You stop at the window and look down.."); System.out.println("You see a stable that is loaded with what seems to be demonic ponies.."); System.out.println("\nMaybe jumping out isn't the best idea.."); found = true; }else if(this.windowOpen && this.isScouted){ System.out.println("\nWhy would you want to jump out this window knowing what's out there.."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't jump out of a closed window!"); found = true; } }else if(windowActions[i].equals("look out")){ if(this.windowOpen){ System.out.println("\nYou look outside the window and search all around."); System.out.println("You see a stable filled with demonic ponies.."); this.isScouted = true; found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't see much through this closed window."); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to s") && this.statue == 1 && this.getRoomID() == 5){ userAction = IR5.getString("\nYou walk up to the statue. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayStatueActions(); found = true; } for(int i = 0; i < statueActions.length; i++){ if(userAction.equals(statueActions[i])){ if(statueActions[i].equals("examine")){ System.out.println("\nIt's a statue made of gold that resembles you."); System.out.println("\nThat's not spookey at all..."); found = true; }else if(statueActions[i].equals("punch")){ System.out.println("\nYou must really hate yourself.."); System.out.println("You punch the statue!"); System.out.println("I guess punching solid gold doesn't feel too good!"); System.out.println("\nYou lose a bit of healh in this process.."); player.decreaseHp(5); found = true; }else if(statueActions[i].equals("kick")){ System.out.println("\nYou kick the solid gold statue.."); System.out.println("You must really hate yourself."); found = true; }else if(statueActions[i].equals("imitate")){ System.out.println("\nYou make a pose similar to the statue that looks like you!"); System.out.println("The only difference is this statue's worth more than your bank account."); found = true; }else if(statueActions[i].equals("smell")){ System.out.println("\nThis statue smells like pure gold and something else that's familiar.."); System.out.println("....."); System.out.println("You realize it smells sorta like you."); found = true; } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to c") && this.closet == 1){ userAction = IR5.getString("\nYou walk up to the closet. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayClosetActions(); found = true; } for(int i = 0; i < closetActions.length; i++){ if(userAction.equals(closetActions[i])){ if(closetActions[i].equals("examine")){ System.out.println("\nIt's a closet.. probably used for storage."); found = true; }else if(closetActions[i].equals("open")){ if(!this.closetFightComplete && !this.closetOpen){ this.closetFight(player); if(player.getHp() <= 0){ Menus.displayGameOver(player); center = true; break; } this.closetOpen = true; this.closetFightComplete = true; found = true; }else if(this.closetFightComplete && this.closetOpen){ System.out.println("\nThe closet door is already open."); System.out.println("You should probably shut so you don't have to smell that dead carcass later!"); found = true; }else if(!this.closetOpen && this.closetFightComplete){ System.out.println("\nYou re-open the closet door and see the demon ponies dead carcass!"); this.closetOpen = true; found = true; } }else if(closetActions[i].equals("close")){ if(this.closetOpen){ System.out.println("\nYou shut the closet door, leaving the carcass of the dead pony in there!"); this.closetOpen = false; found = true; }else if(!this.closetOpen){ System.out.println("\nThe closet door is already closed!"); found = true; } }else if(closetActions[i].equals("listen")){ if(!this.closetFightComplete && !this.closetOpen){ System.out.println("\nYou put your ear next to the door, is sounds like something on the other side is breathing."); found = true; }else if(this.closetFightComplete && !this.closetOpen){ System.out.println("\nYou put your ear next to the door and hear nothing.."); System.out.println("That carcass in there is silently rotting away."); found = true; }else if (this.closetOpen){ System.out.println("\nThe closet door is open.. why listen if you can look inside!?"); found = true; } }else if(closetActions[i].equals("knock")){ if(!this.closetFightComplete && !this.closetOpen){ System.out.println("\nYou knock on the door.."); System.out.println("Right after you hear something ram into the door!"); found = true; }else if(this.closetFightComplete && !this.closetOpen){ System.out.println("\nYou knock on the door.."); System.out.println("But you hear nothing.."); found = true; }else if (this.closetOpen){ System.out.println("\nThe closet door is open.. you cannot knock on it.."); found = true; } }else if(closetActions[i].equals("look inside")){ if(this.closetOpen){ System.out.println("\nYou look inside the closet but all you see is the dead carcass of the demonic pony you slayed.."); found = true; }else if (!this.closetOpen){ System.out.println("\nThe door is closed, there is no way for you too look inside unless it's open."); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to w") && this.window == 1 && this.getRoomID() == 6){ userAction = IR5.getString("\nYou walk up to the window. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayWindowActions(); found = true; } for(int i = 0; i < windowActions.length; i++){ if(userAction.equals(windowActions[i])){ if(windowActions[i].equals("examine")){ System.out.println("\nIt's a window on the east side of the room. It looks like it could be opened or closed."); found = true; }else if(windowActions[i].equals("open")){ if(this.windowOpen){ System.out.println("\nThis window is already open.."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou open the window!"); this.windowOpen = true; found = true; } }else if(windowActions[i].equals("close")){ if(this.windowOpen){ System.out.println("\nYou shut the window."); this.windowOpen = false; found = true; }else if(!this.windowOpen){ System.out.println("\nThis window is already closed!"); found = true; } }else if(windowActions[i].equals("jump out")){ if(this.windowOpen){ System.out.println("\nI don't think jumping out is a good idea.."); System.out.println("Maybe you should just look out of it."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't jump out of a closed window!"); found = true; } }else if(windowActions[i].equals("look out")){ if(this.windowOpen){ System.out.println("\nYou look outside the window and search all around."); System.out.println("You look straight down and see a stable of demonic ponies."); found = true; }else if(!this.windowOpen){ System.out.println("\nYou can't see much through this closed window."); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to a") && this.atticPanel == 1){ userAction = IR5.getString("\nYou walk under the attic panel. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayPanelActions(); found = true; } for(int i = 0; i < panelActions.length; i++){ if(userAction.equals(panelActions[i])){ if(panelActions[i].equals("examine")){ System.out.println("\nIt's an attic panel.. who knows what's inside.."); found = true; }else if(panelActions[i].equals("open")){ if(!this.panelFightComplete && !this.panelOpen){ this.panelFight(player); if(player.getHp() <= 0){ Menus.displayGameOver(player); center = true; break; } this.panelOpen = true; this.panelFightComplete = true; found = true; }else if(this.panelFightComplete && this.panelOpen){ System.out.println("\nThe attic panel is already open."); found = true; }else if(!this.panelOpen && this.panelFightComplete){ System.out.println("\nYou re-open the attic panel to find a bunch of junk.."); this.panelOpen = true; found = true; } }else if(panelActions[i].equals("close")){ if(this.panelOpen){ System.out.println("\nYou shut the attic panel."); this.panelOpen = false; found = true; }else if(!this.panelOpen){ System.out.println("\nThe attic pannel is already shut!"); found = true; } }else if(panelActions[i].equals("look inside")){ if(this.panelOpen){ System.out.println("\nYou look inside the attic but all you see is junk.."); found = true; }else if (!this.panelOpen){ System.out.println("\nThe panel is shut, there is no way for you too look inside unless it's open."); found = true; } } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } if(keyword.startsWith("walk to s") && this.statue == 1 && this.getRoomID() == 10){ if(!this.finalFightComplete){ this.finalFight(player); if(player.getHp() <= 0){ Menus.displayGameOver(player); }else if(player.getHp() > 0){ this.finalFightComplete = true; } }else if(this.finalFightComplete){ userAction = IR5.getString("\nYou walk up to the statue. Choose an action.(Help for list of commands)").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } while(!center){ boolean found = false; if(userAction.startsWith("hel")){ displayStatueActions(); found = true; } for(int i = 0; i < statueActions.length; i++){ if(userAction.equals(statueActions[i])){ if(statueActions[i].equals("examine")){ System.out.println("\nThis was the statue that came to life and attacked you.."); System.out.println("Luckily you killed it."); found = true; }else if(statueActions[i].equals("punch")){ System.out.println("\nYou punch the motionless object.."); found = true; }else if(statueActions[i].equals("kick")){ System.out.println("\nYou kick the motionless object.."); }else if(statueActions[i].equals("imitate")){ System.out.println("\nYou lay on the ground and play dead imitating what you killed."); }else if(statueActions[i].equals("smell")){ System.out.println("\nIt really doesn't smell like much.. yet."); } } } if(!found){ System.err.println("\nSorry this command cannot be used here!"); } userAction = IR5.getString("\nChoose next action.").toLowerCase().trim(); if(userAction.startsWith("cen")){ center = true; } } System.out.println("\nYou return to the center of the room."); } } if(keyword.startsWith("no") || keyword.startsWith("so") || keyword.startsWith("ea") || keyword.startsWith("we")){ moveRoom(player, keyword); } if((keyword.startsWith("no") || keyword.startsWith("so") || keyword.startsWith("ea") || keyword.startsWith("we")) && this.getRoomID() == 10){ finalRoomMove(player, keyword); } } public void displayRoomHelp(){ System.out.println("\n---------" + this.getRoomName() + "---------"); System.out.println("\n" + this.getDescription()); System.out.println("Here are a few words you can enter to do things around the room.."); System.out.println(""); for(int i = 1; i < this.hallwayKeywords.size() + 1; i++){ System.out.println("- " + this.hallwayKeywords.get(i - 1)); } System.out.println("\n-------------------------------"); } public void displayLampActions(){ System.out.println("\nHere are some commands you can use on the lamp!"); System.out.println("**********************************************************"); for(int i = 0; i < lampActions.length; i++){ System.out.println("- " + lampActions[i]); } System.out.println("- center"); System.out.println("**********************************************************"); } public void displayWindowActions(){ System.out.println("\nHere are some commands you can use on the window!"); System.out.println("**********************************************************"); for(int i = 0; i < windowActions.length; i++){ System.out.println("- " + windowActions[i]); } System.out.println("- center"); System.out.println("**********************************************************"); } public void displayPanelActions(){ System.out.println("\nHere are some commands you can use on the attic panel!"); System.out.println("**********************************************************"); for(int i = 0; i < panelActions.length; i++){ System.out.println("- " + panelActions[i]); } System.out.println("- center"); System.out.println("**********************************************************"); } public void displayClosetActions(){ System.out.println("\nHere are some commands you can use on the closet!"); System.out.println("**********************************************************"); for(int i = 0; i < closetActions.length; i++){ System.out.println("- " + closetActions[i]); } System.out.println("- center"); System.out.println("**********************************************************"); } public void displayStatueActions(){ System.out.println("\nHere are some commands you can use on the statue!"); System.out.println("**********************************************************"); for(int i = 0; i < statueActions.length; i++){ System.out.println("- " + statueActions[i]); } System.out.println("- center"); System.out.println("**********************************************************"); } public void closetFight(Player player){ int ponyHealth = 25; String userChoice; int ponyDamage; int userDamage; System.out.println("\nAs you open up the door you're attacked by a demonic pony.."); while(ponyHealth > 0 && player.getHp() > 0){ System.out.println("\n**********Choose Attack*********"); System.out.println("* - Punch *"); System.out.println("* - Kick *"); if(player.getKnife() == 1){ System.out.println("* - Stab(knife) *"); } System.out.println("********************************"); userChoice = IR5.getString("\n").toLowerCase().trim(); if(userChoice.startsWith("pu")){ userDamage = IR5.getRandomNumber(3, 5); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your hands to punch it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(10, 15); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("ki")){ userDamage = IR5.getRandomNumber(4, 6); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your feet to kick it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(5, 10); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 1){ userDamage = IR5.getRandomNumber(12, 15); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to stab it with the knife you picked up!, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(5, 10); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 0){ System.out.println("\nNice try, you don't have a nice you dirty experienced player."); }else{ System.err.println("\nSorry the command " + userChoice + " doesn't work."); } } if(ponyHealth <= 0){ System.out.println("\nVery nice job, you have killed the pony."); System.out.println("You stash the dead carcass into the closet that it came from."); player.addToPoints(10); } } public void panelFight(Player player){ int ponyHealth = 25; String userChoice; int ponyDamage; int userDamage; System.out.println("\nAs you open up the attic panel a demonic pony jumps out and attacks you!"); while(ponyHealth > 0 && player.getHp() > 0){ System.out.println("\n**********Choose Attack*********"); System.out.println("* - Punch *"); System.out.println("* - Kick *"); if(player.getKnife() == 1){ System.out.println("* - Stab(knife) *"); } System.out.println("********************************"); userChoice = IR5.getString("\n").toLowerCase().trim(); if(userChoice.startsWith("pu")){ userDamage = IR5.getRandomNumber(3, 5); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your hands to punch it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(10, 15); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("ki")){ userDamage = IR5.getRandomNumber(4, 6); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your feet to kick it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(10, 15); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 1){ userDamage = IR5.getRandomNumber(12, 15); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to stab it with the knife you picked up!, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(10, 15); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 0){ System.out.println("\nNice try, you don't have a nice you dirty experienced player."); }else{ System.out.println("\nSorry the command " + userChoice + " doesn't work here."); } } if(ponyHealth <= 0){ System.out.println("\nVery nice job, you have killed the pony."); System.out.println("You leave the dead carcass where you killed it, you better get out of this place before it begins to smell!"); player.addToPoints(10); } } public void finalFight(Player player){ int ponyHealth = 50; String userChoice; int ponyDamage; int userDamage; System.out.println("\nYou approach the statue.. All of the sudden it comes to life and and attacks!"); System.out.println("It's a demonic pony but this one has 3 horns and is slightly bigger!"); while(ponyHealth > 0 && player.getHp() > 0){ System.out.println("\n**********Choose Attack*********"); System.out.println("* - Punch *"); System.out.println("* - Kick *"); if(player.getKnife() == 1){ System.out.println("* - Stab(knife) *"); } System.out.println("********************************"); userChoice = IR5.getString("\n").toLowerCase().trim(); if(userChoice.startsWith("pu")){ userDamage = IR5.getRandomNumber(3, 5); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your hands to punch it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(15, 20); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("ki")){ userDamage = IR5.getRandomNumber(3, 5); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to use your feet to kick it, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(15, 20); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 1){ userDamage = IR5.getRandomNumber(12, 15); ponyHealth -= userDamage; if(ponyHealth < 0){ ponyHealth = 0; } System.out.println("\nYou decide to stab it with the knife you picked up!, you deal " + userDamage + " damage to the pony."); System.out.println("The pony has " + ponyHealth + " hp remaining."); if(ponyHealth > 0){ ponyDamage = IR5.getRandomNumber(15, 20); player.decreaseHp(ponyDamage); System.out.println("\nThe pony attacks back buckshotting you with it's hind legs!"); System.out.println("You take " + ponyDamage + " damage."); System.out.println("\nYou have " + player.getHp() + " hp remaining."); } }else if(userChoice.startsWith("st") && player.getKnife() == 0){ System.out.println("\nNice try, you don't have a nice you dirty experienced player."); }else{ System.out.println("\nSorry the command " + userChoice + " doesn't work here."); } } if(ponyHealth <= 0){ System.out.println("\nVery nice job, you have killed the pony."); System.out.println("You leave the dead carcass where you killed it, you better get out of this place before worse things happen!"); player.addToPoints(25); } } public void finalRoomMove(Player player, String keyword) throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException { if(keyword.startsWith("no") && this.getNorthDoor() != 0){ if(player.getKey() == 1 && getFinalFight()){ player.addToPoints(player.getHp()); player.addToPoints(100); Menus.displayGameWon(player); player.setWinGame(true); player.setHp(0); FileIo.writeFile(); }else if(player.getKey() == 0){ System.err.println("\nSorry this door is locked, you need to find the key."); }else if(!getFinalFight()){ System.err.println("\nMaybe you should check out the statue in this room!"); } } if(keyword.startsWith("so") && this.getSouthDoor() != 0){ player.setLocation(this.getSouthDoor()); }else if(keyword.startsWith("so") && this.getSouthDoor() == 0){ System.err.println("\nYou cannot go this direction."); } if(keyword.startsWith("ea") && this.getEastDoor() != 0){ player.setLocation(this.getEastDoor()); }else if(keyword.startsWith("ea") && this.getEastDoor() == 0){ System.err.println("\nYou cannot go this direction."); } if(keyword.startsWith("we") && this.getWestDoor() != 0){ player.setLocation(this.getWestDoor()); }else if(keyword.startsWith("we") && this.getWestDoor() == 0){ System.err.println("\nYou cannot go this direction."); } } }<file_sep>import java.io.Serializable; import java.io.*; import java.util.*; public class Menus implements Serializable { public static void displayStartGame(Player player){ System.out.println("************************************************************"); System.out.println("* Welcome " + player.getUsername() + " to Brony Adventures. *"); System.out.println("* You wake up from a deep sleep in an abandoned house. *"); System.out.println("* This house is home to 3 dangerous demonic ponies. *"); System.out.println("* The goal is to find the key... *"); System.out.println("* Get to the hallway on the north side of the building.. *"); System.out.println("* And escape through the front door safely. *"); System.out.println("* It seems like you are in a room with a bed, a dresser, *"); System.out.println("* And a door to the north.. *"); System.out.println("* You can use the command \"help\" to get started.. *"); System.out.println("************************************************************"); } public static void displayGameWon(Player player){ System.out.println("****************************************************************"); System.out.printf("* Congratulations, %8s" , player.getUsername() + ". You have escaped! *" ); System.out.println(); System.out.println("* Your score of " + player.getHighScore() + " points will be recorded to the highscores.*"); System.out.println("* I hope you enjoyed playing our game! *"); System.out.println("****************************************************************"); } public static void displayHelp() { System.out.println("********************************************************"); System.out.println("* Command | Action *"); System.out.println("********************************************************"); System.out.println("* Walk to -object- | Moves to object *"); System.out.println("* type a direction | Changes rooms in direction. *"); System.out.println("* Center | Return to center of room. *"); System.out.println("* Search | Examines Room *"); System.out.println("* Scream | Player Screams *"); System.out.println("* Eat Food | Eats food if available. *"); System.out.println("* Check Food | Checks amt of food *"); System.out.println("* Health | Displays HP *"); System.out.println("* Points | Displays points *"); System.out.println("* Highscores | Displays highscores *"); System.out.println("* Exit | Saves and Quits Game *"); System.out.println("********************************************************"); } public static void displayGameOver(Player player){ System.out.println("----------------------------------------------"); System.out.println("It seems you have died."); System.err.println("You collected a total of " + player.getHighScore() + " points this game."); System.err.println("Your stats have been placed on the highscores."); System.out.println("----------------------------------------------"); } @SuppressWarnings("unchecked") public static void sortHighscores(){ ArrayList<PlayBronyGame> gameList = FileIo.getGameList(); Collections.sort(gameList, new Comparator<PlayBronyGame>() { public int compare(PlayBronyGame p1, PlayBronyGame p2) { return Integer.valueOf(p2.getPlayerHighscore()) .compareTo(p1.getPlayerHighscore()); } }); if(gameList.size() <= 1){ System.out.println("\nThere are no highscores to display!"); }else{ System.out.println("-------------* Brony Adventures Highscores *-------------"); System.out.println(" Username | Points"); System.out.println("---------------------------------------------------------"); for(int i = 0 ; i < gameList.size(); i++) { displayNameAndScore((i + 1) ,gameList.get(i).getPlayerName(), gameList.get(i).getPlayerHighscore()); } System.out.println("---------------------------------------------------------"); } } public static void displayNameAndScore(int inc, String username, int highscore){ System.out.printf(" " + inc + ". %-12s" , username); System.out.print(" " + highscore); System.out.println(); } }<file_sep>import java.io.*; import java.util.*; public class Room implements Serializable { private int roomID; private String roomName; private String roomDescription; private String roomUniques; private int northDoor; private int southDoor; private int eastDoor; private int westDoor; private ArrayList<String> keywords = new ArrayList<String>(); Room(){ roomID = 0; roomName = ""; roomDescription = ""; roomUniques = ""; northDoor = 0; southDoor = 0; eastDoor = 0; westDoor = 0; } Room(int roomID, String roomName, String roomDescription, String roomUniques, int northDoor, int southDoor, int eastDoor, int westDoor){ this.roomID = roomID; this.roomName = roomName; this.roomDescription = roomDescription; this.roomUniques = roomUniques; this.northDoor = northDoor; this.southDoor = southDoor; this.eastDoor = eastDoor; this.westDoor = westDoor; } public void setRoomID(int roomID){ this.roomID = roomID; } public void setRoomName(String roomName){ this.roomName = roomName; } public void setDescription(String roomDescription){ this.roomDescription = roomDescription; } public void setRoomUniques(String roomUniques){ this.roomUniques = roomUniques; } public void setNorthDoor(int northDoor){ this.northDoor = northDoor; } public void setSouthDoor(int southDoor){ this.southDoor = southDoor; } public void setEastDoor(int eastDoor){ this.eastDoor = eastDoor; } public void setWestDoor(int westDoor){ this.westDoor = westDoor; } public int getRoomID(){ return this.roomID; } public String getRoomName(){ return this.roomName; } public String getDescription(){ return this.roomDescription; } public String getRoomUniques(){ return this.roomUniques; } public int getNorthDoor(){ return this.northDoor; } public int getSouthDoor(){ return this.southDoor; } public int getEastDoor(){ return this.eastDoor; } public int getWestDoor(){ return this.westDoor; } public void moveRoom(Player player, String keyword){ if(keyword.startsWith("no") && this.northDoor != 0 && this.roomID != 10){ player.setLocation(this.northDoor); }else if(keyword.startsWith("no") && this.northDoor == 0){ System.err.println("\nYou cannot go this direction."); } if(keyword.startsWith("so") && this.southDoor != 0){ player.setLocation(this.southDoor); }else if(keyword.startsWith("so") && this.southDoor == 0){ System.err.println("\nYou cannot go this direction."); } if(keyword.startsWith("ea") && this.eastDoor != 0){ player.setLocation(this.eastDoor); }else if(keyword.startsWith("ea") && this.eastDoor == 0){ System.err.println("\nYou cannot go this direction."); } if(keyword.startsWith("we") && this.westDoor != 0){ player.setLocation(this.westDoor); }else if(keyword.startsWith("we") && this.westDoor == 0){ System.err.println("\nYou cannot go this direction."); } } }<file_sep> import java.util.*; import java.io.*; /* ******************************** * Programmers : Sean and Andrew * * CIS 131 : Brony Adventures * * Final Project * **********************************/ class BronyAdventures { public static Player player = new Player(); public final static Scanner scanner = new Scanner(System.in); public static PlayBronyGame game; public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException { while(true){ readyPlayer(); game.playGame(); } } /******************* * Start: Create or get user information *********************/ public static void readyPlayer() throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException { FileIo.readFile(); boolean flag = false; introMsg(); while(!flag) { loggingUserMsg(); int userOption = IR5.getInteger("Select option"); if(userOption == 1) { boolean isExit = false; boolean isNewUser = false; while(!isNewUser && !isExit) { isNewUser = createUser(); if(isNewUser) { flag = true; Menus.displayStartGame(player); } else { String tryAgain = getString("Press any key to try again (type exit to go back)"); if(tryAgain.equals("exit")) { isExit = true; }; } } } else if(userOption == 2) { boolean isExit = false; boolean doesUserExist = false; while(!doesUserExist && !isExit) { doesUserExist = signinUser(); if(doesUserExist) flag = true; else { String tryAgain = getString("Press any key to try again (type exit to go back)"); if(tryAgain.equals("exit")) { isExit = true;}; } } } else if(userOption == 3){ Menus.sortHighscores(); } else if(userOption == 4){ System.exit(-1); } } } public static boolean createUser() throws FileNotFoundException, IOException, ClassNotFoundException, InterruptedException { /** * Initial setup game */ Bedroom guestBedroom = new Bedroom(1, "Guest Bedroom", "This is the guest bedroom at the back of the house.", "\nYou see a door to the north, a dresser and a bed in this room.", 2, 0, 0, 0, 1, 1, 0, 0); Hallway hallway1 = new Hallway(2, "Southern Hallway", "This is the hallway right outside the guest bedroom.", "\nYou see doors to the east and to the west, a lamp, and a window.", 0, 0, 4, 3, 1, 1, 0, 0, 0); Bathroom masterBathroom = new Bathroom(3, "Master Bathroom", "This is the bathroom closest to the master bedroom.", "\nYou see a door to the east and to the north, you also notice a working shower and toiet.", 5, 0, 2, 0, 1, 1, 0, 0, 0, 1); Kitchen kitchen1 = new Kitchen(4, "South-East Kitchen", "This is the kitchen at the back right corner of the house.", "\nYou see doors to the west and to the north, you also notice a knife and a running fridge.", 6, 0, 0, 2, 1, 1, 0, 0); Hallway hallway2 = new Hallway(5, "Western Hallway", "This hallway is to the west of a bedroom.", "\nYou see doors to the south, east, and west. You also see a statue, another window, and a closet.", 8, 3, 7, 0, 0, 1, 1, 0, 1); Hallway hallway3 = new Hallway(6, "Eastern Hallway", "This hallway is to the east of a bedroom.", "\nYou see doors to the south, west, and north. You also see a window, an attic panel, and a statue.", 9, 4, 0, 7, 0, 1, 0, 1, 0); Bedroom masterBedroom = new Bedroom(7, "Master Bedroom", "This is the master bedroom that hovers over the courtyard.", "\nYou see doors to the east and west, a mirror, a bed, and a dresser in here.", 0, 0, 6, 5, 1, 1, 1, 1); Kitchen kitchen2 = new Kitchen(8, "North-West Kitchen", "This kitchen is in the north-west side of the house.", "\nYou see doors to the east and the south, you see a fridge, a useable sink, and a chair.", 0, 5, 10, 0, 0, 1, 1, 1); Bathroom bathroom2 = new Bathroom(9, "Bathroom", "This bathroom is on the north-east side of the house.", "\nYou see doors to the south and to the west, you see a toilet, no shower, a plunger, and some cabinets with a mirror above.", 0, 6, 0, 10, 1, 0, 1, 0, 1, 1); Hallway hallway4 = new Hallway(10, "Northern Hallway", "This hallway is the most northern hallway.", "\nyou see doors to the north, east, and west, and a statue.", 11, 0, 9, 8, 0, 0, 0, 0, 1); // Adds keywords to intialize an action in guestBedroom. guestBedroom.addKeyword("Walk to Dresser"); guestBedroom.addKeyword("Walk to Bed"); guestBedroom.addKeyword("North"); // Adds keywords to intialize an action in hallway1. hallway1.addKeyword("Walk to Lamp"); hallway1.addKeyword("Walk to Window"); hallway1.addKeyword("West"); hallway1.addKeyword("East"); // Adds keywords to intialize an action in masterBathroom. masterBathroom.addKeyword("Walk to Toilet"); masterBathroom.addKeyword("Walk to Shower"); masterBathroom.addKeyword("Walk to Sink"); masterBathroom.addKeyword("East"); masterBathroom.addKeyword("North"); // Adds keywords to intialize an action in kitchen1. kitchen1.addKeyword("Walk to Fridge"); kitchen1.addKeyword("Walk to Knife"); kitchen1.addKeyword("West"); kitchen1.addKeyword("North"); // Adds keywords to intialize an action in hallway2. hallway2.addKeyword("Walk to Window"); hallway2.addKeyword("Walk to Statue"); hallway2.addKeyword("Walk to Closet"); hallway2.addKeyword("North"); hallway2.addKeyword("East"); hallway2.addKeyword("South"); // Adds keywords to intialize an action in hallway3. hallway3.addKeyword("Walk to Window"); hallway3.addKeyword("Walk to Attic Panel"); hallway3.addKeyword("North"); hallway3.addKeyword("West"); hallway3.addKeyword("South"); // Adds keywords to initialize list of actions for the master bedroom. masterBedroom.addKeyword("Walk to Dresser"); masterBedroom.addKeyword("Walk to Bed"); masterBedroom.addKeyword("Walk to Mirror"); masterBedroom.addKeyword("East"); masterBedroom.addKeyword("West"); // Adds keywords to initialize list of actions for the north-west kitchen. kitchen2.addKeyword("Walk to Fridge"); kitchen2.addKeyword("Walk to Sink"); kitchen2.addKeyword("Walk to Chair"); kitchen2.addKeyword("East"); kitchen2.addKeyword("South"); // Adds keywords to initialize list of actions for the 2nd bathroom. bathroom2.addKeyword("Walk to Toilet"); bathroom2.addKeyword("Walk to Plunger"); bathroom2.addKeyword("Walk to Sink"); bathroom2.addKeyword("Walk to Mirror"); bathroom2.addKeyword("South"); bathroom2.addKeyword("West"); // Adds keywords to initialize list of actions for northern hallway. hallway4.addKeyword("Walk to Statue"); hallway4.addKeyword("North"); hallway4.addKeyword("East"); hallway4.addKeyword("West"); /** * Creating user */ String username = getString("Create username"); String password = getString("Create password"); Player newPlayer = new Player(username, password, 0, 100, 0, 1); PlayBronyGame newGame = new PlayBronyGame(newPlayer, guestBedroom, hallway1, masterBathroom, kitchen1, hallway2, hallway3, masterBedroom, kitchen2, bathroom2, hallway4); boolean isNewPlayer = FileIo.addNewPlayer(newGame); if (isNewPlayer) { System.out.println("Creating new user"); game = newGame; FileIo.writeFile(); // System.out.println("Welcome " + username + " to Brony Adventures!"); return true; } else { System.out.println("There is already a user with that username"); return false; } } public static boolean signinUser() throws IOException, InterruptedException { String username = getString("Enter username"); String password = getString("Enter <PASSWORD>"); PlayBronyGame isPlayerExist = FileIo.getGame(username, password); if (isPlayerExist != null) { System.out.println("Welcome back " + username + "!"); game = isPlayerExist; return true; } else { System.out.println("User does not exist"); return false; } } public static void loggingUserMsg() { System.out.println("*************************"); System.out.println("* 1. New Game *"); System.out.println("* 2. Existing Game *"); System.out.println("* 3. View Highscores *"); System.out.println("* 4. Quit Game *"); System.out.println("*************************"); } /******************* End: Create or get user information *********************/ public static String getString(String msg) { String answer = ""; System.out.print(msg + ": "); try { answer = scanner.nextLine(); } catch (Exception e) { System.err.println("Error reading input from user. Ending program."); System.exit(-1); } while (answer.replace(" ", "").equals("")) { System.err.println("Error: Missing input."); try { System.out.println(msg); answer = scanner.nextLine(); } catch (Exception e) { System.err.println("Error reading input from user. Ending program."); System.exit(-1); } } return answer; } public static void introMsg() { System.out.println(""); System.out.println("88888888ba"); System.out.println("88 \"8b"); System.out.println("88 ,8P"); System.out.println("88aaaaaa8P' 8b,dPPYba, ,adPPYba, 8b,dPPYba, 8b d8"); System.out.println("88\"\"\"\"\"\"8b, 88P' \"Y8 a8\" \"8a 88P' `\"8a `8b d8'"); System.out.println("88 `8b 88 8b d8 88 88 `8b d8'"); System.out.println("88 a8P 88 \"8a, ,a8\" 88 88 `8b,d8'"); System.out.println("8888888db\" 88 88YbbdP\"' 88 88 Y88'"); System.out.println(" d88b 88 d8' ,d"); System.out.println(" d8'`8b 88 d8' 88"); System.out.println(" d8' `8b ,adPPYb,88 8b d8 ,adPPYba, 8b,dPPYba, MM88MMM 88 88 8b,dPPYba, ,adPPYba, ,adPPYba,"); System.out.println(" d8YaaaaY8b a8\" `Y88 `8b d8' a8P_____88 88P' `\"8a 88 88 88 88P' \"Y8 a8P_____88 I8[ \"\""); System.out.println(" d8\"\"\"\"\"\"\"\"8b 8b 88 `8b d8' 8PP\"\"\"\"\"\"\" 88 88 88 88 88 88 8PP\"\"\"\"\"\"\" `\"Y8ba,"); System.out.println(" d8' `8b \"8a, ,d88 `8b,d8' \"8b, ,aa 88 88 88, \"8a, ,a88 88 \"8b, ,aa aa ]8I"); System.out.println("d8' `8b `\"8bbdP\"Y8 \"8\" `\"Ybbd8\"' 88 88 \"Y888 `\"YbbdP'Y8 88 `\"Ybbd8\"' `\"YbbdP\"'"); System.out.println(""); } }
06bff4c5e35182839ed7c4d8394ae8f8d12666d9
[ "Java" ]
4
Java
Andyt-Nguyen/Brony-Adventures
6b533ade993c37b5585d838eb6039cd3783184d0
193c32ccf5e30965d52d44a45f66fee55cbd2a03
refs/heads/master
<repo_name>vvakame/gopan<file_sep>/extruder.go package gopan import ( "bytes" "errors" "fmt" "reflect" "strings" "sync" "time" "cloud.google.com/go/civil" "cloud.google.com/go/spanner" ) var typeMap = make(map[reflect.Type]*extruder) var mu sync.Mutex type extruder struct { Type reflect.Type Fields []*extruderField PKFields []*extruderField } type extruderField struct { ColumnIndex int ReflectIndexes []int Name string ColumnType string PK bool Array bool Length int NotNull bool } func getExtruder(t reflect.Type) (*extruder, error) { if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() != reflect.Struct { return nil, errors.New("src is not struct") } mu.Lock() defer mu.Unlock() ex, ok := typeMap[t] if ok { return ex, nil } ex = &extruder{Type: t} typeMap[t] = ex var f func(t reflect.Type, refIndexes []int) error columnIdx := 0 f = func(t reflect.Type, refIndexes []int) error { for i := 0; i < t.NumField(); i++ { sf := t.Field(i) exported := sf.PkgPath == "" if !exported && !sf.Anonymous { continue } tag := sf.Tag.Get("spanner") if tag == "-" { continue } if sf.Anonymous { nextT := sf.Type if nextT.Kind() == reflect.Ptr { nextT = nextT.Elem() } nextRefIndexes := make([]int, 0, len(refIndexes)+1) nextRefIndexes = append(nextRefIndexes, refIndexes...) nextRefIndexes = append(nextRefIndexes, i) err := f(nextT, nextRefIndexes) if err != nil { return err } continue } exF := &extruderField{ColumnIndex: columnIdx, NotNull: true} ex.Fields = append(ex.Fields, exF) nextRefIndexes := make([]int, 0, len(refIndexes)+1) nextRefIndexes = append(nextRefIndexes, refIndexes...) nextRefIndexes = append(nextRefIndexes, i) exF.ReflectIndexes = nextRefIndexes columnIdx++ if tag != "" { exF.Name = tag } else { exF.Name = sf.Name } tag = sf.Tag.Get("gopan") if tag == "id" { exF.PK = true } t := sf.Type switch t.Kind() { case reflect.Array, reflect.Slice: exF.Array = true t = t.Elem() } switch t.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: fallthrough case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: exF.ColumnType = "INT64" case reflect.String: exF.ColumnType = "STRING" case reflect.Bool: exF.ColumnType = "BOOL" case reflect.Float32, reflect.Float64: exF.ColumnType = "FLOAT64" default: switch t { case reflect.TypeOf(spanner.NullString{}): exF.ColumnType = "STRING" exF.NotNull = false case reflect.TypeOf(spanner.NullInt64{}): exF.ColumnType = "INT64" exF.NotNull = false case reflect.TypeOf(spanner.NullFloat64{}): exF.ColumnType = "FLOAT64" exF.NotNull = false case reflect.TypeOf(spanner.NullBool{}): exF.ColumnType = "BOOL" exF.NotNull = false case reflect.TypeOf(spanner.NullTime{}): exF.ColumnType = "TIMESTAMP" exF.NotNull = false case reflect.TypeOf(spanner.NullDate{}): exF.ColumnType = "DATE" exF.NotNull = false case reflect.TypeOf([]byte{}): exF.ColumnType = "BYTES" case reflect.TypeOf(time.Time{}): exF.ColumnType = "TIMESTAMP" case reflect.TypeOf(civil.Date{}): exF.ColumnType = "DATE" default: return fmt.Errorf("unsupported type: %s", sf.Type) } } // TODO Length, NotNull } return nil } err := f(t, nil) if err != nil { return nil, err } for _, f := range ex.Fields { if !f.PK { continue } ex.PKFields = append(ex.PKFields, f) } return ex, nil } func (ex *extruder) Table() string { return ex.Type.Name() } func (ex *extruder) KeyError(v reflect.Value) (*Key, error) { var key spanner.Key for _, f := range ex.PKFields { key = append(key, f.Value(v).Interface()) } return &Key{Table: ex.Table(), Key: key}, nil } func (ex *extruder) Columns() []string { columns := make([]string, 0, len(ex.Fields)) for _, f := range ex.Fields { columns = append(columns, f.Name) } return columns } func (f *extruderField) Value(st reflect.Value) reflect.Value { if st.Kind() == reflect.Ptr { st = st.Elem() } v := st for _, idx := range f.ReflectIndexes { v = v.Field(idx) } return v } func (ex *extruder) DDLCreateTable() string { buf := bytes.NewBufferString("CREATE TABLE ") buf.WriteString(ex.Table()) buf.WriteString(" (\n") for _, f := range ex.Fields { buf.WriteString("\t") buf.WriteString(f.DDLColumn()) buf.WriteString(",\n") } buf.WriteString(") PRIMARY KEY (") var pkNames []string for _, f := range ex.PKFields { pkNames = append(pkNames, f.Name) } buf.WriteString(strings.Join(pkNames, ", ")) buf.WriteString(")") return buf.String() } func (f *extruderField) DDLColumn() string { buf := bytes.NewBufferString("") buf.WriteString(f.Name) buf.WriteString("\t") if f.Array { buf.WriteString("ARRAY<") } buf.WriteString(f.ColumnType) if f.Length != 0 { buf.WriteString("\t") buf.WriteString("(") buf.WriteString(fmt.Sprintf("%d", f.Length)) buf.WriteString(")") } else { switch f.ColumnType { case "STRING", "BYTES": buf.WriteString("\t") buf.WriteString("(MAX)") } } if f.Array { buf.WriteString(">") } if f.NotNull { buf.WriteString("\t") buf.WriteString("NOT NULL") } return buf.String() } <file_sep>/extruder_test.go package gopan import ( "reflect" "strings" "testing" "time" "cloud.google.com/go/spanner" "github.com/MakeNowJust/heredoc" ) type Sample1 struct { ID int64 `gopan:"id"` } func TestExtruder_Table(t *testing.T) { v := reflect.ValueOf(&Sample1{}).Elem() ex, err := getExtruder(v.Type()) if err != nil { t.Fatal(err) } if v := ex.Table(); v != "Sample1" { t.Error("unexpected", v) } } func TestExtruder_KeyError(t *testing.T) { v := reflect.ValueOf(&Sample1{ID: 7}).Elem() ex, err := getExtruder(v.Type()) if err != nil { t.Fatal(err) } key, err := ex.KeyError(v) if err != nil { t.Fatal(err) } if v := key.Table; v != ex.Table() { t.Error("unexpected", v) } if v := reflect.DeepEqual(key.Key, spanner.Key{int64(7)}); !v { t.Error("unexpected", v) } } type Outer struct { ID int64 `gopan:"id"` Name string Embed } type Embed struct { UpdatedAt time.Time CreatedAt time.Time } func TestExtruderField_Value(t *testing.T) { obj := &Outer{} v := reflect.ValueOf(obj).Elem() ex, err := getExtruder(v.Type()) if err != nil { t.Fatal(err) } if v := len(ex.Fields); v != 4 { t.Fatal("unexpected", v) } id := ex.Fields[0] idV := id.Value(v) idV.SetInt(10) name := ex.Fields[1] nameV := name.Value(v) nameV.SetString("Test") updatedAt := ex.Fields[2] updatedAtV := updatedAt.Value(v) now := time.Now() updatedAtV.Set(reflect.ValueOf(now)) createdAt := ex.Fields[3] createdAtV := createdAt.Value(v) createdAtV.Set(reflect.ValueOf(now.Add(10 * time.Minute))) if v := obj.ID; v != 10 { t.Fatal("unexpected", v) } if v := obj.Name; v != "Test" { t.Fatal("unexpected", v) } if v := obj.UpdatedAt; !v.Equal(now) { t.Fatal("unexpected", v) } if v := obj.CreatedAt; !v.Equal(now.Add(10 * time.Minute)) { t.Fatal("unexpected", v) } } func TestExtruder_Columns(t *testing.T) { v := reflect.ValueOf(&Sample1{}).Elem() ex, err := getExtruder(v.Type()) if err != nil { t.Fatal(err) } columns := ex.Columns() if v := len(columns); v != 1 { t.Fatal("unexpected", v) } if v := columns[0]; v != "ID" { t.Fatal("unexpected", v) } } func TestExtruder_DDLCreateTable(t *testing.T) { v := reflect.ValueOf(&Sample1{}).Elem() ex, err := getExtruder(v.Type()) if err != nil { t.Fatal(err) } ddl := ex.DDLCreateTable() expected := heredoc.Doc(` CREATE TABLE Sample1 ( ID INT64 NOT NULL, ) PRIMARY KEY (ID) `) if v := strings.TrimSpace(ddl); v != strings.TrimSpace(expected) { t.Fatal("unexpected", v) } } <file_sep>/README.md # Gopan Go library for Cloud Spanner https://godoc.org/cloud.google.com/go/spanner https://cloud.google.com/spanner/docs/reference/libraries > If you are using Google App Engine - Standard Environment, please access Cloud Spanner using the REST Interface, instead of the client libraries. BLOCKED! ヾ(๑╹◡╹)ノ" ## Future works * [ ] write document comment * [ ] flexible configurations * [ ] add transaction support * [ ] single transaction * [ ] read-only transaction * [ ] read-write transaction * [ ] BufferWrite support * [ ] add spanner.ErrCode support * [ ] add PropertyLoadSaver like feature support * [ ] add raw query support * [ ] add partial column mutations support * [ ] add partial * [ ] add DDL support * [ ] delete database * [ ] create table * [ ] delete table * [ ] add index * [ ] remove index * [ ] alter table * [ ] interleave * [ ] add read from index support * [ ] add PK by multi column support <file_sep>/value.go package gopan import ( "time" "cloud.google.com/go/civil" "cloud.google.com/go/spanner" ) func String(v string) spanner.NullString { return spanner.NullString{Valid: true, StringVal: v} } func Time(v time.Time) spanner.NullTime { if v.IsZero() { return spanner.NullTime{} } return spanner.NullTime{Valid: true, Time: v} } func Float64(v float64) spanner.NullFloat64 { return spanner.NullFloat64{Valid: true, Float64: v} } func Int64(v int64) spanner.NullInt64 { return spanner.NullInt64{Valid: true, Int64: v} } func Date(v civil.Date) spanner.NullDate { return spanner.NullDate{Valid: true, Date: v} } func Bool(v bool) spanner.NullBool { return spanner.NullBool{Valid: true, Bool: v} } <file_sep>/key.go package gopan import "cloud.google.com/go/spanner" // NOTE // spanner.Key does not have Table information. type Key struct { Table string spanner.Key } <file_sep>/usage_test.go package gopan import ( "fmt" "os" "reflect" "testing" "time" "cloud.google.com/go/spanner" "cloud.google.com/go/spanner/admin/database/apiv1" "golang.org/x/net/context" "google.golang.org/api/iterator" ) type Article struct { ID int64 `gopan:"id"` Title string Body string Authors []spanner.NullString CreatedAt time.Time UpdatedAt time.Time } func TestGopan_CreateDB(t *testing.T) { g, err := makeDefaultGopan(context.Background()) if err != nil { t.Fatal(err.Error()) } err = g.CreateDB(&Article{}) if err != nil { t.Fatal(err.Error()) } } func TestGopan_InsertMulti(t *testing.T) { // depends on result of TestGopan_CreateDB g, err := makeDefaultGopan(context.Background()) if err != nil { t.Fatal(err.Error()) } var arts []*Article for i := 1; i <= 100000; i++ { art := &Article{ ID: int64(i), Title: fmt.Sprintf("Title %d", i), Body: fmt.Sprintf("Body %d", i), Authors: []spanner.NullString{String("vvakame"), String("cat")}, CreatedAt: time.Now(), UpdatedAt: time.Now(), } arts = append(arts, art) if len(arts) == 2000 { _, err = g.InsertMulti(arts) if err != nil { t.Fatal(err.Error()) } arts = nil } } if len(arts) != 0 { _, err = g.InsertMulti(arts) if err != nil { t.Fatal(err.Error()) } } } func TestGopan_Get(t *testing.T) { g, err := makeDefaultGopan(context.Background()) if err != nil { t.Fatal(err.Error()) } { // Before key := g.Key(&Article{ID: 300}) err := g.Delete(key) if err != nil { t.Log(err) } } art := &Article{ ID: 300, Title: "Title TestGopan_GetMulti", Body: "Body TestGopan_GetMulti", Authors: []spanner.NullString{String("vvakame"), String("maya")}, CreatedAt: time.Now(), UpdatedAt: time.Now(), } _, err = g.Insert(art) if err != nil { t.Fatal(err) } { ex, err := getExtruder(reflect.TypeOf(Article{})) if err != nil { t.Fatal(err) } keySet := spanner.Keys(g.Key(art).Key) iter := g.Client.Single().Read(g.Context, ex.Table(), keySet, ex.Columns()) defer iter.Stop() for i := 0; ; i++ { row, err := iter.Next() if err == iterator.Done { break } else if err != nil { if err != nil { t.Fatal(err) } } err = row.ToStruct(&Article{}) if err != nil { t.Fatal(err) } } } newArt := &Article{ID: 300} err = g.Get(newArt) if err != nil { t.Fatal(err) } if v := newArt.Title; v != art.Title { t.Error("unexpected", v) } if v := newArt.Body; v != art.Body { t.Error("unexpected", v) } } func TestSpanner_AutoInc(t *testing.T) { t.SkipNow() // Result: Spanner does not have AUTOINCREMENT like feature. g, err := makeDefaultGopan(context.Background()) if err != nil { t.Fatal(err.Error()) } columns := []string{"Title", "Body", "CreatedAt", "UpdatedAt"} m := []*spanner.Mutation{ spanner.Insert("Article", columns, []interface{}{"Title", "Body", time.Now(), time.Now()}), } g.Client.Apply(g.Context, m) } func makeDefaultGopan(c context.Context) (*Gopan, error) { g := FromContext(context.Background()) g.ProjectID = os.Getenv("GCLOUD_PROJECT_ID") g.Instance = os.Getenv("GCLOUD_SPANNER_INSTANCE") g.DBName = os.Getenv("GCLOUD_SPANNER_DBNAME") adminClient, err := database.NewDatabaseAdminClient(context.Background()) if err != nil { return nil, err } g.AdminClient = adminClient client, err := spanner.NewClient(c, fmt.Sprintf("projects/%s/instances/%s/databases/%s", g.ProjectID, g.Instance, g.DBName)) if err != nil { return nil, err } g.Client = client return g, nil } <file_sep>/test.sh #!/bin/sh -eux goimports -w . go tool vet . ! golint . | \ grep -v "should have comment or be unexported" | \ grep -v "comment on exported method" go test ./... $@ <file_sep>/gopan.go package gopan import ( "errors" "fmt" "reflect" "cloud.google.com/go/spanner" "cloud.google.com/go/spanner/admin/database/apiv1" "golang.org/x/net/context" "google.golang.org/api/iterator" adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" ) type Gopan struct { Context context.Context AdminClient *database.DatabaseAdminClient Client *spanner.Client ProjectID string Instance string DBName string } func FromContext(c context.Context) *Gopan { // TODO その他の値の設定 return &Gopan{ Context: c, } } func (g *Gopan) CreateDB(srcs ...interface{}) error { var tableDDLs []string for _, src := range srcs { v := reflect.Indirect(reflect.ValueOf(src)) extruder, err := getExtruder(v.Type()) if err != nil { return err } tableDDLs = append(tableDDLs, extruder.DDLCreateTable()) } op, err := g.AdminClient.CreateDatabase(g.Context, &adminpb.CreateDatabaseRequest{ Parent: fmt.Sprintf("projects/%s/instances/%s", g.ProjectID, g.Instance), CreateStatement: fmt.Sprintf("CREATE DATABASE `%s`", g.DBName), ExtraStatements: tableDDLs, }) if err != nil { return err } _, err = op.Wait(g.Context) if err != nil { return err } return nil } // TODO DBの設定(Namespace的な)が必要 context.Context経由 func (g *Gopan) Key(src interface{}) *Key { key, err := g.KeyError(src) if err == nil { return key } return nil } // Deprecated: use Table instead. func (g *Gopan) Kind(src interface{}) string { return g.Table(src) } func (g *Gopan) Table(src interface{}) string { return reflect.Indirect(reflect.ValueOf(src)).Type().Name() } func (g *Gopan) KeyError(src interface{}) (*Key, error) { v := reflect.Indirect(reflect.ValueOf(src)) ex, err := getExtruder(v.Type()) if err != nil { return nil, err } return ex.KeyError(v) } // TODO func (g *Gopan) RunInTransaction( // Deprecated: use Insert or Update or InsertOrUpdate instead. func (g *Gopan) Put(src interface{}) (*Key, error) { keys, err := g.PutMulti([]interface{}{src}) if err != nil { // TODO return nil, err } return keys[0], err } // Deprecated: use InsertMulti or UpdateMulti or InsertOrUpdateMulti instead. func (g *Gopan) PutMulti(src interface{}) ([]*Key, error) { return g.InsertMulti(src) } func (g *Gopan) Insert(src interface{}) (*Key, error) { keys, err := g.InsertMulti([]interface{}{src}) if err != nil { // TODO return nil, err } return keys[0], err } func (g *Gopan) InsertMulti(src interface{}) ([]*Key, error) { return g.execMutationMulti(src, spanner.InsertStruct) } func (g *Gopan) Update(src interface{}) (*Key, error) { keys, err := g.UpdateMulti([]interface{}{src}) if err != nil { // TODO return nil, err } return keys[0], err } func (g *Gopan) UpdateMulti(src interface{}) ([]*Key, error) { return g.execMutationMulti(src, spanner.UpdateStruct) } func (g *Gopan) InsertOrUpdate(src interface{}) (*Key, error) { keys, err := g.UpdateMulti([]interface{}{src}) if err != nil { // TODO return nil, err } return keys[0], err } func (g *Gopan) InsertOrUpdateMulti(src interface{}) ([]*Key, error) { return g.execMutationMulti(src, spanner.InsertOrUpdateStruct) } func (g *Gopan) execMutationMulti(src interface{}, f func(table string, in interface{}) (*spanner.Mutation, error)) ([]*Key, error) { vs := reflect.Indirect(reflect.ValueOf(src)) if k := vs.Type().Kind(); k != reflect.Slice && k != reflect.Array { return nil, fmt.Errorf("unsupported type: %s", k.String()) } muts := make([]*spanner.Mutation, 0, vs.Len()) for i := 0; i < vs.Len(); i++ { v := vs.Index(i) mut, err := f(g.Table(v.Interface()), v.Interface()) if err != nil { return nil, err } muts = append(muts, mut) } _, err := g.Client.Apply(g.Context, muts) if err != nil { return nil, err } // TODO keys := make([]*Key, vs.Len()) return keys, nil } func (g *Gopan) Get(dst interface{}) error { return g.GetMulti([]interface{}{dst}) } func (g *Gopan) GetMulti(dst interface{}) error { vs := reflect.Indirect(reflect.ValueOf(dst)) if k := vs.Type().Kind(); k != reflect.Slice && k != reflect.Array { return fmt.Errorf("unsupported type: %s", k.String()) } var ex *extruder var keys []spanner.Key for i := 0; i < vs.Len(); i++ { v := reflect.ValueOf(vs.Index(i).Interface()) // remove Kind=Interface extruder, err := getExtruder(v.Type()) if err != nil { return err } if i == 0 { ex = extruder } else if ex.Table() != extruder.Table() { return errors.New("") // TODO } key, err := extruder.KeyError(v) if err != nil { return err } keys = append(keys, key.Key) } keySet := spanner.Keys(keys...) iter := g.Client.Single().Read(g.Context, ex.Table(), keySet, ex.Columns()) defer iter.Stop() for i := 0; ; i++ { row, err := iter.Next() if err == iterator.Done { return nil } else if err != nil { return err } err = row.ToStruct(vs.Index(i).Interface()) if err != nil { return err } } } func (g *Gopan) Delete(key *Key) error { return g.DeleteMulti([]*Key{key}) } func (g *Gopan) DeleteMulti(keys []*Key) error { muts := make([]*spanner.Mutation, 0, len(keys)) for _, key := range keys { mut := spanner.Delete(key.Table, key.Key) muts = append(muts, mut) } _, err := g.Client.Apply(g.Context, muts) if err != nil { return err } return nil }
143901482baedea88aae3ed8f711a7ca8258b9b5
[ "Markdown", "Go", "Shell" ]
8
Go
vvakame/gopan
8757ab9852561d91fa3e0757ca69975da7f573ec
1307ec90357193dc53349d319db6759563d5ec52
refs/heads/master
<file_sep>var async = require('async'); function fun1(callback){ var data = "--i am fun1--"; callback(null,data); } function fun2(args1,callback){ var data1 = "--i am fun2(1)--"; var data2 = "--i am fun2(2)--"; var data3 = "--i am fun2(3)--"; console.log(args1); //console.log(data1); //console.log(data2); //console.log(data3); callback(null,data1,data2,data3); } function fun3(args1,args2,args3,callback){ var data = "--i am fun3--"; console.log(args1); console.log(args2); console.log(args3); //console.log(data); callback(null,data); } async.waterfall([fun1,fun2,fun3], function (err,finalresult) { console.log(finalresult); });
12d9926b25ae82c0a5db234bdee81f9d4542adbe
[ "JavaScript" ]
1
JavaScript
kashishgupta1990/AsyncModuleDemo
a3ee0e179c1e57ac6c4db34ad61b9b477cd2ec4d
520f3bec21c2a6481fb691c033667342e3c5868a
refs/heads/master
<file_sep>package man; import est.Estudiante; import est.NotaSet; import java.util.ArrayList; import java.util.List; public class Manejador { List<Estudiante> estudiantes = new ArrayList<>(); public void agregarEstudiante(String nombre, double nota, int edad) { Estudiante e = new Estudiante(); e.setNombre(nombre); e.setEdad(edad); e.setNota(nota); estudiantes.add(e); } public String listar() { StringBuilder cad = new StringBuilder(); estudiantes.forEach(e -> { cad.append("============\n"); cad.append("Nombre: " + e.getNombre() + "\n"); cad.append("Edad: " + e.getEdad() + "\n"); cad.append("Nota: " + e.getNota() + "\n"); cad.append("============\n"); }); return cad.toString(); } public NotaSet calculo() { NotaSet datos = new NotaSet(); estudiantes.forEach(e -> { if ((double) e.getNota() >= 3.0) { datos.plus1Gana(); } else if ((double) e.getNota() >= 2.0) { datos.plus1Habilitan(); } else { datos.plus1Pierde(); } }); return datos; } } <file_sep>package est; public class NotaSet { private int ganan = 0; private int pieden = 0; private int habilitan = 0; /** * @param ganan the ganan to set */ public void setGanan(int ganan) { this.ganan = ganan; } /** * @param habilitan the habilitan to set */ public void setHabilitan(int habilitan) { this.habilitan = habilitan; } /** * @param pieden the pieden to set */ public void setPieden(int pieden) { this.pieden = pieden; } /** * @return the ganan */ public int getGanan() { return ganan; } /** * @return the habilitan */ public int getHabilitan() { return habilitan; } /** * @return the pieden */ public int getPieden() { return pieden; } public NotaSet(int pierden, int habilitan, int ganan) { this.ganan = ganan; this.pieden = pierden; this.habilitan = habilitan; } public NotaSet() { this.ganan = 0; this.pieden = 0; this.habilitan = 0; } public void plus1Pierde() { this.pieden += 1; } public void plus1Habilitan() { this.habilitan += 1; } public void plus1Gana() { this.ganan += 1; } }<file_sep># SoftwareLibre-JFreeChart Ejercicio simple de como se puede utilizar la libreria JFreeChart para hacer graficas en jswing <file_sep>package est; public class Estudiante { private String nombre; private double nota; private int edad; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public double getNota() { return nota; } public void setNota(double nota) { this.nota = nota; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } }
b97d69a45d7fd164ccc91a134b05f459b7c89c4c
[ "Markdown", "Java" ]
4
Java
Pedrioko/SoftwareLibre-JFreeChart
a739e17999c6c85e0dbec321a41e8e6034314d50
5ae0dbab5ef17293b45b7f1628e2f33b41711c63
refs/heads/master
<file_sep>import { HomeFilled } from "@ant-design/icons"; import { Col, Collapse, Row, Typography } from "antd"; export default function Faq() { const { Text } = Typography; const { Panel } = Collapse; return ( <div className="h-auto mt-10"> <Row className="mt-20 pt-2 pb-4 mx-auto w-3/5" align="middle"> <Col span={24} className="flex justify-start items-center"> <HomeFilled /> <Text strong className="text-black ml-4"> Faq </Text> </Col> </Row> <Row className="w-full bg-fixed bg-cover bg-no-repeat bg-center relative" style={{ backgroundImage: `url(/images/blog-bg.png)`, height: "40vh", backgroundSize: "cover", filter: "brightness(50%)", }} justify="center" align="middle" ></Row> <Row className="absolute w-full" style={{ height: "40vh", transform: "translateY(-100%)" }} justify="center" align="middle" > <Col> <Text level={1} strong className="block text-white text-6xl font-bold" > Faqs </Text> </Col> </Row> <div className="py-20 w-4/5 mx-auto"> <Collapse defaultActiveKey={["1"]} style={{ backgroundColor: "#fff", border: "none" }} > <Panel header="What is Lorem Ipsum?" key="1" className="text-2xl font-bold" > <p className="font-normal" style={{ fontSize: "18px" }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium eleifend ullamcorper. Suspendisse in leo tristique, sollicitudin ex eget, ultricies dui. Quisque at tortor et nunc rutrum condimentum a eget purus. Phasellus efficitur pulvinar tortor id auctor. Donec eget facilisis orci, vel rutrum tortor. </p> </Panel> <Panel header="Where does It come from?" key="2" className="text-2xl font-bold" > <p className="font-normal" style={{ fontSize: "18px" }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium eleifend ullamcorper. Suspendisse in leo tristique, sollicitudin ex eget, ultricies dui. Quisque at tortor et nunc rutrum condimentum a eget purus. Phasellus efficitur pulvinar tortor id auctor. Donec eget facilisis orci, vel rutrum tortor. </p> </Panel> <Panel header="Where can I get some?" key="3" className="text-2xl font-bold" > <p className="font-normal" style={{ fontSize: "18px" }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium eleifend ullamcorper. Suspendisse in leo tristique, sollicitudin ex eget, ultricies dui. Quisque at tortor et nunc rutrum condimentum a eget purus. Phasellus efficitur pulvinar tortor id auctor. Donec eget facilisis orci, vel rutrum tortor. </p> </Panel> <Panel header="Why do we use It?" key="4" className="text-2xl font-bold" > <p className="font-normal" style={{ fontSize: "18px" }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium eleifend ullamcorper. Suspendisse in leo tristique, sollicitudin ex eget, ultricies dui. Quisque at tortor et nunc rutrum condimentum a eget purus. Phasellus efficitur pulvinar tortor id auctor. Donec eget facilisis orci, vel rutrum tortor. </p> </Panel> <Panel header="The standard Lorem Ipsum passage, used since 1500s" key="5" className="text-2xl font-bold" > <p className="font-normal" style={{ fontSize: "18px" }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pretium eleifend ullamcorper. Suspendisse in leo tristique, sollicitudin ex eget, ultricies dui. Quisque at tortor et nunc rutrum condimentum a eget purus. Phasellus efficitur pulvinar tortor id auctor. Donec eget facilisis orci, vel rutrum tortor. </p> </Panel> </Collapse> </div> </div> ); } <file_sep>export const addToCart = (pid,number) => { return { type:"CART_ITEM_ADD", payload:{ plateId:pid, quantity:number } } } export const removeInCart = (pid) => { return { type:"CART_ITEM_ADD", payload:{ plateId:pid, } } }<file_sep>import React, { useEffect } from "react"; import { Row, Col } from "antd"; import Link from "next/link"; import { shallowEqual, useSelector } from "react-redux"; import { createSelector } from "reselect"; const FoodGrid = ({ category }) => { const data = useSelector(foodSelector, shallowEqual); return ( <Row className="food-grid" justify="center" gutter={[32, 48]} align="middle" > {category && category.map((plate, index) => { return index < 6 ? ( <Col xs={12} sm={8} md={6} lg={4} xl={4} xxl={4} className="gutter-row" key={plate.id} > {/* <Link href={`/category/${encodeURIComponent(plate.id)}`}> */} <Link href="/category"> <a> <div className="flex flex-col food-card h-56"> <img className="category-icon" src={plate.url} alt="" /> <label className="category-label cursor-pointer"> {plate.name} </label> </div> </a> </Link> </Col> ) : ( "" ); })} </Row> ); }; const foodSelector = createSelector( (state) => state.food.collection, (data) => data ); export default FoodGrid; <file_sep>import { Drawer } from "antd"; import Link from "next/link"; import { useEffect, useState } from "react"; import { FiAlignLeft } from "react-icons/fi"; import { FaBroadcastTower, FaComments, FaEdit, FaGripHorizontal, FaQuestionCircle, FaUtensils, } from "react-icons/fa"; const LeftMenu = () => { const [visible, setVisible] = useState(false); const [isMobile, setIsMobile] = useState(false); const onClose = () => { setVisible(false); }; useEffect(() => { window.screen.width < 780 ? setIsMobile(true) : setIsMobile(false); }, []); return ( <div> {/* LEFT MENU */} <button type="button" className="text-dark-500 pl-12 dark:text-gray-200 hover:text-gray-600 dark:hover:text-gray-400 focus:outline-none focus:text-gray-600 dark:focus:text-gray-400" aria-label="toggle menu" onClick={() => setVisible(true)} > <FiAlignLeft size={30} /> </button> <Drawer destroyOnClose placement="left" closable={false} onClose={onClose} width={isMobile ? "100%" : "35%"} visible={visible} drawerStyle={{ width: "85%", margin: "0 auto", }} keyboard={true} > <img src="/images/close.png" alt="close" className="h-4 w-4 mb-4 cursor-pointer float-right" onClick={onClose} /> <ul> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/newincheffy"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <FaBroadcastTower color="#d73d36" className="mr-5" size={30} /> New in cheffy </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/category"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <FaGripHorizontal color="#d73d36" className="mr-5" size={30} /> Categories </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/chef"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <img src="/images/chef/chef.svg" alt="" className="mr-7" /> Chef </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/kitchen"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <FaUtensils color="#d73d36" className="mr-5" size={30} /> Rent a kitchen </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/blog"> <a style={{ fontSize: 18 }} className="flex align-center disable" onClick={onClose} > <FaEdit color="#d73d36" className="mr-5" size={30} /> Blog </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/faq"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <FaComments color="#d73d36" className="mr-5" size={30} /> Faq </a> </Link> </li> <li style={{ borderBottom: "1px solid #A0AEC0" }} className="pt-5 pb-5" > <Link href="/help"> <a style={{ fontSize: 18 }} className="flex align-center" onClick={onClose} > <FaQuestionCircle color="#d73d36" className="mr-5" size={30} /> Help </a> </Link> </li> </ul> </Drawer> </div> ); }; export default LeftMenu; <file_sep>import Head from "next/head"; import { useDispatch } from "react-redux"; import { FoodLayout } from "../src/components/Layouts/home"; import { FoodContent } from "../src/components/Layouts/home"; const Home = () => { const dispatch = useDispatch(); return ( <> <Head> <title>Cheffy - Home</title> </Head> <FoodContent dispatch={dispatch} /> </> ); }; Home.Layout = FoodLayout; export default Home; <file_sep>import { Fragment, useState } from 'react'; import { Button, Typography, Form, Input, Row, Col } from 'antd'; import Link from 'next/link'; import { FacebookFilled, GoogleCircleFilled } from '@ant-design/icons'; import NumericInput from '../NumericInput'; const Page2 = ({ onClick, customer }) => { const [value, setValue] = useState(''); const [password, setType] = useState('password'); const { Text } = Typography; const onChange = (value) => setValue(value); const isPasswordVisible = () => { if ('password' === password) { setType(() => 'text'); } if ('text' === password) { setType(() => 'password'); } }; return ( <> <div className="flex flex-row justify-between align-center mb-6"> <Text className="text-4xl font-extrabold">{customer} Sign Up</Text> <img src="/images/close.png" alt="close" className="h-4 w-4 cursor-pointer" onClick={onClick} /> </div> <Text className="my-8"> or<Text className="text-red-500 ml-2">login to your account</Text> </Text> <Form className="mt-10" layout="vertical"> <Form.Item> <NumericInput value={value} onChange={onChange} /> </Form.Item> <Form.Item> <Input className="signup-input" placeholder="Name" type="text" /> </Form.Item> <Form.Item> <Input className="signup-input" placeholder="Email" type="email" /> </Form.Item> <Form.Item> <Input className="signup-input" placeholder="<PASSWORD>" type={password} /> <img src="/images/eye.png" className="absolute right-2 bottom-5 cursor-pointer" alt="show" onClick={isPasswordVisible} /> </Form.Item> <Text className="mb-6">Have a referral code?</Text> <Form.Item> <Button className="py-6 flex flex-row justify-center items-center" block type="primary"> Continue </Button> </Form.Item> </Form> <Text> By creating an account, I accept the <Text className="text-red-500">Terms & Conditions</Text> </Text> <Text className="text-center block mt-8 mb-4 text-xl">Or Sign Up With</Text> <Row className="flex justify-around" gutter={16}> <Col span={12}> <Button className="py-6 px-10 flex flex-row justify-center items-center" style={{ backgroundColor: '#3B5998' }} prefix={<FacebookFilled />} > Facebook </Button> </Col> <Col span={12}> <Button className="py-6 px-10 flex flex-row justify-center items-center" prefix={<GoogleCircleFilled />} > Google </Button> </Col> </Row> </> ); }; export default Page2; <file_sep>import { useState } from 'react'; import { Button, Typography, Form, Input, Row, Col, message } from 'antd'; import Link from 'next/link'; import { ArrowLeftOutlined, FacebookOutlined, GoogleOutlined } from '@ant-design/icons'; import { signIn } from 'next-auth/client'; import { userLogin } from '../../../../redux/actions/auth/authAction'; import { useDispatch } from 'react-redux'; const LoginPage2 = ({ onClick, customer, goBack }) => { const [password, setType] = useState('password'); const dispatch = useDispatch(); const { Text } = Typography; const isPasswordVisible = () => { if ('password' === password) { setType(() => 'text'); } if ('text' === password) { setType(() => 'password'); } }; const onFinish = async (values) => { try { const vals = { login: values.email.trim(), password: values.password, }; const userData = await dispatch(userLogin(vals)); // console.log('cheffyCredentials', userData); if (userData && userData.token) { let callbackUrl = '/'; if (userData.data.userResponse.user_type == 'user') { callbackUrl = '/food'; } else if (userData.data.userResponse.user_type == 'chef') { callbackUrl = '/chef'; } else if (userData.data.userResponse.user_type == 'admin') { callbackUrl = '/kitchen'; } else if (userData.data.userResponse.user_type == 'driver') { callbackUrl = '/driver'; } const user = { apiToken: userData.token, id: userData.data.userResponse.id, name: userData.data.userResponse.name, email: userData.data.userResponse.email, role: userData.data.userResponse.user_type, image: userData.data.userResponse.imagePath, callbackUrl: `${process.env.NEXTAUTH_URL}${callbackUrl}`, }; // console.log('user', user); signIn('cheffyCredentials', user); } } catch (err) { //console.log('err', err.toString()); message.error(err.message); } }; return ( <> <div className="flex flex-row justify-between align-center mb-6"> <Text className="text-4xl font-extrabold">{customer} Sign In</Text> <img src="/images/close.png" alt="close" className="h-4 w-4 cursor-pointer" onClick={onClick} /> </div> <Text className="my-8"> or<Text className="text-red-500 ml-2">Sign Up</Text> </Text> <Form className="mt-10" layout="vertical" onFinish={onFinish}> <Form.Item name="email"> <Input className="signup-input" placeholder="Email" type="email" /> </Form.Item> <Form.Item name="password" className="relative"> <Input className="signup-input" placeholder="<PASSWORD>" type={password} /> </Form.Item> <span> <img src="/images/eye.png" className="absolute right-6 top-1/3 bottom-1/2 cursor-pointer" alt="show" onClick={isPasswordVisible} /> </span> <Form.Item> <Button htmlType="submit" className="py-6 flex flex-row justify-center items-center" block type="primary" > Sign In </Button> </Form.Item> </Form> <Text className="text-red-500">Forgot Password ?</Text> <Text className="text-center block mt-8 mb-4 text-xl">Or Sign In With</Text> <Row className="flex justify-around" gutter={16}> <Col span={12}> <Button className="py-6 px-10 flex flex-row justify-center items-center" style={{ backgroundColor: '#3B5998' }} prefix={<FacebookOutlined />} > Facebook </Button> </Col> <Col span={12}> <Button className="py-6 px-10 flex flex-row justify-center items-center" prefix={<GoogleOutlined />} > Google </Button> </Col> </Row> <Button className="mt-4 flex flex-row justify-center items-center" onClick={goBack}> <ArrowLeftOutlined /> Back </Button> </> ); }; export default LoginPage2; <file_sep>import { ClockCircleOutlined } from "@ant-design/icons"; import { Button, Col, Divider, Row, Table, Tabs, Typography } from "antd"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { fetchFood } from "../../../redux/actions/food"; import { asyncLocalStorage } from "../../../utils/localStorage"; import { addToCart } from "../../../redux/actions/cart/cartAction"; import styled from "styled-components"; import { useLocalStorageState } from "ahooks"; import Head from "next/head"; const { TabPane } = Tabs; const { Text } = Typography; const ClockIcon = () => { return <img src="/images/clock.png" className="w-3 h-3" alt="clock" />; }; const TruckIcon = () => { return <img src="/images/truck.png" alt="truck" className="h-3 w-auto" />; }; const CartIcon = () => { return <img src="/images/cart.png" alt="cart" className="w-4 h-4" />; }; const StarIcon = () => { return <img className="w-3 h-3" src="/images/star-yellow.png" alt="rating" />; }; const TabName = ({ name }) => { return ( <Text strong className="text-black"> {name} </Text> ); }; const FoodDetailContent = ({ foodId, data, platesRelated }) => { const dispatch = useDispatch(); const [page1, setPage1] = useState(""); const [cartitems,setCartitems] = useLocalStorageState("cartitems",{"items":[]}) const selectedFood = Object.assign(data); const image_url = selectedFood?.PlateImages[0]?.url; const chefImage = selectedFood.chef.image ? selectedFood.chef.image : "/images/chef/chef.jpg"; const rating = selectedFood.rating ? selectedFood.rating : "no rating yet"; const [numberof, setNumber] = useState(1); const [inCart, setInCart] = useState(false); const router = useRouter(); useEffect(async () => { dispatch(fetchFood()); setPage1(0); console.log(cartitems) // try { // const plateId = foodId; // let cartitems = await asyncLocalStorage.getItem("cartitems"); // cartitems = JSON.parse(cartitems); // // console.log(cartitems) // cartitems["items"].forEach((item) => { // // console.log(item) // if (item.plateId == plateId) { // // console.log("Already in the cart.!"); // setInCart(true); // } // }); // } catch (e) { // console.log(e); // } }, [cartitems]); const AddOne = () => { // console.log("x") if (numberof < 10) { setNumber(numberof + 1); } }; const removeOne = () => { if (numberof > 1) { setNumber(numberof - 1); } }; const goTocart = () => { router.push("/cart"); }; const AddtoCart = async () => { // console.log(asyncLocalStorage) dispatch(addToCart(foodId,numberof)) let cartitems = await asyncLocalStorage.getItem("cartitems"); // console.log(cartitems) const plateId = foodId; const orderednumber = numberof; let item = { plateId: plateId, ordered: orderednumber, }; if (!cartitems) { await asyncLocalStorage.setItem( "cartitems", JSON.stringify({ items: [item] }) ); setInCart(true); console.log("Added to cart.!"); } else { cartitems = JSON.parse(cartitems); // console.log(cartitems) cartitems["items"].forEach((item) => { // console.log(item) if (item.plateId == plateId) { console.log("Already in the cart.!"); setInCart(true); // return } }); // console.log(inCart) if (inCart !== true) { // console.log("Not first or not in cart too") cartitems["items"].push(item); console.log("Pushed.!"); await asyncLocalStorage.setItem("cartitems", JSON.stringify(cartitems)); setInCart(true); } } }; const handlePrev = () => { setPage1(page1 - 3); }; const handleNext = () => { setPage1(page1 + 3); }; const columns = [ { title: "Ingredients", dataIndex: "Ingredients", key: "Ingredients", }, { title: "Purchase Date", dataIndex: "Date", key: "Date", }, ]; const dataSource = [ { key: "1", Ingredients: "1.Tomato", Date: "8-19-19", }, { key: "2", Ingredients: "2.Water", Date: "8-19-19", }, { key: "3", Ingredients: "3.Egg", Date: "8-19-19", }, ]; const FlexBox = styled.div` display: flex; align-items: center; justify-content: flex-start; margin-top: 16px; width: 100%; @media (max-width: 768px) { flex-direction: column; justify-content: center; } `; const getBackgrounStyle = (plate) => { if(plate?.PlateImages[0]?.url){ return `url(${plate?.PlateImages[0]?.url})`}} return ( <> {selectedFood ? <Head> <title>Order - {selectedFood.name}</title> </Head> : <Head> <title>Loading..</title> </Head>} <Row className="w-full bg-fixed bg-cover bg-no-repeat bg-center relative mt-12" style={{ backgroundImage: `url(${image_url})`, height: "40vh", backgroundSize: "cover", filter: "brightness(30%)", }} justify="center" align="middle" ></Row> <Row className="absolute w-full" style={{ height: "40vh", transform: "translateY(-100%)" }} justify="center" align="middle" > <Col> <Text strong className="block text-white text-3xl"> {selectedFood.name} </Text> <div className="flex flex-row justify-center mt-2"> <ClockCircleOutlined className="text-white mt-1" /> <Text className="ml-3 text-white text-center"> {selectedFood.delivery_time} Min </Text> </div> </Col> </Row> <Row className="pt-2 pb-4 mx-auto w-3/5 sm:w-100" justify="center" align="bottom" > <Col span={5} xs={14} sm={16} md={5} className="mt-16"> <img src={chefImage} alt={selectedFood.chef.name} className="w-100 mb-6 md:mb-0 block" /> </Col> <Col span={1}></Col> <Col span={18} className="pb-2" xs={22} sm={22} md={18}> <FlexBox> <Col> <Text strong className="text-2xl font-bold"> {selectedFood.chef.name} </Text> </Col> </FlexBox> <Row> <FlexBox> <span className="flex flex-row items-center mt-2 mb-2"> <StarIcon /> <Text className="ml-2"> {rating} ({selectedFood.reviews.length + 1}) </Text> </span> <span className="mx-7 flex flex-row justify-center items-center mt-2 mb-2"> <ClockIcon /> <Text className="ml-2 text-center"> {selectedFood.delivery_time} Min </Text> </span> <span className="flex flex-row items-center mt-2 mb-2"> <TruckIcon /> <Text className="ml-2">Delivery</Text> </span> </FlexBox> </Row> </Col> </Row> <Row className="w-3/5 mx-auto"> <Divider style={{ backgroundColor: "#A0AEC0" }} /> </Row> <Row className="my-2 mx-auto w-3/5" align="middle" sm={12}> <FlexBox> <h1 className="text-2xl font-bold md:mb-0 xs:mb-3"> ${selectedFood.price} </h1> <Button onClick={() => { if (inCart) { goTocart(); } else { AddtoCart(); } }} size="large" type="primary" className="flex flex-row items-center mx-4 rounded-none" > <CartIcon /> {inCart ? ( <p className="ml-2">Go to Cart</p> ) : ( <p className="ml-2">Add to Cart</p> )} </Button> <span style={{ backgroundColor: "#EDF2F7", borderBottom: "1px solid #A0AEC0", display: "inline-block", }} className="md:mt-0 xs:mt-5" > <Button onClick={removeOne} size="large" className="border-none text-black rounded-none" ghost > {" - "} </Button> <Text className="md:mx-2 xs:mx-0">{numberof}</Text> <Button onClick={AddOne} size="large" className="border-none text-black rounded-none" ghost > {" + "} </Button> </span> </FlexBox> </Row> <Row className="w-3/5 mx-auto"> <Divider style={{ backgroundColor: "#A0AEC0" }} /> </Row> <Row className="w-3/5 mx-auto mb-10"> <Col span={24}> <Tabs defaultActiveKey="1" size="large"> <TabPane tab={<TabName name="The Plate" />} key="1"> <Text className="mb-6 mt-2 block"> {selectedFood.description} </Text> <Table pagination={false} dataSource={dataSource} columns={columns} /> </TabPane> <TabPane tab={<TabName name="Kitchen" />} key="2"> Content of Tab Pane 2 </TabPane> <TabPane tab={<TabName name="Recipe" />} key="3"> Content of Tab Pane 3 </TabPane> <TabPane tab={<TabName name="Review" />} key="4"> Content of Tab Pane 4 </TabPane> </Tabs> </Col> </Row> <Row className="w-3/5 mx-auto mb-10" justify="space-between" align="middle" > <Col> <Text strong className="md:text-3xl font-bold xs:text-2xl"> Other Plates </Text> </Col> <Col> <span className="flex flex-row space-x-4"> <Button className="border-none rounded-none" disabled={page1 === 0} onClick={handlePrev} > <img onClick={handlePrev} src="/images/page-left.png" /> </Button> <Button className="border-none rounded-none" disabled={page1 >= data.length - 1} onClick={handleNext} > <img onClick={handlePrev} src="/images/page-right.png" /> </Button> </span> </Col> </Row> <Row xs={12} className="other-plate-grid flex justify-center md:pl-20 md:pr-20" > {platesRelated.map((plate, index) => { return ( index >= page1 && index < page1 + 3 && ( <Col key={plate.id} className="new-food-card md:p-8 mb-6" xs={16} xxl={16} sm={16} md={16} lg={8} xl={6} > <Link href={`/food-detail/${encodeURIComponent(plate.id)}`}> <a> <Row justify="center" className="other-food-image h-40" style={{ backgroundImage: getBackgrounStyle(), backgroundSize: "cover", }} ></Row> <Row> <Text className="mt-4 mb-1">{plate.name}</Text> </Row> <Row> <Col span={8}> <Row align="middle"> <StarIcon /> <Text className="ml-2"> {plate.rating ? plate.rating : "no rating yet"} </Text> </Row> </Col> <Col span={8}> <Row align="middle"> <ClockIcon /> <Text className="ml-2"> {plate?.delivery_time} Min </Text> </Row> </Col> <Col span={8}> <Row align="middle" justify="end"> <TruckIcon /> <Text className="ml-2">Delivery</Text> </Row> </Col> </Row> </a> </Link> </Col> ) ); })} </Row> </> ); }; export default FoodDetailContent; <file_sep>import { Col, Row } from 'antd'; import Link from 'next/link'; import React, { useEffect, useState } from 'react' import { useDispatch } from 'react-redux'; import { mustTryAndRecommendedChef } from '../../../redux/actions/chef/chefAction'; import axiosClient from '../../../utils/axios-config'; function TopKitchens() { const [topKitchens, settopKitchens] = useState(''); const dispatch = useDispatch(); useEffect(async () => { const url = "https://cheffyus-api.herokuapp.com/kitchens/" try{ const res = await axiosClient(url); settopKitchens(res); }catch(e){ console.log(e) } }, []); return ( <> <Row className="food-grid mt-16 mb-10" gutter={32} justify="start" align="middle"> <Col className="my-5"> <label className="font-extrabold text-5xl xs:text-4xl sm:text-4xl lg:text-5xl">Kitchens You Should see</label> </Col> </Row> <Row className="food-grid" justify="center" gutter={32} align="middle"> {topKitchens && topKitchens.map((item, index) => { console.log(item) return index < 6 ? ( <Col className="gutter-row h-64" xs={12} sm={8} md={6} lg={4} xl={4} xxl={4} key={item["kitchen"].id}> <Link href={`/kitchen/${encodeURIComponent(item["kitchen"]["name"])}/${encodeURIComponent(item["kitchen"].id)}`}> <a> <div className="flex flex-col py-6 px-3 items-center"> <img className="category-icon mb-4" src={item["kitchen"]["image_urls"][0]} alt="" /> <label className="category-label cursor-pointer">{item["kitchen"]["name"]}</label> </div> </a> </Link> </Col> ) : ( '' ); })} </Row> </> ); }; export default TopKitchens <file_sep>import React, { useEffect, useState } from "react"; import { Typography, Card, Row, Col, Button, Grid, Input, Space, Divider, Tabs, } from "antd"; import { HomeFilled, MenuOutlined, StarFilled, ClockCircleFilled, } from "@ant-design/icons"; import { IoMdArrowDropdown } from "react-icons/io"; import axiosClient from "../../../utils/axios-config"; import Link from "next/link"; import { useRouter } from "next/router"; const { TabPane } = Tabs; const KitchenCol = ({ name, rating, count, price, price_type, imgURL }) => { return ( <> <div className="kitchen-card pb-4" dir="ltr"> <img src={imgURL} className="w-100 h-36" /> <p className="pt-2 font-normal text-lg">{name}</p> <p className="flex items-center text-base pt-2"> <StarFilled className="pr-1 text-yellow-500" /> {`${rating} (${count})`} <p className="flex items-center pl-6" dir="ltr"> <ClockCircleFilled className="pr-1" /> {`$${price}`} - {price_type} </p> </p> </div> </> ); }; const KitchenContent = () => { const { Title, Paragraph, Text } = Typography; const [kitchens, setKitchens] = useState([]); const router = useRouter(); useEffect(async () => { try { const url = "https://cheffyus-api.herokuapp.com/kitchens/"; const res = await axiosClient.get(url); setKitchens(res); console.log("Added"); } catch (e) { console.log(e); } }, []); const showKitchen = (kname, kId) => { console.log(kId); router.push(`/kitchen/${kname}/${kId}`); }; return ( <> <Row className="mt-20 pt-2 pb-4 mx-auto w-3/5" align="middle"> <Col span={24} className="flex justify-start items-center"> <HomeFilled /> <Text strong className="text-black ml-4"> Rent Kitchen </Text> </Col> </Row> <Row className="w-full bg-fixed bg-cover bg-no-repeat bg-center relative" style={{ backgroundImage: `url(/images/background.jpg)`, height: "30vh", backgroundSize: "100%", filter: "brightness(50%)", }} justify="center" align="middle" ></Row> <Row className="absolute w-full" style={{ height: "30vh", transform: "translateY(-100%)" }} justify="center" align="middle" > <Col> <Text level={1} strong className="block text-white text-5xl"> Rent a Kitchen </Text> </Col> </Row> <div className="py-20 w-4/5 md:w-3/5 mx-auto"> <hr /> <Tabs defaultActiveKey={"relavence"} className="font-bold" size="large" direction="rtl" moreIcon={<MenuOutlined />} > <TabPane key="filters" tab="Filters"> Filters Tab </TabPane> <TabPane key="ratings" tab="Ratings"> Ratings Tab </TabPane> <TabPane key="relavence" tab="Relavence"> <div className="kitchen-item "> <Row gutter={[16, 16]} className="flex pt-4" dir="ltr"> {kitchens && kitchens.map((item, index) => { return ( <Col onClick={() => showKitchen( item["kitchen"]["name"], item["kitchen"]["id"] ) } className="cursor-pointer" span={8} > <KitchenCol name={item["kitchen"]["name"]} imgURL={item["kitchen"]["image_urls"][0]} rating={"4.3"} count={item["kitchen"]["likes"]} price={item["kitchen"]["price_per_time"]} price_type={item["kitchen"]["time_type"]} /> </Col> ); })} </Row> </div> <div dir="ltr" className="flex items-center justify-center pt-10 load-more" > <p className="text-white flex items-center bg-red-500 py-4 px-10 text-lg"> Load More <IoMdArrowDropdown className="text-3xl" /> </p> </div> </TabPane> </Tabs> </div> </> ); }; export default KitchenContent; <file_sep>import React from "react"; import { useRouter } from "next/router"; import { FoodDetailContent } from "../../src/components/Layouts/food-detail/"; import FoodHeader from "../../src/components/Layouts/Header/HomeHeader"; import FoodFooter from "../../src/components/Layouts/home/FoodFooter"; const Index = ({ data, platesRelated }) => { const router = useRouter(); const foodId = router.query.foodId || []; return ( <div> <FoodHeader /> <FoodDetailContent foodId={foodId} data={data} platesRelated={platesRelated} /> <FoodFooter /> </div> ); }; export async function getServerSideProps({ query }) { let response = await ( await fetch(`https://mycheffy.herokuapp.com/plate/show/${query.foodId}`) ).json(); const data = await response.data; response = await ( await fetch(`https://mycheffy.herokuapp.com/plate/${query.foodId}/related`) ).json(); const platesRelated = await response.data; return { props: { data, platesRelated }, }; } export default Index; <file_sep>import produce from "immer"; import * as types from "../actions/counter/counterType"; const cartCounter = (state = 0, { type }) => { switch (type) { case "CART_ITEM_ADD": console.log("Adding.!",state+1,state) console.log(window.localStorage.getItem("cartitems")) return state+1; case "CART_ITEM_REMOVE": return state - 1; default: return state; } }; export const cartReducer = produce(cartCounter); <file_sep>// import ChefHeader from './ChefHeader'; export { default as ChefLayout } from './ChefLayout'; export { default as ChefContent } from './ChefContent'; <file_sep>import React, { useEffect, useState } from "react"; import { Row, Col } from "antd"; import { popularAndNew } from "../../../redux/actions/food"; import { useDispatch } from "react-redux"; import Link from "next/link"; const StarIcon = () => { return <img className="mr-2 w-4 h-4" src="/images/star.png" alt="rating" />; }; const ClockIcon = () => { return <img className="mr-2 w-4 h-4" src="/images/clock.png" alt="time" />; }; const TruckIcon = () => { return ( <img className="mr-2" src="/images/truck.png" width="20px" alt="delivery" /> ); }; const PopularNearYou = ({ popular }) => { return ( <> <Row className="food-grid mt-16 mb-10" gutter={32} justify="start" align="middle" > <Col className="my-5"> <label className="font-extrabold text-5xl xs:text-4xl sm:text-4xl md:text-4xl lg:text-5xl"> Popular Near You </label> </Col> </Row> <Row className="food-grid" gutter={[32, 48]} justify="center" align="top"> {popular && popular.map((data, index) => { return index > 4 && index < 9 ? ( <Col xs={24} sm={12} md={12} lg={8} xl={6} xxl={6} key={data.id} className="new-food-card" > <Link href={`/food-detail/${encodeURIComponent(data.id)}`}> <a> <Row justify="center" className="new-food-image" style={{ backgroundImage: `url(${data.PlateImages[0]?.url})`, }} ></Row> <Row className="my-5 ml-1 mr-2"> <Col span={8}> <Row align="middle"> <StarIcon /> <label>4.5</label> </Row> </Col> <Col span={8}> <Row align="middle"> <ClockIcon /> <label>15-20 min</label> </Row> </Col> <Col span={8}> <Row align="middle" justify="end"> <TruckIcon /> <label>Delivery</label> </Row> </Col> </Row> <Row> <label className="label">{data.name}</label> </Row> </a> </Link> </Col> ) : ( "" ); })} </Row> </> ); }; export default PopularNearYou; <file_sep>import React, { Component, useEffect, useState } from "react"; import Link from "next/link"; import { Menu, Dropdown, Button, Drawer, Badge } from "antd"; import { signOut, useSession } from "next-auth/client"; import { DownOutlined } from "@ant-design/icons"; import { FaUser } from "react-icons/fa"; import Signup from "./Signup/Signup"; import Login from "./Login/Login"; import LeftMenu from "../menu/LeftMenu"; import { FaShoppingBag } from "react-icons/fa"; import { asyncLocalStorage } from "../../../utils/localStorage"; import { useLocalStorageState } from "ahooks"; import { connect } from "react-redux"; const FoodHeader = ({count}) => { const [session, loading] = useSession(); const [cartCount,setCartCount] = useState(0); const isChef = session?.role === "chef"; const isDriver = session?.role === "driver"; const isUser = session?.role === "user"; const [items,setItems] = useLocalStorageState("cartitems") useEffect(async () => { try{ setCartCount(items["items"].length) // console.log("Count has been set") } catch(e){ console.log(e) } },[items]) const DropdownMobile = () => { return ( <Menu className="mt-4"> <Menu.Item key="0" className="py-6 px-8"> {!session ? ( <Signup isMobile={true} /> ) : ( <Link href={`${isChef ? "/chef" : isDriver ? "/driver" : "/food"}`}> <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" > Dashboard </a> </Link> )} </Menu.Item> <Menu.Item key="1" className="py-6 px-8"> {!session ? ( <Login isMobile={true} /> ) : ( <Link href={`${ isChef ? "/chef/profile" : isDriver ? "/driver/profile" : "/food/profile" }`} > <a href="#" className="block px-8 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" > Profile </a> </Link> )} </Menu.Item> <Menu.Item key="2" className="py-6 px-8"> <Link href="/about"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm rounded-md"> About </a> </Link> </Menu.Item> <Menu.Item key="3" className="py-6 px-8"> <Link href="/contact"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm rounded-md"> Contact us </a> </Link> </Menu.Item> <Menu.Item key="4" className="py-6 px-8"> <Link href="/cart"> <p className="cursor-pointer flex items-center"> Cart ({cartCount}) </p> </Link> </Menu.Item> {session ? ( <Menu.Item key="4" className="py-6 px-8"> <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" onClick={(e) => { e.preventDefault(); signOut({ callbackUrl: "/" }); }} > Sign out </a> </Menu.Item> ) : null} </Menu> ); }; const ImgIcon = () => { // console.log(session.user.image) if (session.user.image == "null") { return <FaUser className="text-2xl h-8 w-8 rounded-full mr-2" />; } else { return ( <img src={session.user.image} className="user-img h-8 w-8 rounded-full mr-6" alt="" /> ); } return <FaUser />; }; const DropdownMenu = () => { return ( <Menu className="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg py-1 bg-white ring-1 ring-black ring-opacity-5"> <Menu.Item key="0"> <Link href={`${isChef ? "/chef" : isDriver ? "/driver" : "/food"}`}> <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" > Dashboard </a> </Link> </Menu.Item> <Menu.Item key="1"> <Link href={`${ isChef ? "/chef/profile" : isDriver ? "/driver/profile" : "/food/profile" }`} > <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" > Profile </a> </Link> </Menu.Item> <Menu.Item key="2"> <a href="#" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem" onClick={(e) => { e.preventDefault(); signOut({ callbackUrl: "/" }); }} > Sign out </a> </Menu.Item> </Menu> ); }; return session ? ( <nav style={{ backgroundColor: "#F7FCFF", boxShadow: "0 0 5px #ddd" }} className="dark:bg-gray-800 stickey" > <div className="mx-auto py-4"> <div className="md:flex md:items-center md:justify-between"> <div className="flex justify-between items-center"> {/* LEFT MENU */} <LeftMenu /> <div className="hidden md:flex cursor-pointer red pl-12"> <Link href="/"> <img src="/images/logo.png" /> </Link> </div> <div className="md:hidden cursor-pointer red"> <Link href="/"> <img src="/images/mobile-logo.png" /> </Link> </div> {/* Mobile menu button */} <div className="flex md:hidden pr-8"> <Dropdown overlayClassName="fixed w-screen" className="flex flex-row justify-center items-center md:mt-0" overlay={DropdownMobile} trigger={["click"]} placement="bottomRight" > <button type="button" className="text-gray-500 dark:text-gray-200 hover:text-gray-600 dark:hover:text-gray-400 focus:outline-none focus:text-gray-600 dark:focus:text-gray-400" aria-label="toggle menu" > <svg viewBox="0 0 24 24" className="h-6 w-6 fill-current"> <path fillRule="evenodd" d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z" /> </svg> </button> </Dropdown> </div> </div> {/* Mobile Menu open: "block", Menu closed: "hidden" */} <div className="hidden md:flex md:items-center md:justify-between flex-1"> <div className="hidden md:flex md:items-center md:justify-between flex-1"> <div className="flex flex-col -mx-4 md:flex-row md:items-center md:mx-8"> <Link href="/about"> <a>About</a> </Link> <Link href="/about"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm rounded-md"> Contact us </a> </Link> </div> <div className="flex items-center"> <Badge count={cartCount}> <Link href="/cart"> <p className="cursor-pointer flex items-center"> <FaShoppingBag className="text-2xl" /> </p> </Link> </Badge> <Dropdown className="flex flex-row justify-center items-center mt-4 md:mt-0" overlay={DropdownMenu} trigger={["click"]} placement="bottomRight" > <Button style={{ backgroundColor: "transparent" }} className="px-6 flex flex-row justify-center items-center" type="text" icon={<ImgIcon />} > {session.user.name} <DownOutlined className="ml-2" /> </Button> {/* <a className="max-w-xs bg-gray-800 rounded-full flex items-center text-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" onClick={(e) => e.preventDefault()} > <img className="h-8 w-8 rounded-full" src={session.user.image} alt="" /> </a> */} </Dropdown> </div> </div> </div> </div> </div> </nav> ) : ( <nav style={{ backgroundColor: "#F7FCFF", boxShadow: "0 0 5px #ddd" }} className="dark:bg-gray-800 stickey" > <div className="mx-auto py-4"> <div className="md:flex md:items-center md:justify-between"> <div className="flex justify-between items-center"> {/* LEFT MENU */} <LeftMenu /> <div className="hidden md:flex cursor-pointer red pl-8"> <Link href="/"> <img src="/images/logo.png" /> </Link> </div> <div className="md:hidden cursor-pointer red"> <Link href="/"> <img src="/images/mobile-logo.png" /> </Link> </div> {/* Mobile menu button */} <div className="flex md:hidden pr-8"> <Dropdown overlayClassName="fixed w-screen" className="flex flex-row justify-center items-center md:mt-0" overlay={DropdownMobile} trigger={["click"]} placement="bottomRight" > <button type="button" className="text-gray-500 dark:text-gray-200 hover:text-gray-600 dark:hover:text-gray-400 focus:outline-none focus:text-gray-600 dark:focus:text-gray-400" aria-label="toggle menu" > <svg viewBox="0 0 24 24" className="h-6 w-6 fill-current"> <path fillRule="evenodd" d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z" /> </svg> </button> </Dropdown> </div> </div> {/* Mobile Menu open: "block", Menu closed: "hidden" */} <div className="hidden md:flex md:items-center md:justify-between flex-1"> <div className="hidden md:flex md:items-center md:justify-between flex-1"> <div className="flex flex-col -mx-4 md:flex-row md:items-center md:mx-8"> <Link href="/about"> <a>About</a> </Link> <Link href="/about"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm rounded-md"> Contact us </a> </Link> </div> <div className="flex items-center mt-4 md:mt-0"> {/* <Link href="/kitchen"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm">Rent Kitchen</a> </Link> <Link href="/chef"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm">Chef</a> </Link> <Link href="/driver"> <a className="mx-2 mt-2 md:mt-0 px-2 py-1 text-sm">Driver</a> </Link> */} <Badge count={cartCount} > <Link href="/cart"> <p className="cursor-pointer"> <FaShoppingBag className="text-2xl" /> </p> </Link> </Badge> <Signup /> <Login /> </div> </div> </div> </div> </div> </nav> ); }; const mapToProps = state => { // console.log(state) return { count : state.cart } } export default connect(mapToProps)(FoodHeader);
98444f2253b6020e035c5d816ae913fb7fadf012
[ "JavaScript" ]
15
JavaScript
bibinprathap/cheffyfinal
4c15a6d88278382812994a824518b4e876c953fc
9067e87022758f17a62d89e8e18de7b8052d65e0
refs/heads/master
<file_sep>package com.nr.project2.service; import java.util.List; import com.nr.project2.model.UserDto; public interface UserService { void add(UserDto userDto) throws Exception; List<UserDto> getAllUsers(); UserDto getUserByLoginId(String userId); UserDto updateUser(UserDto userDto); String deleteUser(String userId); } <file_sep>package com.nr.project2.domain; import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; @Entity @Table(name = "user") @DynamicUpdate(value=true) public class User implements Serializable { /** * */ private static final long serialVersionUID = -2204361126742466308L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "user_no") private String userNo; @Column(name = "login_id") private String loginId; @Column(name = "<PASSWORD>") private String password; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "type", referencedColumnName = "user_type_code") private UserType type; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "version") private int version; @Column(name = "isdeleted") private boolean isDeleted; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "nr_user_role", joinColumns = @JoinColumn(name = "user") , inverseJoinColumns = @JoinColumn(name = "role") ) private Set<Role> roles; public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } public UserType getType() { return type; } public void setType(UserType type) { this.type = type; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLoginId() { return loginId; } public void setLoginId(String loginId) { this.loginId = loginId; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } } <file_sep>package com.nr.project2.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.nr.project2.model.UserDto; import com.nr.project2.service.UserService; @Controller("userController") @RequestMapping("user") public class UserController { @Autowired private UserService userService; @PostMapping("/add") public String add(UserDto user) throws Exception{ userService.add(user); return "login"; } @PostMapping("/login") public String login() throws Exception{ return "login"; } @PostMapping("/register") public String register(Model model) throws Exception{ model.addAttribute("user", new UserDto()); return "register"; } @PutMapping("/update") public UserDto update(UserDto user){ return userService.updateUser(user); } @DeleteMapping("/delete") public String delete(String userId){ return userService.deleteUser(userId); } @GetMapping("/") public List<UserDto> getAllUsers(){ return userService.getAllUsers(); } @GetMapping("/{userId") public UserDto getAllUsers(@PathVariable("userId") String userId){ return userService.getUserByLoginId(userId); } } <file_sep>package com.nr.project2; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @SpringBootApplication public class Project2Application { @Autowired private ServletContext servletContext; public static void main(String[] args) { SpringApplication.run(Project2Application.class, args); } @Bean("messageSource") public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setCacheSeconds(3600); // refresh cache once per hour return messageSource; } @Bean @Description("Thymeleaf Template Resolver") public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); return templateResolver; } @Bean @Description("Thymeleaf Template Engine") public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setTemplateEngineMessageSource(messageSource()); return templateEngine; } @Bean @Description("Thymeleaf View Resolver") public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); return viewResolver; } } <file_sep>package com.nr.project2.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user_type") public class UserType implements Serializable { /** * */ private static final long serialVersionUID = -6876619145490018698L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "user_type_code") private String userTypeCode; @Column(name = "user_type") private String userType; @Column(name = "description") private String description; @Column(name = "version") private int version; @Column(name = "isdeleted") private boolean isDeleted; public UserType(String userTypeCode) { this.userTypeCode = userTypeCode; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserTypeCode() { return userTypeCode; } public void setUserTypeCode(String userTypeCode) { this.userTypeCode = userTypeCode; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } } <file_sep>package com.nr.project2.domain; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "role") public class Role { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "role_id") private int roleId; @Column(name = "role") private String role; @Column(name = "description") private String description; @Column(name = "version") private int version; @Column(name = "isdeleted") private boolean isdeleted; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "role_access", joinColumns = @JoinColumn(name = "role"), inverseJoinColumns = @JoinColumn(name = "access")) private Set<Access> accesses; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isIsdeleted() { return isdeleted; } public void setIsdeleted(boolean isdeleted) { this.isdeleted = isdeleted; } public Set<Access> getAccesses() { return accesses; } public void setAccesses(Set<Access> accesses) { this.accesses = accesses; } } <file_sep>package com.nr.project2.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "access") public class Access { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "access_id") private int accessId; @Column(name = "access") private String access; @Column(name = "description") private String description; @Column(name = "version") private int version; @Column(name = "isdeleted") private boolean isdeleted; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAccessId() { return accessId; } public void setAccessId(int accessId) { this.accessId = accessId; } public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isIsdeleted() { return isdeleted; } public void setIsdeleted(boolean isdeleted) { this.isdeleted = isdeleted; } }
615d6dc982034db0c4fc1f72092f33b36402dd03
[ "Java" ]
7
Java
Nigrumrose/springboot-jpa-thymeleaf2
4aee887792d70ec81d4f6378c2bdd48ecd31d9a2
25010ceea0c1a35944c4cc609d3ded96f8ed5c07
refs/heads/main
<file_sep>-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Apr 25, 2021 at 05:49 PM -- Server version: 10.4.18-MariaDB -- PHP Version: 8.0.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `gadgetbadgetonlineplatform` -- -- -------------------------------------------------------- -- -- Table structure for table `funders` -- CREATE TABLE `funders` ( `funderID` int(11) NOT NULL, `funderName` varchar(100) NOT NULL, `category` varchar(100) NOT NULL, `description` varchar(500) NOT NULL, `fundingAmount` double(8,2) NOT NULL, `fundStartDate` date DEFAULT NULL, `fundEndDate` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `funders` -- INSERT INTO `funders` (`funderID`, `funderName`, `category`, `description`, `fundingAmount`, `fundStartDate`, `fundEndDate`) VALUES (4, 'ddd', 'ddd', 'ddd', 100000.00, '2021-04-01', '2021-04-21'), (6, 'Nimal', 'IT', 'to buy laptop', 10000.00, '2021-05-22', '2021-05-25'), (7, 'Sunimal', 'Managment', 'to research', 10000.00, '2021-05-22', '2021-05-26'), (8, 'Kasun', 'sport', 'To win games', 2000.00, '2021-04-24', '2021-04-30'); -- -- Indexes for dumped tables -- -- -- Indexes for table `funders` -- ALTER TABLE `funders` ADD PRIMARY KEY (`funderID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `funders` -- ALTER TABLE `funders` MODIFY `funderID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep># paf-_project IT19117492 K.V.A.S.Prabash Service Development • Technologies Used: Java,jAX-RX(jersy) on tomcat(Restful web service) • Tools: Eclips • Database: MySQL About project - Funding service In this GadegetBadgetShop Funding service part is here. Then this part ● Insert Funding ● Retrieve Funding ● Update Funding ● Delete Funding <img src="https://www.logo.wine/a/logo/Java_(programming_language)/Java_(programming_language)-Logo.wine.svg" alt="javascript" width="70" height="70"/> <img src="https://cdn.worldvectorlogo.com/logos/eclipse-11.svg" alt="javascript" width="70" height="70"/><img src="https://seeklogo.com/images/M/mysql-logo-69B39F7D18-seeklogo.com.png" alt="javascript" width="70" height="70"/> ![paf](https://user-images.githubusercontent.com/57107463/118290658-4bb36500-b4f4-11eb-8185-597ce34262d7.PNG) <file_sep>package model; import model.Funder; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FunderAPI */ @WebServlet("/FunderAPI") public class FunderAPI extends HttpServlet { private static final long serialVersionUID = 1L; Funder fundObj = new Funder(); /** * @see HttpServlet#HttpServlet() */ public FunderAPI() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String outpot = fundObj.insertFund(request.getParameter("funderName"), request.getParameter("category"), request.getParameter("description"), request.getParameter("fundingAmount"), request.getParameter("fundStartDate"), request.getParameter("fundEndDate")); response.getWriter().write(outpot); } /** * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) */ protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Map paras = getParasMap(request); String output = fundObj.Updatefund(paras.get("hidFundIDSave").toString(), paras.get("funderName").toString(), paras.get("category").toString(), paras.get("description").toString(), paras.get("fundingAmount").toString(), paras.get("fundStartDate").toString(), paras.get("fundEndDate").toString()); response.getWriter().write(output); } /** * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse) */ protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Map paras = getParasMap(request); String output = fundObj.deletefundData(paras.get("funderID").toString()); response.getWriter().write(output); } private static Map getParasMap(HttpServletRequest request) { Map<String, String> map = new HashMap<String, String>(); try { Scanner scanner = new Scanner(request.getInputStream(), "UTF-8"); String queryString = scanner.hasNext() ? scanner.useDelimiter("\\A").next() : ""; scanner.close(); String[] params = queryString.split("&"); for (String param : params) { String[] p = param.split("="); map.put(p[0], p[1]); } } catch (Exception e) { } return map; } }
ae74b30599bd8c3b26c812646492715c1a716196
[ "Markdown", "SQL", "Java" ]
3
SQL
SachinthaPrabash/paf-_project
2ba7ec5e203a8a41e858794e36a87a5a5ddf811d
3c51b03fdff073e524f1e11778ae0b32e079d40b
refs/heads/master
<file_sep>/*This is example app.js, some code parts has been deleted*/ require('./scripts/bootstrap') require('./scripts/polyfills.js') require('./scripts/bootstrap-datetimepicker') require('./scripts/bootstrap-select') require('./scripts/jquery.datatables') require('./scripts/bootstrap-checkbox-radio-switch-tags') require('./scripts/jquery.easypiechart.min') require('./scripts/chartist.min') require('./scripts/bootstrap-notify') require('./scripts/sweetalert2') require('./scripts/jquery-jvectormap') require('./scripts/jquery.bootstrap.wizard.min') require('./scripts/bootstrap-table') require('./scripts/fullcalendar.min') require('./scripts/demo') require('../../../node_modules/sweetalert2/dist/sweetalert2.min') require('parsleyjs') require('./classes/LinkParser.js') /*This is example app.js, some code parts has been deleted*/ import Vue from 'vue' import Resource from 'vue-resource' import PortalVue from 'portal-vue' import Modal from './components/common/utilities/Modal.vue' Vue.use(Resource) import BootstrapVue from 'bootstrap-vue' Vue.use(BootstrapVue) const VueInputMask = require('vue-inputmask').default Vue.use(VueInputMask) import VeeValidate from 'vee-validate' import Dictionary from './dictionary' Vue.use(VeeValidate) VeeValidate.Validator.localize('en', Dictionary.en) import store from './store/index' //import vuex import VTooltip from 'v-tooltip' import VModal from 'vue-js-modal' import preloaderPopup from './components/common/preloader-popup.vue' import Vtabs from './components/Vtabs.vue' import Toastr from 'vue-toastr' require('vue-toastr/src/vue-toastr.scss') var VueScrollTo = require('vue-scrollto') Vue.use(VueScrollTo) /*This is example app.js, some code parts has been deleted*/ Vue.component('preloader-popup', preloaderPopup) Vue.component('v-tabs', Vtabs) Vue.component('car-error-modal', require('./components/common/carErrorModal.vue')) Vue.component('a-select', require('./components/common/a-select.vue')) Vue.component('information-page', require('./components/information/Information.vue')) Vue.component('footer-element', require('./components/footer-element.vue')) Vue.component('nav-button', require('./components/navButton.vue')) Vue.component('meetAlert', require('./components/start/MeetingForm.vue')) Vue.component('unit-checkbox', require('./components/common/unitCheckbox.vue')) Vue.component('checkbox-group', require('./components/common/checkboxGroup.vue')) Vue.component('circular-progress-bar', require('./components/common/circularProgressBar.vue')) Vue.component('u-radio', require('./components/common/uRadio.vue')) Vue.component('Datepicker', require('./components/common/Datepicker')) Vue.component('error-alert', require('./components/common/errorAlert.vue')) Vue.component('edit-btn', require('./components/common/utilities/crud/EditBtn.vue')) Vue.component('store-btn', require('./components/common/utilities/crud/StoreBtn.vue')) Vue.component('delete-btn', require('./components/common/utilities/crud/DeleteBtn.vue')) Vue.component('util-modal', Modal) import 'babel-polyfill' import Vuetify from 'vuetify' import 'vuetify/dist/vuetify.min.css' Vue.use(Vuetify) Vue.use(Resource) Vue.use(VeeValidate) Vue.use(VTooltip) Vue.use(VModal) Vue.use(Toastr) Vue.use(PortalVue) /*This is example app.js, some code parts has been deleted*/ export const eventHub = new Vue() export const vm = new Vue() const app = new Vue({ el: '#app', store }) <file_sep>### This is code parts (Vue.js), based by data from api project - - - This is improvement by contracts, where in all contracts folder has been two forms, store and edit. In result we have one form by one contract, where if contract 'id' exist data will update, else in DB stored new contract. This code can be improved more, but time was limited for this task. Also look common and adapters folder. Component Datepicker.vue used in contract form Code in file app.js shown for example, some code parts has been deleted.<file_sep>import * as Moment from 'moment' import * as MomentRange from 'moment-range' const moment = MomentRange.extendMoment(Moment) moment.locale('nl') export default class DateTime { /*** * @param {string} outFormat * @param {object} date * @returns {string} */ static getDate(outFormat = 'DD-MM-YYYY', date = new Date()) { return this.moment(date, 'YYYY-MM-DD').format(outFormat) } /*** * * @param {string} date * @param {string} inFormat * @return {*} */ static getDayOfWeek(date = new Date(), inFormat = 'YYYY-MM-DD HH:mm') { return this.getMoment(date, inFormat).day() } /*** * * @param {string} IsoDate * @param {string} outFormat * @returns {string} */ static convertFromIso(IsoDate, outFormat = 'YYYY-MM-DD HH:mm:ss') { return this.moment(IsoDate).format(outFormat) } /*** * @param {string} date * @param {string} inFormat * @param {string} outFormat * @returns {string} */ static convertFromTo(date, inFormat, outFormat) { return this.moment(date, inFormat).format(outFormat) } /** * * @returns {string} */ static getCurrentIsoDate() { return this.moment().format() } /** * * @param {string} date * @param {string} inFormat * @param {string} outFormat * @return {moment} moment */ static getCurrentDateTime(date = new Date(), inFormat = 'YYYY-MM-DD HH:mm', outFormat = 'YYYY-MM-DD HH:mm') { return this.moment(date, inFormat).format(outFormat) } /** * * @param {string} isoDate * @returns {string} */ static convertToIso(isoDate) { if (!this.moment(isoDate).isValid()) { throw new Error(`Datetime format is not valid: ${isoDate}`) } if (isoDate.includes('T')) { return isoDate } return new Date(isoDate).toISOString() } /*** * @return {moment.Moment} */ static get moment() { return moment } /*** * * @param {string} date * @param {string} inFormat * @param {string} start [year|month|quarter|week|isoWeek|day|date|hour|minute|second] * @return {moment} moment */ static getMoment(date = new Date(), inFormat = 'YYYY-MM-DD HH:mm', start = '') { return this.moment(date, inFormat).startOf(start) } /*** * * @param {string} dateBefore * @param {Date} dateAfter * @param {string} precision [year|month|week|isoWeek|day|hour|minute|second] * @param {string} inFormat * @returns {boolean} */ static isAfter( dateBefore, dateAfter = new Date(), precision = 'second', inFormat = 'YYYY-MM-DD' ) { return this.moment(dateBefore, inFormat).isSameOrAfter(this.moment(dateAfter, inFormat), precision) } /*** * @param {string} start in date format * @param {string} end in date format * @param {string} format * @param {string} range_by * @return {array} */ static getRange(start, end, format = 'DD-MM-YYYY', range_by = 'days') { let range = moment.range(moment(start, format), moment(end, format)) let time_units = Array.from(range.by(range_by)).map(m => m.format(format)) return time_units } }
14e967a1fd599b946157eec79bd33c67edc06c5e
[ "JavaScript", "Markdown" ]
3
JavaScript
artj0mm/components
0a88ecd3e0f99ab7ed6058435ccef48192017e52
0275f209a12ac33141aaca8978b48b9209f22831
refs/heads/master
<repo_name>HeadClot/Citadel<file_sep>/Assets/Scripts/EmailButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class EmailButton : MonoBehaviour { [SerializeField] private GameObject iconman; [SerializeField] private GameObject mailtitleman; [SerializeField] private int mailButtonIndex; [SerializeField] private AudioSource SFX; // assign in the editor [SerializeField] private AudioClip SFXClip; // assign in the editor [SerializeField] private CenterTabButtons CenterTabButtonsManager; // assign in the editor private int invslot; void MailInvClick () { invslot = EmailTitle.Instance.emailInventoryIndices[mailButtonIndex]; if (invslot < 0) return; //mailtitleman.GetComponent<MailTitleManager>().SetMailTitle(invslot); //Set Mail Title Text for MFD EmailCurrent.Instance.emailCurrent = mailButtonIndex; //Set current mail to be played EmailTitle.Instance.SFX.clip = EmailTitle.Instance.emailVoiceClips[EmailCurrent.Instance.emailCurrent]; EmailTitle.Instance.SFX.Play (); CenterTabButtonsManager.TabButtonClick (5); } [SerializeField] private Button MailButton = null; // assign in the editor void Start() { MailButton.onClick.AddListener(() => { MailInvClick();}); } }<file_sep>/Assets/Standard Assets/Effects/ImageEffects/Scripts/BerserkEffect.cs using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [AddComponentMenu("Image Effects/Color Adjustments/Berserk Effect")] public class BerserkEffect : ImageEffectBase { public Texture2D swapTexture; public float effectStrength = 3f; public float lothreshold = 0.0f; public float hithreshold = 0.25f; private float oldeffectStrength; private float oldlothreshold; private float oldhithreshold; void Awake () { oldeffectStrength = effectStrength; oldlothreshold = lothreshold; oldhithreshold = hithreshold; } public void Reset() { effectStrength = oldeffectStrength; lothreshold = oldlothreshold; hithreshold = oldhithreshold; } void OnRenderImage (RenderTexture source, RenderTexture destination) { material.SetTexture("_SwapTex", swapTexture); material.SetFloat("_EffectStrength", effectStrength); if (lothreshold < 0f) lothreshold = 0f; if (hithreshold > 1f) hithreshold = 1f; if (hithreshold < 0) hithreshold = 0; if (lothreshold > hithreshold || hithreshold < lothreshold) lothreshold = hithreshold; material.SetFloat("_LowThreshold", lothreshold); material.SetFloat("_HighThreshold", hithreshold); Graphics.Blit (source, destination, material); } } } <file_sep>/Assets/Scripts/GetInput.cs using System.Collections; using System.Collections.Generic; using UnityEngine; // Master input handling functions from configuration public class GetInput : MonoBehaviour { public static GetInput a; public bool isCapsLockOn; void Awake() { a = this; isCapsLockOn = false; } public bool Forward() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[0]])) return true; else return false; } public bool StrafeLeft() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[1]])) return true; else return false; } public bool Backpedal() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[2]])) return true; else return false; } public bool StrafeRight() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[3]])) return true; else return false; } public bool Jump() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[4]])) return true; else return false; } public bool Crouch() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[5]])) return true; else return false; } public bool Prone() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[6]])) return true; else return false; } public bool LeanLeft() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[7]])) return true; else return false; } public bool LeanRight() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[8]])) return true; else return false; } public bool Sprint() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[9]])) return true; else return false; } public bool ToggleSprint() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[10]])) return true; else return false; } public bool TurnLeft() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[11]])) return true; else return false; } public bool TurnRight() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[12]])) return true; else return false; } public bool LookUp() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[13]])) return true; else return false; } public bool LookDown() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[14]])) return true; else return false; } public bool RecentLog() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[15]])) return true; else return false; } public bool Biomonitor() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[16]])) return true; else return false; } public bool Sensaround() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[17]])) return true; else return false; } public bool Lantern() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[18]])) return true; else return false; } public bool Shield() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[19]])) return true; else return false; } public bool Infrared() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[20]])) return true; else return false; } public bool Email() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[21]])) return true; else return false; } public bool Booster() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[22]])) return true; else return false; } public bool Jumpjets() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[23]])) return true; else return false; } public bool Attack(bool isFullAuto) { if (isFullAuto) { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[24]])) return true; else return false; } else { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[24]])) return true; else return false; } } public bool Use() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[25]])) return true; else return false; } public bool Menu() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[26]])) return true; else return false; } public bool ToggleMode() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[27]])) return true; else return false; } public bool Reload() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[28]])) return true; else return false; } public bool WeaponCycUp() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[29]])) return true; else return false; } public bool WeaponCycDown() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[30]])) return true; else return false; } public bool Grenade() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[31]])) return true; else return false; } public bool GrenadeCycUp() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[32]])) return true; else return false; } public bool GrenadeCycDown() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[33]])) return true; else return false; } public bool HardwareCycUp() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[34]])) return true; else return false; } public bool HardwareCycDown() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[35]])) return true; else return false; } public bool Patch() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[36]])) return true; else return false; } public bool PatchCycUp() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[37]])) return true; else return false; } public bool PatchCycDown() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[38]])) return true; else return false; } public bool Map() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[39]])) return true; else return false; } public bool SwimUp() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[40]])) return true; else return false; } public bool SwimDn() { if (Input.GetKey(Const.a.InputValues[Const.a.InputCodeSettings[41]])) return true; else return false; } public bool SwapAmmoType() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[42]])) return true; else return false; } public bool Console() { if (Input.GetKeyDown(Const.a.InputValues[Const.a.InputCodeSettings[43]])) return true; else return false; } public bool CapsLockOn() { if (Input.GetKeyDown(KeyCode.CapsLock)) isCapsLockOn = !isCapsLockOn; return isCapsLockOn; } public bool Numpad0() { if (Input.GetKeyDown(KeyCode.Keypad0)) return true; else return false; } public bool Numpad1() { if (Input.GetKeyDown(KeyCode.Keypad1)) return true; else return false; } public bool Numpad2() { if (Input.GetKeyDown(KeyCode.Keypad2)) return true; else return false; } public bool Numpad3() { if (Input.GetKeyDown(KeyCode.Keypad3)) return true; else return false; } public bool Numpad4() { if (Input.GetKeyDown(KeyCode.Keypad4)) return true; else return false; } public bool Numpad5() { if (Input.GetKeyDown(KeyCode.Keypad5)) return true; else return false; } public bool Numpad6() { if (Input.GetKeyDown(KeyCode.Keypad6)) return true; else return false; } public bool Numpad7() { if (Input.GetKeyDown(KeyCode.Keypad7)) return true; else return false; } public bool Numpad8() { if (Input.GetKeyDown(KeyCode.Keypad8)) return true; else return false; } public bool Numpad9() { if (Input.GetKeyDown(KeyCode.Keypad9)) return true; else return false; } public bool NumpadPeriod() { if (Input.GetKeyDown(KeyCode.KeypadPeriod)) return true; else return false; } public bool NumpadMinus() { if (Input.GetKeyDown(KeyCode.KeypadMinus)) return true; else return false; } } <file_sep>/Assets/Scripts/GrenadeInventory.cs using UnityEngine; using System.Collections; public class GrenadeInventory : MonoBehaviour { public int[] grenAmmo; public static GrenadeInventory GrenadeInvInstance; void Awake () { GrenadeInvInstance = this; for (int i= 0; i<7; i++) { GrenadeInvInstance.grenAmmo[i] = 0; } } } <file_sep>/Assets/Scripts/TeleportTouch.cs using UnityEngine; using System.Collections; public class TeleportTouch : MonoBehaviour { public Transform targetDestination; // assign in the editor public bool playSound; public AudioClip SoundFX; public GameObject teleportFX; public float justUsed = 0f; private AudioSource SoundFXSource; void Awake () { SoundFXSource = GetComponent<AudioSource>(); } void OnTriggerEnter ( Collider col ) { if ((col.gameObject.tag == "Player") && (col.gameObject.GetComponent<PlayerHealth>().hm.health > 0f) && (justUsed < Time.time)) { teleportFX.SetActive(true); col.transform.position = targetDestination.position; targetDestination.transform.gameObject.GetComponent<TeleportTouch>().justUsed = Time.time + 1.0f; if (playSound) SoundFXSource.PlayOneShot(SoundFX); } } }<file_sep>/Assets/Scripts/GrenadeButtonsManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class GrenadeButtonsManager : MonoBehaviour { [SerializeField] private GameObject[] grenButtons; [SerializeField] private GameObject[] grenCountsText; void Update() { for (int i=0; i<7; i++) { if (GrenadeInventory.GrenadeInvInstance.grenAmmo[i] > 0) { if (!grenButtons[i].activeInHierarchy) grenButtons[i].SetActive(true); if (!grenCountsText[i].activeInHierarchy) grenCountsText[i].SetActive(true); } else { if (grenButtons[i].activeInHierarchy) grenButtons[i].SetActive(false); if (grenCountsText[i].activeInHierarchy) grenCountsText[i].SetActive(false); } } } }<file_sep>/Assets/Scripts/GeneralInvCurrent.cs using UnityEngine; using System.Collections; public class GeneralInvCurrent : MonoBehaviour { public int generalInvCurrent = new int(); public int generalInvIndex = new int(); public int[] generalInventoryIndices = new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13}; public static GeneralInvCurrent GeneralInvInstance; public GameObject vaporizeButton; public GameObject activateButton; public GameObject applyButton; void Awake() { GeneralInvInstance = this; GeneralInvInstance.generalInvCurrent = 0; // Current slot in the general inventory (14 slots) GeneralInvInstance.generalInvIndex = 0; // Current index to the item look-up table } void Update() { bool setVaporizeButtonOn = false; bool setActivateButtonOn = false; bool setApplyButtonOn = false; switch( GeneralInvInstance.generalInvCurrent) { case 0: setVaporizeButtonOn = true; break; case 1: setVaporizeButtonOn = true; break; case 2: setVaporizeButtonOn = true; break; case 3: setVaporizeButtonOn = true; break; case 4: setVaporizeButtonOn = true; break; case 5: setVaporizeButtonOn = true; break; case 33: setVaporizeButtonOn = true; break; case 34: setVaporizeButtonOn = true; break; case 35: setVaporizeButtonOn = true; break; case 52: setActivateButtonOn = true; break; case 53: setActivateButtonOn = true; break; case 55: setActivateButtonOn = true; break; case 58: setVaporizeButtonOn = true; break; case 62: setVaporizeButtonOn = true; break; } switch (PatchCurrent.PatchInstance.patchCurrent) { case 0: setApplyButtonOn = true; break; case 1: setApplyButtonOn = true; break; case 2: setApplyButtonOn = true; break; case 3: setApplyButtonOn = true; break; case 4: setApplyButtonOn = true; break; case 5: setApplyButtonOn = true; break; case 6: setApplyButtonOn = true; break; } if (setVaporizeButtonOn) vaporizeButton.SetActive(true); else vaporizeButton.SetActive(false); if (setActivateButtonOn) activateButton.SetActive(true); else activateButton.SetActive(false); if (setApplyButtonOn) applyButton.SetActive(true); else applyButton.SetActive(false); } } <file_sep>/Assets/Scripts/EmailTitle.cs using UnityEngine; using System.Collections; public class EmailTitle : MonoBehaviour { public string[] emailInventoryTitle; public int[] emailInventoryIndices; [SerializeField] public string[] emailInvTitleSource; public static EmailTitle Instance; public AudioClip[] emailVoiceClips = null; // assign in the editor [SerializeField] public AudioSource SFX = null; // assign in the editor void Awake() { Instance = this; Instance.emailInventoryTitle = new string[]{"SHODAN-06.NOV.72","Rebecca-1","Dummy","","","",""};; Instance.emailInventoryIndices = new int[]{1,2,3,4,5,6,7}; Instance.emailVoiceClips = emailVoiceClips; } } <file_sep>/Assets/Scripts/SaveObject.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SaveObject : MonoBehaviour { //public string SaveID; public int SaveID; void Start () { //string x,y,z; //x = transform.localPosition.x.ToString("0000.00000"); //y = transform.localPosition.y.ToString("0000.00000"); //z = transform.localPosition.z.ToString("0000.00000"); //SaveID = (x + y + z); SaveID = gameObject.GetInstanceID(); //Const.sprint("Saveable Object has ID# of: " + SaveID.ToString()); } } <file_sep>/Assets/Scripts/HealingFX.cs using UnityEngine; using System.Collections; public class HealingFX : MonoBehaviour { public float activeTime = 0.1f; private float effectFinished; void OnEnable () { effectFinished = Time.time + activeTime; } void Deactivate () { gameObject.SetActive(false); } void Update () { if (effectFinished < Time.time) { Deactivate(); } } } <file_sep>/Assets/Scripts/ConfigSlider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigSlider : MonoBehaviour { private Slider slideControl; public int index; void Start () { slideControl = GetComponent<Slider>(); if (slideControl == null) { Debug.Log("ERROR: No slider for object with ConfigSlider script"); } switch(index) { case 0: slideControl.value = Const.a.GraphicsFOV; break; case 1: slideControl.value = Const.a.GraphicsGamma; break; case 2: slideControl.value = Const.a.AudioVolumeMaster; break; case 3: slideControl.value = Const.a.AudioVolumeMusic; break; case 4: slideControl.value = Const.a.AudioVolumeMessage; break; case 5: slideControl.value = Const.a.AudioVolumeEffects; break; } } public void SetValue() { switch(index) { case 0: Const.a.GraphicsFOV = (int)slideControl.value; Const.a.SetFOV(); break; case 1: Const.a.GraphicsGamma = (int)slideControl.value; Const.a.SetBrightness(); break; case 2: Const.a.AudioVolumeMaster = (int)slideControl.value; Const.a.SetVolume(); break; case 3: Const.a.AudioVolumeMusic = (int)slideControl.value; Const.a.SetVolume(); break; case 4: Const.a.AudioVolumeMessage = (int)slideControl.value; Const.a.SetVolume(); break; case 5: Const.a.AudioVolumeEffects = (int)slideControl.value; Const.a.SetVolume(); break; } Const.a.WriteConfig(); } } <file_sep>/README.md # Citadel Started 7/6/2015 Released -ETA 9/22/18- The fan System Shock remake.  The goal is to recreate the original closely while enhancing it with 3D models instead of 2D sprites, 3D details to the station in and out, particle effects, and subtle sound effect additions.  After releasing a playable version, focus will shift to making mod and mapping tools. PLEASE submit bug and feature requests here on this github. If you would like to join and aid in any capacity, please email <NAME>, the main author, at <EMAIL> Special thanks to Looking Glass Studios and Origin Games for the original 1994 product. Special thanks to Night Dive Studios for allowing this project to live on unhindered. DISCLAIMER: Citadel is work in progress. That means features may be broken, missing, or not in a final state of polish. Also, this means that the game is not in an "installable" state and must be "built" in Unity OR ran inside the Unity editor. Also, the github version is always updated after I get to a reasonable "stopping point" for adding to the game. This means Github is missing certain features that are actually closed in the Issues list on here (I'll change this at some point where I don't close bugs for instance until after the commit is done for that bug.) Continue for your own fun. Install Instructions: 1. Download the Github repository. 2. Install Unity 2019.1.0.0f2: https://unity3d.com/get-unity/download/archive 3. Extract all into a folder and name of your liking. 4. Open Unity. 5. Click on Open Other or Open Project (the name if the button changes depending on whether it is a fresh install or already installed.) 6. Select the top folder where you extracted the game files. It must be only one level above the Assets folder, e.g. Citadel-v0.1/Assets. 7. Wait as Unity loads in the project and reimports all assets and auto-compiles the script code (may take an hour for the very first time). 8. Either A. Click the play button at the top of the screen (it's a triangle), or B. In the top menu bar go to File->Build & Run. <file_sep>/Assets/Scripts/LogDataTabContainerManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LogDataTabContainerManager : MonoBehaviour { public Text logName; public Text logSender; public Text logSubject; public void SendLogData(int referenceIndex) { logName.text = Const.a.audiologNames[referenceIndex]; logSender.text = Const.a.audiologSenders[referenceIndex]; logSubject.text = Const.a.audiologSubjects[referenceIndex]; } } <file_sep>/Assets/Scripts/LogTableContentsButtonsManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class LogTableContentsButtonsManager : MonoBehaviour { [SerializeField] private GameObject[] LogButtons; void Update() { for (int i=0; i<10; i++) { // Only show category buttons for levels we have logs from if (LogInventory.a.numLogsFromLevel[i] > 0) { LogButtons[i].SetActive(true); } else { LogButtons[i].SetActive(false); } } } } <file_sep>/Assets/Scripts/KeypadElevator.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class KeypadElevator : MonoBehaviour { public int securityThreshhold = 100; // if security level is not below this level, this is unusable public DataTab dataTabResetter; public GameObject elevatorControl; public GameObject[] elevatorButtonHandlers; public GameObject[] targetDestination; public Door linkedDoor; public bool[] buttonsEnabled; public bool[] buttonsDarkened; public string[] buttonText; public int currentFloor; public AudioClip SFX; private float disconnectDist; public float useDist = 2f; private AudioSource SFXSource; private bool padInUse; private GameObject levelManager; private GameObject playerCapsule; private GameObject playerCamera; private float distanceCheck; private int defIndex = 0; private int maxIndex = 8; private int four = 4; private float tickFinished; public float tickSecs = 0.1f; public string blockedBySecurityText = "Blocked by SHODAN level Security."; void Awake () { levelManager = GameObject.Find("LevelManager"); if (levelManager == null) Const.sprint("Warning: Could not find object 'LevelManager' in scene",playerCapsule.transform.parent.gameObject); if (targetDestination == null) Const.sprint("Warning: Could not find target destination for elevator keypad" + gameObject.name,playerCapsule.transform.parent.gameObject); } void Start () { padInUse = false; disconnectDist = Const.a.frobDistance; SFXSource = GetComponent<AudioSource>(); for (int i=defIndex;i<maxIndex;i++) { elevatorButtonHandlers[i].GetComponent<ElevatorButton>().SetTooFarFalse(); } tickFinished = Time.time + tickSecs + Random.Range(0.1f,0.5f); // Random start to prevent tick calculations from bunching up in one frame } public void Use (UseData ud) { if (LevelManager.a.levelSecurity[LevelManager.a.currentLevel] > securityThreshhold) { Const.sprint(blockedBySecurityText,ud.owner); MFDManager.a.BlockedBySecurity(); return; } padInUse = true; SFXSource.PlayOneShot(SFX); dataTabResetter.Reset(); elevatorControl.SetActive(true); playerCapsule = ud.owner.GetComponent<PlayerReferenceManager>().playerCapsule; // Get player capsule of player using this pad playerCamera = ud.owner.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera; for (int i=defIndex;i<maxIndex;i++) { elevatorControl.GetComponent<ElevatorKeypad>().buttonsEnabled[i] = buttonsEnabled[i]; elevatorControl.GetComponent<ElevatorKeypad>().buttonsDarkened[i] = buttonsDarkened[i]; elevatorControl.GetComponent<ElevatorKeypad>().buttonText[i] = buttonText[i]; elevatorControl.GetComponent<ElevatorKeypad>().targetDestination[i] = targetDestination[i]; } elevatorControl.GetComponent<ElevatorKeypad>().currentFloor = currentFloor; elevatorControl.GetComponent<ElevatorKeypad>().activeKeypad = gameObject; if (playerCamera.GetComponent<MouseLookScript>().inventoryMode == false) playerCamera.GetComponent<MouseLookScript>().ToggleInventoryMode(); MFDManager.a.OpenTab(four,true,MFDManager.TabMSG.Elevator,defIndex,MFDManager.handedness.LeftHand); } void Update () { // limit checks to only once every tickSecs to prevent CPU overload if (tickFinished < Time.time) { if (padInUse) { distanceCheck = Vector3.Distance (playerCapsule.transform.position, gameObject.transform.position); if (distanceCheck > disconnectDist) { padInUse = false; MFDManager.a.TurnOffElevatorPad (); } else { for (int i = defIndex; i < maxIndex; i++) { if (distanceCheck < useDist) { if (MFDManager.a.GetElevatorControlActiveState ()) elevatorButtonHandlers [i].GetComponent<ElevatorButton> ().SetTooFarFalse (); } else { if (MFDManager.a.GetElevatorControlActiveState ()) elevatorButtonHandlers [i].GetComponent<ElevatorButton> ().SetTooFarTrue (); } if (linkedDoor.doorOpen == Door.doorState.Closed) { if (MFDManager.a.GetElevatorControlActiveState ()) elevatorButtonHandlers [i].GetComponent<ElevatorButton> ().doorOpen = false; } else { if (MFDManager.a.GetElevatorControlActiveState ()) elevatorButtonHandlers [i].GetComponent<ElevatorButton> ().doorOpen = true; } } } } } } } <file_sep>/Assets/Scripts/PatchButton.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class PatchButton: MonoBehaviour { public int PatchButtonIndex; public int useableItemIndex; public MFDManager mfdManager; public PlayerPatch pps; public void DoubleClick() { pps.ActivatePatch(useableItemIndex); } public void PatchInvClick () { mfdManager.SendInfoToItemTab(useableItemIndex); PatchCurrent.PatchInstance.patchCurrent = PatchButtonIndex; //Set current for (int i = 0; i < 7; i++) { PatchCurrent.PatchInstance.patchCountsTextObjects [i].color = Const.a.ssGreenText; } PatchCurrent.PatchInstance.patchCountsTextObjects[PatchButtonIndex].color = Const.a.ssYellowText; } void Start() { GetComponent<Button>().onClick.AddListener(() => { PatchInvClick(); }); } }<file_sep>/Assets/Scripts/HardwareInventory.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HardwareInventory : MonoBehaviour { public bool[] hasHardware; public int[] hardwareVersion; public int[] hardwareVersionSetting; public int[] hardwareInventoryIndexRef; public string[] hardwareInventoryText; public static HardwareInventory a; public HardwareInventoryButtonsManager hwButtonsManager; void Awake() { a = this; for (int i = 0; i < 14; i++) { a.hardwareInventoryIndexRef[i] = -1; a.hardwareVersionSetting [i] = 1; } } } <file_sep>/Assets/Scripts/GeneralInvText.cs using UnityEngine; using UnityEngine.UI; using System.Collections; [System.Serializable] public class GeneralInvText : MonoBehaviour { Text text; public int slotnum = 0; private int referenceIndex = -1; void Start () { text = GetComponent<Text>(); } void Update () { referenceIndex = gameObject.transform.GetComponentInParent<GeneralInvButton>().useableItemIndex; if (referenceIndex > -1) { text.text = Const.a.useableItemsNameText[referenceIndex]; } else { text.text = string.Empty; } if (slotnum == GeneralInvCurrent.GeneralInvInstance.generalInvCurrent) { text.color = Const.a.ssYellowText; // Yellow } else { text.color = Const.a.ssGreenText; // Green } } }<file_sep>/Assets/Scripts/MultiMediaTabManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class MultiMediaTabManager : MonoBehaviour { public GameObject startingSubTab; public GameObject secondaryTab1; public GameObject secondaryTab2; public GameObject emailTab; public GameObject dataTab; public GameObject headerLabel; public void ResetTabs() { startingSubTab.SetActive(false); secondaryTab1.SetActive(false); secondaryTab2.SetActive(false); emailTab.SetActive(false); dataTab.SetActive(false); headerLabel.GetComponent<Text>().text = System.String.Empty; } public void OpenLogTableContents() { ResetTabs(); startingSubTab.SetActive(true); headerLabel.GetComponent<Text>().text = "LOGS"; } public void OpenLogsLevelFolder(int curlevel) { ResetTabs(); secondaryTab1.SetActive(true); headerLabel.GetComponent<Text>().text = "Level " + curlevel.ToString() + " Logs"; secondaryTab1.GetComponent<LogContentsButtonsManager>().currentLevelFolder = curlevel; secondaryTab1.GetComponent<LogContentsButtonsManager>().InitializeLogsFromLevelIntoFolder(); } public void OpenLogTextReader() { ResetTabs(); secondaryTab2.SetActive(true); } public void OpenEmailTableContents() { ResetTabs(); emailTab.SetActive(true); headerLabel.GetComponent<Text>().text = "EMAIL"; } public void OpenDataTableContents() { ResetTabs(); dataTab.SetActive(true); headerLabel.GetComponent<Text>().text = "DATA"; } } <file_sep>/Assets/Scripts/NPC_Hopper.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NPC_Hopper : MonoBehaviour { public bool visitWaypointsRandomly = false; public bool inFront = false; public bool goIntoPain = false; public int index = 14; // NPC reference index for looking up constants in tables in Const.cs public enum collisionType{None,Box,Capsule,Sphere,Mesh}; public collisionType normalCollider; public collisionType corpseCollider; public Const.aiState currentState; public float fieldOfViewAngle = 160f; public float fieldOfViewAttack = 80f; public float distToSeeWhenBehind = 2.5f; public float sightRange = 50f; public float walkSpeed = 0.8f; public float runSpeed = 0.8f; public float proj1Range = 17.92f; public float rangeToEnemy = 0f; public float timeToPain = 2f; // time between going into pain animation public float timeBetweenPain = 5f; public float timeTillDead = 1.5f; public float timeBetweenProj1 = 1f; public float changeEnemyTime = 3f; // Time before enemy will switch to different attacker public float timeToFire = 1f; public float delayBeforeFire = 0.5f; public float firingFinished; public float attackFinished; public float fireDelayFinished; public float yawSpeed = 50f; public float hopForce = 5f; public Vector3 navigationTargetPosition; public Vector3 idealTransformForward; [HideInInspector] public GameObject attacker; public GameObject enemy; public GameObject firePoint; public GameObject normalBody; public GameObject collisionAid1; public GameObject collisionAid2; public GameObject deathBody; public GameObject targetEndHelper; //public GameObject[] gibs; public Transform[] walkWaypoints; // point(s) for NPC to walk to when roaming or patrolling public AudioClip SFXIdle; public AudioClip SFXFootstep; public AudioClip SFXSightSound; public AudioClip SFXAttack1; public AudioClip SFXPainClip; public AudioClip SFXDeathClip; public AudioClip SFXInspect; public AudioClip SFXInteracting; private bool hasSFX; private bool firstSighting; private bool dyingSetup; private bool painMade; private bool hadEnemy; private bool dying; private bool hopDone; private int nextPointIndex; //private int currentWaypoint; private enum painSelection{Pain1,Pain2,Pain3}; private painSelection currentPainAnim; private float idleTime; //private float timeTillEnemyChangeFinished; private float timeTillDeadFinished; //private float timeTillPainFinished; private float painFinished; private float tick; private float tickFinished; private float lastHealth; private Vector3 fireEndPoint; private AudioSource SFX; //private NavMeshAgent nav; private Animation anim; private Rigidbody rbody; private HealthManager healthManager; private BoxCollider boxCollider; private CapsuleCollider capsuleCollider; private SphereCollider sphereCollider; private MeshCollider meshCollider; void Start () { healthManager = GetComponent<HealthManager>(); rbody = GetComponent<Rigidbody>(); SFX = GetComponent<AudioSource>(); anim = GetComponent<Animation>(); //Setup colliders for NPC and its corpse if (normalCollider == corpseCollider) { Debug.Log("ERROR: normalCollider and corpseCollider cannot be the same on NPC!"); return; } switch(normalCollider) { case collisionType.Box: boxCollider = GetComponent<BoxCollider>(); boxCollider.enabled = true; break; case collisionType.Sphere: sphereCollider = GetComponent<SphereCollider>(); sphereCollider.enabled = true; break; case collisionType.Mesh: meshCollider = GetComponent<MeshCollider>(); meshCollider.enabled = true; break; case collisionType.Capsule: capsuleCollider = GetComponent<CapsuleCollider>(); capsuleCollider.enabled = true; break; } switch(corpseCollider) { case collisionType.Box: boxCollider = GetComponent<BoxCollider>(); boxCollider.enabled = false; break; case collisionType.Sphere: sphereCollider = GetComponent<SphereCollider>(); sphereCollider.enabled = false; break; case collisionType.Mesh: meshCollider = GetComponent<MeshCollider>(); meshCollider.enabled = false; break; case collisionType.Capsule: capsuleCollider = GetComponent<CapsuleCollider>(); capsuleCollider.enabled = false; break; } currentState = Const.aiState.Idle; //currentWaypoint = 0; tick = 0.05f; // Think every 0.05f seconds to save on CPU idealTransformForward = transform.forward; enemy = null; attacker = null; firstSighting = true; goIntoPain = false; dyingSetup = false; hopDone = false; idleTime = Time.time + Random.Range(3f,10f); attackFinished = Time.time + 1f; tickFinished = Time.time + tick; timeTillDeadFinished = Time.time; firingFinished = Time.time; painFinished = Time.time; fireDelayFinished = Time.time; currentPainAnim = painSelection.Pain1; if (SFX == null) { Debug.Log ("WARNING: No audio source for npc at: " + transform.position.x.ToString () + ", " + transform.position.y.ToString () + ", " + transform.position.z + "."); hasSFX = false; } else { hasSFX = true; } if (healthManager.health > 0) { if (walkWaypoints.Length > 0 && walkWaypoints[0] != null) { currentState = Const.aiState.Walk; // If waypoints are set, start walking to them } else { currentState = Const.aiState.Idle; // Default to idle } } deathBody.SetActive(false); normalBody.SetActive(true); collisionAid1.SetActive(true); collisionAid2.SetActive(true); } void Update () { if (PauseScript.a != null && PauseScript.a.paused) { return; // don't do any checks or anything else...we're paused! } // Only think every tick seconds to save on CPU and prevent race conditions if (tickFinished < Time.time) { Think(); tickFinished = Time.time + tick; } } void Think () { CheckAndUpdateState (); switch (currentState) { case Const.aiState.Idle: Idle(); break; //case Const.aiState.Walk: Walk(); break; case Const.aiState.Run: Run(); break; case Const.aiState.Attack1: Attack(); break; case Const.aiState.Pain: Pain(); break; case Const.aiState.Dying: Dying(); break; default: break; } } // All state changes go in here. Check for stuff. See what we need to be doing. Need to change? void CheckAndUpdateState() { if (currentState == Const.aiState.Dead) return; // Check to see if we got hurt if (healthManager.health < lastHealth) { if (healthManager.health <= 0) { currentState = Const.aiState.Dying; return; } lastHealth = healthManager.health; // Make initial sight sound if we aren't running, attacking, or already in pain if (currentState != Const.aiState.Run || currentState != Const.aiState.Attack1 || currentState != Const.aiState.Attack2 || currentState != Const.aiState.Attack3 || currentState != Const.aiState.Pain) SightSound (); enemy = healthManager.attacker; currentState = Const.aiState.Run; return; } else { lastHealth = healthManager.health; } // Take a look around for enemies if (enemy == null) { // we don't have an enemy yet so let's look to see if we can see one if (CheckIfPlayerInSight ()) { currentState = Const.aiState.Run; // quit standing around and start fighting return; } } else { // We have an enemy now what... // Oh can we still see it? // Can I shoot it? // please?? // Can I melee it? // cherry on top? if (anim.IsPlaying ("Hop")) { if (anim ["Hop"].time > (0.69f * 1.55f) || anim ["Hop"].time < (0.09f)) { if (CheckIfEnemyInSight ()) { float dist = Vector3.Distance (transform.position, enemy.transform.position); // See if we are close enough to attack if (dist < proj1Range) { if (attackFinished < Time.time) { if (CheckIfEnemyInFront (enemy)) { inFront = true; firingFinished = Time.time + timeBetweenProj1; fireDelayFinished = Time.time + delayBeforeFire; fireEndPoint = enemy.transform.position; currentState = Const.aiState.Attack1; return; } else { inFront = false; } } } } } else { inFront = false; } } } } void Idle() { // Set animation state anim["Idle"].wrapMode = WrapMode.Loop; anim.Play("Idle"); // Play an idle sound if the idle sound timer has timed out if ((idleTime < Time.time) && (SFXIdle != null)) { SFX.PlayOneShot(SFXIdle); // play idle sound idleTime = Time.time + Random.Range(3f,10f); // reset the timer to keep idle sounds from playing repetitively } } void SightSound() { if (firstSighting) { firstSighting = false; if (hasSFX) SFX.PlayOneShot(SFXSightSound); } } /* void Walk() { nav.isStopped = false; nav.speed = walkSpeed; // Set animation state //anim.Play("Walk"); // Set waypoint to next waypoint when we get close enough to the current waypoint if (nav.remainingDistance < distanceTillClose) { currentWaypoint = nextPointIndex; if ((currentWaypoint == walkWaypoints.Length) || (walkWaypoints[currentWaypoint] == null)) {currentWaypoint = 0; nextPointIndex = 0;} // Wrap around } // Check to see if we got hurt if (healthManager.health < lastHealth) { if (healthManager.health <= 0) { currentState = Const.aiState.Dying; return; } currentState = Const.aiState.Run; return; } lastHealth = healthManager.health; nav.SetDestination(walkWaypoints[currentWaypoint].transform.position); // Walk nextPointIndex++; // Take a look around for enemies returnedEnemy = null; // reset temporary GameObject to hold any returned enemy we find if (CheckIfPlayerInSight(returnedEnemy)) { enemy = Const.a.player1.GetComponent<PlayerReferenceManager>().playerCapsule;; currentState = Const.aiState.Run; // quit standing around and start fighting return; } // I'm walkin', and waitin'...on the edge of my seat anticipating. }*/ void AI_Face(GameObject goalLocation) { Vector3 dir = (goalLocation.transform.position - transform.position).normalized; dir.y = 0f; Quaternion lookRot = Quaternion.LookRotation(dir,Vector3.up); transform.rotation = Quaternion.Slerp (transform.rotation, lookRot, tick * yawSpeed); // rotate as fast as we can towards goal position } void Run() { // Set animation state anim["Hop"].wrapMode = WrapMode.Loop; anim.Play ("Hop"); AI_Face (enemy); // turn and face your executioner // move it move it if (anim ["Hop"].time > (0.09f*1.55f)) { if (!hopDone) { hopDone = true; rbody.AddForce (transform.forward * hopForce); // moving forward! } } else { hopDone = false; } /* if (anim.IsPlaying ("Hop")) { if (anim ["Hop"].time > (0.69f * 1.55f) || anim ["Hop"].time < (0.09f)) { if (CheckIfEnemyInSight ()) { float dist = Vector3.Distance (transform.position, enemy.transform.position); // See if we are close enough to attack if (dist < proj1Range) { if (attackFinished < Time.time) { if (CheckIfEnemyInFront (enemy)) { inFront = true; firingFinished = Time.time + timeBetweenProj1; fireDelayFinished = Time.time + delayBeforeFire; fireEndPoint = enemy.transform.position; currentState = Const.aiState.Attack1; return; } else { inFront = false; } } } } } else { inFront = false; } }*/ } void Attack() { if (fireDelayFinished > Time.time) { anim.Play ("Idle"); anim ["Hop"].time = 0f; } if (fireDelayFinished < Time.time) { anim.Play ("Shoot"); AI_Face (enemy); if (firingFinished < Time.time) { currentState = Const.aiState.Run; return; } if (attackFinished < Time.time && firingFinished > Time.time && anim ["Shoot"].time > 0.1f) { if (SFXAttack1 != null) SFX.PlayOneShot (SFXAttack1); attackFinished = Time.time + timeBetweenProj1; bool useBlood = false; DamageData damageData = new DamageData (); RaycastHit tempHit = new RaycastHit (); Vector3 tempvec = Vector3.Normalize (fireEndPoint - firePoint.transform.position); Ray tempRay = new Ray (firePoint.transform.position, tempvec); if (Physics.Raycast (tempRay, out tempHit, 200f)) { HealthManager tempHM = tempHit.transform.gameObject.GetComponent<HealthManager> (); if (tempHit.transform.gameObject.GetComponent<HealthManager> () != null) { useBlood = true; } GameObject impact = Const.a.GetObjectFromPool (Const.PoolType.HopperImpact); if (impact != null) { impact.transform.position = tempHit.point; impact.transform.rotation = Quaternion.FromToRotation (Vector3.up, tempHit.normal); impact.SetActive (true); } // Determine blood type of hit target and spawn corresponding blood particle effect from the Const.Pool GameObject impact2 = Const.a.GetObjectFromPool (Const.PoolType.SparksSmall); if (useBlood) impact2 = GetImpactType (tempHM); if (impact2 != null) { impact2.transform.position = tempHit.point; impact2.transform.rotation = Quaternion.FromToRotation (Vector3.up, tempHit.normal); impact2.SetActive (true); } damageData.hit = tempHit; damageData.attacknormal = Vector3.Normalize (firePoint.transform.position - fireEndPoint); damageData.damage = Const.a.damagePerHitForWeapon [14]; tempHit.transform.gameObject.SendMessage ("TakeDamage", damageData, SendMessageOptions.DontRequireReceiver); GameObject lasertracer = Const.a.GetObjectFromPool (Const.PoolType.LaserLinesHopper); targetEndHelper.transform.position = tempHit.point; if (lasertracer != null) { lasertracer.SetActive (true); lasertracer.GetComponent<LaserDrawing> ().startPoint = firePoint.transform.position; lasertracer.GetComponent<LaserDrawing> ().endPoint = targetEndHelper.transform.position; } } } } } void Pain() { if (painFinished < Time.time) { if (SFXPainClip != null) SFX.PlayOneShot(SFXPainClip); float r = Random.Range(0,1); if (r < 0.34) { currentPainAnim = painSelection.Pain1; } else { if (r < 0.67) { currentPainAnim = painSelection.Pain2; } else { currentPainAnim = painSelection.Pain3; } } switch (currentPainAnim) { case painSelection.Pain1: anim.Play ("Pain1"); break; case painSelection.Pain2: anim.Play ("Pain2"); break; case painSelection.Pain3: anim.Play ("Pain3"); break; } painFinished = Time.time + timeBetweenPain; } } void Dying() { if (!dyingSetup) { dyingSetup = true; SFX.PlayOneShot(SFXDeathClip); // Turn off normal NPC collider and enable corpse collider for searching switch(normalCollider) { case collisionType.Box: boxCollider = GetComponent<BoxCollider>(); boxCollider.enabled = false; break; case collisionType.Sphere: sphereCollider = GetComponent<SphereCollider>(); sphereCollider.enabled = false; break; case collisionType.Mesh: meshCollider = GetComponent<MeshCollider>(); meshCollider.enabled = false; break; case collisionType.Capsule: capsuleCollider = GetComponent<CapsuleCollider>(); capsuleCollider.enabled = false; break; } switch(corpseCollider) { case collisionType.Box: boxCollider = GetComponent<BoxCollider>(); boxCollider.enabled = true; boxCollider.isTrigger = false; break; case collisionType.Sphere: sphereCollider = GetComponent<SphereCollider>(); sphereCollider.enabled = true; sphereCollider.isTrigger = false; break; case collisionType.Mesh: meshCollider = GetComponent<MeshCollider>(); meshCollider.enabled = true; meshCollider.isTrigger = false; break; case collisionType.Capsule: capsuleCollider = GetComponent<CapsuleCollider>(); capsuleCollider.enabled = true; capsuleCollider.isTrigger = false; break; } collisionAid1.SetActive(false); collisionAid2.SetActive(false); normalBody.SetActive(false); deathBody.SetActive(true); //for (int i=0;i<gibs.Length;i++) { // gibs[i].SetActive(true); // gibs[i].GetComponent<Rigidbody>().WakeUp(); //} gameObject.tag = "Searchable"; // Enable searching //nav.speed = nav.speed * 0.5f; // half the speed while collapsing or whatever timeTillDeadFinished = Time.time + timeTillDead; // wait for death animation to finish before going into Dead() } if (timeTillDeadFinished < Time.time) { //ai_dead = true; //ai_dying = false; //nav.isStopped = true; // Stop moving //rbody.isKinematic = true; currentState = Const.aiState.Dead; } } // Sub functions bool CheckIfEnemyInFront (GameObject target) { Vector3 vec = Vector3.Normalize(target.transform.position - transform.position); float dot = Vector3.Dot(vec,transform.forward); if (dot > 0.800) return true; // enemy is within 18 degrees of forward facing vector return false; } bool CheckIfEnemyInSight() { Vector3 checkline = enemy.transform.position - transform.position; // Get vector line made from enemy to found player RaycastHit hit; if(Physics.Raycast(transform.position + transform.up, checkline.normalized, out hit, sightRange)) { if (hit.collider.gameObject == enemy) { if (CheckIfEnemyInFront(enemy)) return true; } } return false; } /* bool CheckIfPlayerInSight (GameObject returnContainerForFoundEnemy) { if (enemy != null) return CheckIfEnemyInSight(); GameObject playr1 = Const.a.player1; GameObject playr2 = Const.a.player2; GameObject playr3 = Const.a.player3; GameObject playr4 = Const.a.player4; if (playr1 == null) { Debug.Log("WARNING: NPC sight check - no host player 1."); return false; } // No host player if (playr1 != null) {playr1 = playr1.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr2 != null) {playr2 = playr2.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr3 != null) {playr3 = playr3.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr4 != null) {playr4 = playr4.GetComponent<PlayerReferenceManager>().playerCapsule;} GameObject tempent = null; bool LOSpossible = false; for (int i=0;i<4;i++) { tempent = null; // Cycle through all the players to see if we can see anybody. Defaults to earlier joined players. TODO: Add randomization if multiple players are visible. if (playr1 != null && i == 0) tempent = playr1; if (playr2 != null && i == 1) tempent = playr2; if (playr3 != null && i == 2) tempent = playr3; if (playr4 != null && i == 4) tempent = playr4; if (tempent == null) continue; */ bool CheckIfPlayerInSight() { GameObject tempent = Const.a.player1.GetComponent<PlayerReferenceManager>().playerCapsule; Vector3 checkline = Vector3.Normalize(tempent.transform.position - transform.position); // Get vector line made from enemy to found player RaycastHit hit; if(Physics.Raycast(transform.position, checkline, out hit, sightRange)) { if (hit.collider.gameObject == tempent) { float dist = Vector3.Distance(tempent.transform.position,transform.position); // Get distance between enemy and found player float dot = Vector3.Dot(checkline,transform.forward.normalized); if (dot > 0.10f) { // enemy is within 81 degrees of forward facing vector if (firstSighting) { firstSighting = false; if (hasSFX) SFX.PlayOneShot(SFXSightSound); } enemy = tempent; return true; // time to fight! } else { if (dist < distToSeeWhenBehind) { SightSound(); enemy = tempent; return true; // time to turn around and face your executioner! } } } } return false; } GameObject GetImpactType (HealthManager hm) { if (hm == null) return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); switch (hm.bloodType) { case HealthManager.BloodType.None: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); case HealthManager.BloodType.Red: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmall); case HealthManager.BloodType.Yellow: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallYellow); case HealthManager.BloodType.Green: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallGreen); case HealthManager.BloodType.Robot: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmallBlue); } return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); } } <file_sep>/Assets/Scripts/ChargeStation.cs using UnityEngine; using System.Collections; public class ChargeStation : MonoBehaviour { public float amount = 170; //default to 2/3 of 255, the total energy player can have public float resetTime = 150; //150 seconds public bool requireReset; public float minSecurityLevel = 0; private float nextthink; void Awake () { nextthink = Time.time; } public void Use (UseData ud) { if (LevelManager.a.GetCurrentLevelSecurity () >= minSecurityLevel) { MFDManager.a.BlockedBySecurity (); return; } if (nextthink < Time.time) { ud.owner.GetComponent<PlayerReferenceManager>().playerCapsule.GetComponent<PlayerEnergy>().GiveEnergy(amount, 1); Const.sprint("Energy drawn from Power Station.", ud.owner); if (requireReset) { nextthink = Time.time + resetTime; } } else { Const.sprint("Power Station is recharging\n", ud.owner); } } } <file_sep>/Assets/Scripts/VaporizeButton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VaporizeButton : MonoBehaviour { public GeneralInventory playerGenInv; public GeneralInvCurrent playerGenCur; public GameObject playerCamera; public Image ico; public Text ict; public void PtrEnter () { GUIState.a.PtrHandler(true,true,GUIState.ButtonType.Generic,gameObject); playerCamera.GetComponent<MouseLookScript>().currentButton = gameObject; } public void PtrExit () { GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } public void OnVaporizeClick() { playerGenInv.generalInventoryIndexRef[playerGenCur.generalInvCurrent] = -1; } } <file_sep>/Assets/Scripts/TickIndicatorAnimation.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class TickIndicatorAnimation : MonoBehaviour { public PlayerHealth playerHealth; public PlayerEnergy playerEnergy; public Sprite[] indicatorImages; public bool healthIndicator; // if true, for health, if false, for energy public float thinkTime = 0.5f; private float nextthink; private Image indicator; private int tick; void Awake () { tick = 0; indicator = GetComponent<Image>(); } void Update () { if (nextthink < Time.time) { if (healthIndicator) { if (playerHealth.hm.health > 176) { indicator.overrideSprite = indicatorImages[0]; //indicator.sprite = indicatorImages[0]; } else { if (playerHealth.hm.health > 88) { indicator.overrideSprite = indicatorImages[1]; } else { switch (tick) { case 1: indicator.overrideSprite = indicatorImages[2]; break; case 2: indicator.overrideSprite = indicatorImages[3]; break; case 3: indicator.overrideSprite = indicatorImages[4]; break; case 4: indicator.overrideSprite = indicatorImages[5]; break; case 5: indicator.overrideSprite = indicatorImages[6]; break; } } } } else { if (playerEnergy.energy > 176) { indicator.overrideSprite = indicatorImages[0]; } else { if (playerEnergy.energy > 88) { indicator.overrideSprite = indicatorImages[1]; } else { switch (tick) { case 1: indicator.overrideSprite = indicatorImages[2]; break; case 2: indicator.overrideSprite = indicatorImages[3]; break; case 3: indicator.overrideSprite = indicatorImages[4]; break; case 4: indicator.overrideSprite = indicatorImages[5]; break; case 5: indicator.overrideSprite = indicatorImages[2]; // 1 less frame than the health indicator, hold the dark one twice as long break; } } } } tick++; if (tick > 5) tick = 0; nextthink = Time.time + thinkTime; } } } <file_sep>/Assets/Scripts/PuzzleGrid.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PuzzleGrid : MonoBehaviour { public bool[] powered; public CellType[] cellType; public enum CellType {Off,Standard,And,Bypass}; // off is blank, standard is X or +, AND takes two power sources, Bypass is always + public enum GridType {King,Queen,Knight,Rook,Bishop,Pawn}; public GridType gridType; public int sourceIndex; public int outputIndex; public int width; public int height; public Button[] gridCells; public Sprite nodeOn; public Sprite gridPlus; public Sprite gridPlusgreen; public Sprite gridPluspurple; public Sprite gridX; public Sprite gridXgreen; public Sprite gridXpurple; public Sprite gridNull; public Sprite gridSpecial; public Sprite gridSpecialgreen; public Sprite gridSpecialpurple; public Sprite gridSpecialOn0; public Sprite gridSpecialOn0green; public Sprite gridSpecialOn0purple; public Sprite gridSpecialOn1; public Sprite gridPlusOn0; public Sprite gridPlusOn1; public Sprite gridXOn0; public Sprite gridXOn1; public Sprite gridAlwaysOn0; public Sprite gridAlwaysOn0green; public Sprite gridAlwaysOn0purple; public Sprite gridAlwaysOn1; public Image outputNode; public enum GridColorTheme {Gray,Green,Purple}; public GridColorTheme theme; public AudioClip solvedSFX; public bool puzzleSolved; public Slider progressBar; private bool[] grid; private AudioSource audsource; private UseData udSender; private GameObject[] targets; void Awake () { puzzleSolved = false; audsource = GetComponent<AudioSource>(); EvaluatePuzzle(); UpdateCellImages(); targets = new GameObject[4]; } public void SendGrid(bool[] states, CellType[] types, GridType gtype, int start, int end, int w, int h, GridColorTheme colors, GameObject senttarget, GameObject senttarget1, GameObject senttarget2, GameObject senttarget3, UseData ud) { grid = states; cellType = types; gridType = gtype; sourceIndex = start; outputIndex = end; width = w; height = h; theme = colors; targets[0] = senttarget; targets[1] = senttarget1; targets[2] = senttarget2; targets[3] = senttarget3; udSender = ud; EvaluatePuzzle(); if (udSender.mainIndex == 54) { PuzzleSolved (); } UpdateCellImages(); } void Update () { //EvaluatePuzzle(); not needed, useless activity UpdateCellImages(); } public void OnGridCellClick (int index) { if (puzzleSolved) return; if (cellType[index] == CellType.Standard) { switch (gridType) { case GridType.King: King(index); break; case GridType.Queen: Queen(index); break; case GridType.Knight: Knight(index); break; case GridType.Rook: Rook(index); break; case GridType.Bishop: Bishop(index); break; case GridType.Pawn: Pawn(index); break; } } EvaluatePuzzle(); UpdateCellImages(); } public void UpdateCellImages() { for (int i=0;i<(width*height);i++) { if (cellType[i] != CellType.Off) { if (cellType[i] == CellType.Standard) { if (!grid[i]) { // Theme dependent switch (theme) { case GridColorTheme.Gray: gridCells [i].image.overrideSprite = gridX; break; case GridColorTheme.Green: gridCells [i].image.overrideSprite = gridXgreen; break; case GridColorTheme.Purple: gridCells [i].image.overrideSprite = gridXpurple; break; } } else { if (powered [i]) { gridCells [i].image.overrideSprite = gridPlusOn0; // powered node // TODO: handle different power images for lines between neighbors } else { // Theme dependent switch (theme) { case GridColorTheme.Gray: gridCells [i].image.overrideSprite = gridPlus; break; case GridColorTheme.Green: gridCells [i].image.overrideSprite = gridPlusgreen; break; case GridColorTheme.Purple: gridCells [i].image.overrideSprite = gridPluspurple; break; } } } } if (cellType[i] == CellType.And) { if (powered[i]) { // Theme dependent switch (theme) { case GridColorTheme.Gray: gridCells [i].image.overrideSprite = gridSpecialOn0; break; case GridColorTheme.Green: gridCells [i].image.overrideSprite = gridSpecialOn0green; break; case GridColorTheme.Purple: gridCells [i].image.overrideSprite = gridSpecialOn0purple; break; } } else { // Theme dependent switch (theme) { case GridColorTheme.Gray: gridCells [i].image.overrideSprite = gridSpecial; break; case GridColorTheme.Green: gridCells [i].image.overrideSprite = gridSpecialgreen; break; case GridColorTheme.Purple: gridCells [i].image.overrideSprite = gridSpecialpurple; break; } } } if (cellType[i] == CellType.Bypass) { if (powered[i]) { gridCells[i].image.overrideSprite = gridAlwaysOn1; // And node powered } else { // Theme dependent switch (theme) { case GridColorTheme.Gray: gridCells [i].image.overrideSprite = gridAlwaysOn0; break; case GridColorTheme.Green: gridCells [i].image.overrideSprite = gridAlwaysOn0green; break; case GridColorTheme.Purple: gridCells [i].image.overrideSprite = gridAlwaysOn0purple; break; } } } } else { gridCells[i].image.overrideSprite = gridNull; } } } public void EvaluatePuzzle() { List<int> queue = new List<int> (); bool[] checkedCells = new bool[width * height]; int cellAbove; int cellBelow; int cellLeft; int cellRight; int movingIndex; // Reset the power for (int i = 0; i < (width * height); i++) { powered [i] = false; } // Set power for starting node if (grid.Length < 1) return; powered [sourceIndex] = grid [sourceIndex]; // Turn on power for cell adjacent to source node if it is a plus movingIndex = sourceIndex; if (!powered [movingIndex]) return; // Source is off // Flow power to all nodes, adding any nodes to check to the queue queue.Add (sourceIndex); // Initialize queue while (queue.Count > 0) { movingIndex = queue [0]; // Get next item in the queue if (checkedCells [movingIndex]) { queue.Remove (movingIndex); continue; } //Const.sprint(("movingIndex = " + movingIndex.ToString()),Const.a.allPlayers); cellAbove = ReturnCellAbove (movingIndex); cellBelow = ReturnCellBelow (movingIndex); cellLeft = ReturnCellToLeft (movingIndex); cellRight = ReturnCellToRight (movingIndex); if (cellAbove != -1 && !checkedCells [cellAbove] && grid [cellAbove]) queue.Add (cellAbove); if (cellBelow != -1 && !checkedCells [cellBelow] && grid [cellBelow]) queue.Add (cellBelow); if (cellLeft != -1 && !checkedCells [cellLeft] && grid [cellLeft]) queue.Add (cellLeft); if (cellRight != -1 && !checkedCells [cellRight] && grid [cellRight]) queue.Add (cellRight); int poweredCount = 0; if (cellAbove != -1) { if (powered [cellAbove]) poweredCount++; } if (cellBelow != -1) { if (powered [cellBelow]) poweredCount++; } if (cellLeft != -1) { if (powered [cellLeft]) poweredCount++; } if (cellRight != -1) { if (powered [cellRight]) poweredCount++; } if (cellType [movingIndex] == CellType.And) { if (poweredCount > 1) powered [movingIndex] = true; } else { if (cellType [movingIndex] == CellType.Standard || cellType [movingIndex] == CellType.Bypass) { if (grid [movingIndex] && poweredCount > 0) powered [movingIndex] = true; Const.sprint (("movingIndex = " + movingIndex.ToString () + ", powered = " + powered [movingIndex].ToString ()), Const.a.allPlayers); } } checkedCells [movingIndex] = true; if (poweredCount > 1) { float percentProgress = 0f; int stepLeft = 0; int iteration = 0; for (int i = 0; i < grid.Length; i++) { if ((i == stepLeft || i == (stepLeft + width) || i == stepLeft + (width * 2)|| i == stepLeft + (width * 3)) && percentProgress < (iteration/7f)) { if (powered [i]) { percentProgress += (1f / 7f); iteration++; continue; } stepLeft++; } } progressBar.value = percentProgress; } } if (powered[outputIndex]) PuzzleSolved(); // Latched solved state, no else statement to switch solved state back } void PuzzleSolved() { puzzleSolved = true; outputNode.overrideSprite = nodeOn; audsource.PlayOneShot(solvedSFX); Const.a.UseTargets(udSender,targets); } int ReturnCellAbove(int index) { int retval = -1; bool outOfBounds = ((index-width) < 0) ? true: false; if (!outOfBounds){ if (cellType[index-width] != CellType.Off) retval = (index-width); // return cell above if not on top row } return retval; } int ReturnCellBelow(int index) { int retval = -1; bool outOfBounds = ((index+width) > ((width*height)-1)) ? true: false; if (!outOfBounds) { if (cellType[index+width] != CellType.Off) retval = (index+width); // return cell below if not on bottom row } return retval; } int ReturnCellToLeft(int index) { int retval = -1; if (!((index/width) > 0 && (index%width < 1))) { if ((index-1) >= 0) { if (cellType[index-1] != CellType.Off) retval = index-1; // return index to left if not in far left column } } return retval; } int ReturnCellToRight(int index) { int retval = -1; if (!(((index+1)/width) > 0 && ((index+1)%width < 1))) { if ((index+1) < (width*height)) { if (cellType[index+1] != CellType.Off) retval = index+1; // return index to right if not in far right column } } return retval; } // Only flip clicked cell void Pawn(int index) { if (cellType[index] == CellType.Standard) grid[index] = !grid[index]; // FLip clicked cell if it is standard } // Flip vertically and horizontally adjacent standard cells along with center void King(int index) { grid[index] = !grid[index]; // Flip clicked cell int cellAbove = ReturnCellAbove(index); int cellBelow = ReturnCellBelow(index); int cellLeft = ReturnCellToLeft(index); int cellRight = ReturnCellToRight(index); if (cellAbove != -1 && cellType[cellAbove] == CellType.Standard) grid[cellAbove] = !grid[cellAbove]; if (cellBelow != -1 && cellType[cellBelow] == CellType.Standard) grid[cellBelow] = !grid[cellBelow]; if (cellLeft != -1 && cellType[cellLeft] == CellType.Standard) grid[cellLeft] = !grid[cellLeft]; if (cellRight != -1 && cellType[cellRight] == CellType.Standard) grid[cellRight] = !grid[cellRight]; } // Flip vertically, horizontally, and diagonally adjacent cells across entire puzzle along with center void Queen(int index) { } // Flip corners along with center void Knight(int index) { } // Flip vertically and horizontally adjacent cells across entire puzzle along with center void Rook(int index) { grid[index] = !grid[index]; // Flip clicked cell int tempIndex = index; for (int i=0;i<width;i++) { int cellAbove = ReturnCellAbove(tempIndex); // get next cell up if (cellAbove != -1 && cellType[cellAbove] == CellType.Standard) grid[cellAbove] = !grid[cellAbove]; else break; // blocked by deactivated cells or special tempIndex = cellAbove; // move index up to cellAbove } tempIndex = index; int cellBelow = -1; for (int i=0;i<width;i++) { cellBelow = ReturnCellBelow(tempIndex); // get next cell up if (cellBelow != -1 && cellType[cellBelow] == CellType.Standard) grid[cellBelow] = !grid[cellBelow]; else break; // blocked by deactivated cells or special tempIndex = cellBelow; // move index up to cellAbove } tempIndex = index; int cellLeft = -1; for (int i=0;i<width;i++) { cellLeft= ReturnCellToLeft(tempIndex); // get next cell up if (cellLeft != -1 && cellType[cellLeft] == CellType.Standard) grid[cellLeft] = !grid[cellLeft]; else break; // blocked by deactivated cells or special tempIndex = cellLeft; // move index up to cellAbove } tempIndex = index; for (int i=0;i<width;i++) { int cellRight = ReturnCellToRight(tempIndex); // get next cell up if (cellRight != -1 && cellType[cellRight] == CellType.Standard) grid[cellRight] = !grid[cellRight]; else break; // blocked by deactivated cells or special tempIndex = cellRight; // move index up to cellAbove } } // Flip diagonally adjacent cells across entire puzzle along with center void Bishop(int index) { } } <file_sep>/Assets/Scripts/ImageSequenceTextureArray.cs using UnityEngine; using System.Collections; public class ImageSequenceTextureArray : MonoBehaviour { //An array of Objects that stores the results of the Resources.LoadAll() method private Object[] objects; private Object[] glowobjects; //Each returned object is converted to a Texture and stored in this array private Texture[] textures; private Texture[] glowtextures; //With this Material object, a reference to the game object Material can be stored private Material goMaterial; //An integer to advance frames private int frameCounter = 0; public string resourceFolder; public string glowResourceFolder; public float frameDelay = 0.35f; public bool animateGlow = false; public bool randomFrame = false; // randomly pick a frame instead of sequential public bool reverseSequence = false; private float tick; private float tickFinished; void Awake() { //Get a reference to the Material of the game object this script is attached to. this.goMaterial = this.GetComponent<Renderer>().material; //gameObject.SetActive (false); } void Start () { //Load all textures found on the Sequence folder, that is placed inside the resources folder if (resourceFolder == "") { return; } this.objects = Resources.LoadAll(resourceFolder, typeof(Texture)); this.glowobjects = Resources.LoadAll(glowResourceFolder, typeof(Texture)); //Initialize the array of textures with the same size as the objects array this.textures = new Texture[objects.Length]; this.glowtextures = new Texture[glowobjects.Length]; //Cast each Object to Texture and store the result inside the Textures array for(int i=0; i < objects.Length;i++) { this.textures[i] = (Texture)this.objects[i]; } for(int i=0; i < glowobjects.Length;i++) { this.glowtextures[i] = (Texture)this.glowobjects[i]; } if (reverseSequence) { frameCounter = (textures.Length - 1); } else { frameCounter = 0; } tick = frameDelay; tickFinished = Time.time + tick; } void Update () { if (resourceFolder == "") { return; } if (tickFinished < Time.time) { Think(); tickFinished = Time.time + tick; } } void Think () { if (reverseSequence) { frameCounter = (--frameCounter) % textures.Length; } else { frameCounter = (++frameCounter) % textures.Length; } if (randomFrame) { frameCounter = Random.Range (0, textures.Length); } //Set the material's texture to the current value of the frameCounter variable goMaterial.mainTexture = textures[frameCounter]; if (animateGlow) { goMaterial.SetTexture("_EmissionMap", glowtextures[frameCounter]); } } }<file_sep>/Assets/Scripts/TouchEnergyDrain.cs using UnityEngine; using System.Collections; public class TouchEnergyDrain : MonoBehaviour { public float drainage = 1; // assign in the editor void OnCollisionEnter (Collision col) { if (col.gameObject.tag == "Player") { col.gameObject.GetComponent<PlayerEnergy>().TakeEnergy(drainage); } } }<file_sep>/Assets/Scripts/StartMenuDifficultyController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class StartMenuDifficultyController : MonoBehaviour { public GameObject button0; public GameObject button1; public GameObject button2; public GameObject button3; public int difficultySetting; public string[] highlightString; public Text externalTextObject; public void SetDifficulty (int value) { difficultySetting = value; externalTextObject.text = highlightString[difficultySetting]; } void ResetHighlights () { button0.GetComponent<StartMenuButtonHighlight>().SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); button1.GetComponent<StartMenuButtonHighlight>().SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); button2.GetComponent<StartMenuButtonHighlight>().SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); button3.GetComponent<StartMenuButtonHighlight>().SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); externalTextObject.text = highlightString[difficultySetting]; } void ClickViaKeyboard () { difficultySetting++; if (difficultySetting >= 4) difficultySetting = 0; externalTextObject.text = highlightString[difficultySetting]; } void Update () { switch (difficultySetting) { case 0: ResetHighlights(); button0.GetComponent<StartMenuButtonHighlight>().SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); break; case 1: ResetHighlights(); button1.GetComponent<StartMenuButtonHighlight>().SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); break; case 2: ResetHighlights(); button2.GetComponent<StartMenuButtonHighlight>().SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); break; case 3: ResetHighlights(); button3.GetComponent<StartMenuButtonHighlight>().SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); break; } } } <file_sep>/Assets/Scripts/ConfigToggles.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigToggles : MonoBehaviour { private Toggle self; public enum ConfigToggleType{Fullscreen,SSAO,Bloom,Reverb,Subtitles,InvertLook,InvertCyber,InvertInventoryCycling,QuickPickup,QuickReload}; public ConfigToggleType ToggleType; void Start () { self = GetComponent<Toggle>(); switch (ToggleType) { case ConfigToggleType.Fullscreen: self.isOn = Const.a.GraphicsFullscreen; break; case ConfigToggleType.SSAO: self.isOn = Const.a.GraphicsSSAO; break; case ConfigToggleType.Bloom: self.isOn = Const.a.GraphicsBloom; break; case ConfigToggleType.Reverb: self.isOn = Const.a.AudioReverb; break; case ConfigToggleType.Subtitles: self.isOn = Const.a.AudioReverb; break; case ConfigToggleType.InvertLook: self.isOn = Const.a.InputInvertLook; break; case ConfigToggleType.InvertCyber: self.isOn = Const.a.InputInvertCyberspaceLook; break; case ConfigToggleType.InvertInventoryCycling: self.isOn = Const.a.InputInvertInventoryCycling; break; case ConfigToggleType.QuickPickup: self.isOn = Const.a.InputQuickItemPickup; break; case ConfigToggleType.QuickReload: self.isOn = Const.a.InputQuickReloadWeapons; break; } } public void ToggleFullscreen () { Const.a.GraphicsFullscreen = self.isOn; Const.a.WriteConfig(); } public void ToggleSSAO () { Const.a.GraphicsSSAO = self.isOn; Const.a.WriteConfig(); } public void ToggleBloom () { Const.a.GraphicsBloom = self.isOn; Const.a.WriteConfig(); } public void ToggleReverb () { Const.a.AudioReverb = self.isOn; Const.a.WriteConfig(); } public void ToggleSubtitles () { Const.a.AudioSubtitles = self.isOn; Const.a.WriteConfig(); } public void ToggleInvertLook () { Const.a.InputInvertLook = self.isOn; Const.a.WriteConfig(); } public void ToggleInvertCyberLook () { Const.a.InputInvertCyberspaceLook = self.isOn; Const.a.WriteConfig(); } public void ToggleInvertInventoryCycling () { Const.a.InputInvertInventoryCycling = self.isOn; Const.a.WriteConfig(); } public void ToggleQuickItemPickup () { Const.a.InputQuickItemPickup = self.isOn; Const.a.WriteConfig(); } public void ToggleQuickReloadWeapon () { Const.a.InputQuickReloadWeapons = self.isOn; Const.a.WriteConfig(); } } <file_sep>/Assets/Scripts/AIGoals.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public enum GoalType {None,AttackAnyPlayer,AttackPlayer1,AttackPlayer2,AttackPlayer3,AttackPlayer4,Interact,Wander,Guard,Patrol}; public class AIGoals : MonoBehaviour { private int tempInt = 0; public static AIGoals a; void Awake() { a = this; } public void AddInGoal(GoalType[] gList, GoalType goalToAdd) { for (tempInt = 0;tempInt<gList.Length;tempInt++) { if (gList[tempInt] == GoalType.None) { gList[tempInt] = goalToAdd; return; } } // Debug.Log("WARNING: Attempting to add goal to full list!"); } public bool CheckIfInGoals(GoalType[] gList, GoalType goal) { for (tempInt=0;tempInt<gList.Length;tempInt++) { if (gList[tempInt] == goal) return true; } return false; } } <file_sep>/Assets/Scripts/BeverageSpawn.cs using UnityEngine; using System.Collections; public class BeverageSpawn : MonoBehaviour { [SerializeField] private Texture skin1; [SerializeField] private Texture skin2; [SerializeField] private Texture skin3; [SerializeField] private Texture skin4; void Awake () { float i; i = Random.Range(0.0f,1.0f); if (i > 0.75) { GetComponent<Renderer>().material.mainTexture = skin1; } else { if (i < 0.75 && i > 0.5) { GetComponent<Renderer>().material.mainTexture = skin1; } else { if (i < 0.5 && i > 0.25) { GetComponent<Renderer>().material.mainTexture = skin3; } else { GetComponent<Renderer>().material.mainTexture = skin4; } } } } } <file_sep>/Assets/Scripts/MailTitleManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class MailTitleManager : MonoBehaviour { [SerializeField] public string[] mailTitle; public void SetMailTitle (int index) { if (index >= 0) GetComponent<Text>().text = mailTitle[index]; } }<file_sep>/Assets/Scripts/DataTab.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class DataTab : MonoBehaviour { public GameObject headerText; public GameObject noItemsText; public GameObject blockedBySecurity; public GameObject elevatorUIControl; public GameObject keycodeUIControl; public GameObject[] searchItemImages; public GameObject audioLogContainer; public GameObject puzzleGrid; public GameObject puzzleWire; public Text headerText_text; public SearchButton searchContainer; public Vector3 objectInUsePos; public bool usingObject; public Transform playerCapsuleTransform; void Awake () { Reset(); } void Update () { if (usingObject) { if (Vector3.Distance(playerCapsuleTransform.position, objectInUsePos) > Const.a.frobDistance) { Reset(); } } } public void Reset() { usingObject = false; headerText.SetActive(false); headerText_text.text = System.String.Empty; noItemsText.SetActive(false); blockedBySecurity.SetActive(false); elevatorUIControl.SetActive(false); keycodeUIControl.SetActive(false); puzzleGrid.SetActive(false); puzzleWire.SetActive(false); audioLogContainer.SetActive(false); for (int i=0; i<=3;i++) { searchItemImages[i].SetActive(false); } } public void Search(string head, int numberFoundContents, int[] contents, int[] customIndex) { headerText.SetActive(true); headerText_text.enabled = true; headerText_text.text = head; if (numberFoundContents <= 0) { noItemsText.SetActive(true); noItemsText.GetComponent<Text>().enabled = true; return; } for (int i=0;i<4;i++) { if (contents[i] > -1) { searchItemImages[i].SetActive(true); searchItemImages[i].GetComponent<Image>().overrideSprite = Const.a.searchItemIconSprites[contents[i]]; searchContainer.contents[i] = contents[i]; searchContainer.customIndex[i] = customIndex[i]; } } } public void GridPuzzle(bool[] states, PuzzleGrid.CellType[] types, PuzzleGrid.GridType gtype, int start, int end, int width, int height, PuzzleGrid.GridColorTheme colors, GameObject t1, GameObject t2, GameObject t3, GameObject t4, UseData ud) { puzzleGrid.GetComponent<PuzzleGrid>().SendGrid(states,types,gtype,start,end, width, height,colors,t1 ,t2, t3, t4,ud); } } <file_sep>/Assets/Scripts/HardwareButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityStandardAssets.ImageEffects; public class HardwareButton : MonoBehaviour { //[SerializeField] private GameObject iconman; [SerializeField] private AudioSource SFX = null; // assign in the editor [SerializeField] private AudioClip SFXClip = null; // assign in the editor [SerializeField] private AudioClip SFXClipDeactivate = null; // assign in the editor public CenterTabButtons ctb; public Sprite buttonDeactive; public Sprite buttonActive1; public Sprite buttonActive2; public Sprite buttonActive3; public Sprite buttonActive4; public HardwareInventory hwi; public HardwareInvCurrent hwc; public int referenceIndex; public int ref14Index; private bool toggleState = false; private Button butn; private float defaultZero = 0f; private float brightness = 0f; public GameObject sensaroundCenter; public GameObject sensaroundLH; public GameObject sensaroundRH; public GameObject sensaroundCenterCamera; public GameObject sensaroundLHCamera; public GameObject sensaroundRHCamera; public Light infraredLight; public GameObject playerCamera; public HeadMountedLantern hml; void Awake () { butn = GetComponent<Button>(); } public void PtrEnter () { GUIState.a.isBlocking = true; } public void PtrExit () { GUIState.a.isBlocking = false; } void Update () { ListenForHardwareHotkeys(); } public void ChangeHardwareVersion (int ind, int verz) { SetVersionIconForButton (true, verz); switch (ind) { case 0: break; case 1: break; case 2: break; case 3: break; case 4: break; case 5: break; case 6: // Bio break; case 7: // Lantern // figure out which brightness setting to use depending on version again switch(verz) { case 1: brightness = hml.lanternVersion1Brightness; break; case 2: brightness = hml.lanternVersion2Brightness; break; case 3: brightness = hml.lanternVersion3Brightness; break; default: brightness = defaultZero; break; } hml.headlight.intensity = brightness; // set the light intensity per version break; case 8: break; case 9: break; case 10: break; case 11: break; case 12: break; case 13: break; } } public void ListenForHardwareHotkeys () { // Bio if (GetInput.a != null && HardwareInventory.a.hasHardware[6] && GetInput.a.Biomonitor()) { BioClick (); } // Sensaround if (GetInput.a != null && HardwareInventory.a.hasHardware[3] && GetInput.a.Sensaround()) { SensaroundClick (); } // Shield if (GetInput.a != null && HardwareInventory.a.hasHardware[5] && GetInput.a.Shield()) { ShieldClick (); } // Lantern if (GetInput.a != null && HardwareInventory.a.hasHardware[7] && GetInput.a.Lantern()) { LanternClick (); } // Infrared if (GetInput.a != null && HardwareInventory.a.hasHardware[11] && GetInput.a.Infrared()) { InfraredClick (); } // Ereader if (GetInput.a != null && HardwareInventory.a.hasHardware[2] && GetInput.a.Email()) { EReaderClick (); } // Booster if (GetInput.a != null && HardwareInventory.a.hasHardware[9] && GetInput.a.Booster()) { BoosterClick (); } // JumpJets if (GetInput.a != null && HardwareInventory.a.hasHardware[10] && GetInput.a.Jumpjets()) { JumpJetsClick (); } } public void SetVersionIconForButton(bool isOn, int verz) { if (isOn) { switch (verz) { case 0: Const.sprint ("ERROR: Hardware version set to 0!! for " + Const.a.useableItemsNameText [referenceIndex], Const.a.allPlayers); break; case 1: butn.image.overrideSprite = buttonActive1; break; case 2: butn.image.overrideSprite = buttonActive2; break; case 3: butn.image.overrideSprite = buttonActive3; break; case 4: butn.image.overrideSprite = buttonActive4; break; } } else { butn.image.overrideSprite = buttonDeactive; } } public void BioClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [6] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); } public void SensaroundClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [3] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); if (toggleState) { switch (hwi.hardwareVersion [ref14Index]) { case 1: sensaroundCenterCamera.SetActive (true); sensaroundCenter.SetActive (true); break; case 2: sensaroundCenterCamera.SetActive (true); sensaroundCenter.SetActive (true); sensaroundLHCamera.SetActive (true); sensaroundLH.SetActive (true); sensaroundRHCamera.SetActive (true); sensaroundRH.SetActive (true); break; case 3: sensaroundCenterCamera.SetActive (true); sensaroundCenter.SetActive (true); sensaroundLHCamera.SetActive (true); sensaroundLH.SetActive (true); sensaroundRHCamera.SetActive (true); sensaroundRH.SetActive (true); break; case 4: sensaroundCenterCamera.SetActive (true); sensaroundCenter.SetActive (true); sensaroundLHCamera.SetActive (true); sensaroundLH.SetActive (true); sensaroundRHCamera.SetActive (true); sensaroundRH.SetActive (true); break; } } else { sensaroundCenterCamera.SetActive (false); sensaroundCenter.SetActive (false); sensaroundLHCamera.SetActive (false); sensaroundLH.SetActive (false); sensaroundRHCamera.SetActive (false); sensaroundRH.SetActive (false); } } public void ShieldClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [5] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); } public void LanternClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [7] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); // figure out which brightness setting to use depending on version switch(hwi.hardwareVersionSetting[ref14Index]) { case 1: brightness = hml.lanternVersion1Brightness; break; case 2: brightness = hml.lanternVersion2Brightness; break; case 3: brightness = hml.lanternVersion3Brightness; break; default: brightness = defaultZero; break; } if (hwc.hardwareIsActive [ref14Index]) { hml.headlight.intensity = brightness; // set the light intensity per version } else { hml.headlight.intensity = defaultZero; // turn the light off } } public void InfraredClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [11] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); if (toggleState) { infraredLight.enabled = true; playerCamera.GetComponent<Grayscale>().enabled = true; } else { infraredLight.enabled = false; playerCamera.GetComponent<Grayscale>().enabled = false; } } public void EReaderClick () { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [2] = toggleState; if (toggleState) { butn.image.overrideSprite = buttonActive1; } else { butn.image.overrideSprite = buttonDeactive; } if (ctb != null) ctb.TabButtonClickSilent(4); MFDManager.a.OpenEReaderInItemsTab(); } public void BoosterClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [9] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); } public void JumpJetsClick() { if (toggleState) { SFX.PlayOneShot (SFXClipDeactivate); } else { SFX.PlayOneShot (SFXClip); } toggleState = !toggleState; hwc.hardwareIsActive [10] = toggleState; SetVersionIconForButton (toggleState, hwi.hardwareVersionSetting[ref14Index]); } } <file_sep>/Assets/Scripts/HealthManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthManager : MonoBehaviour { public float health = -1f; // current health public float maxhealth; // maximum health public float gibhealth; // point at which we splatter public bool gibOnDeath = false; // used for things like crates to "gib" and shatter public bool gibCorpse = false; public bool vaporizeCorpse = true; public bool isNPC = false; public bool isObject = false; public bool applyImpact = false; public int[] gibIndices; public GameObject[] gibObjects; public int index; public int securityAmount; public GameObject attacker; public Const.PoolType deathFX; public enum BloodType {None,Red,Yellow,Green,Robot}; public BloodType bloodType; public GameObject[] targetOnDeath; public AudioClip backupDeathSound; public bool debugMessages = false; private bool initialized = false; private bool deathDone = false; private AIController aic; private Rigidbody rbody; private MeshCollider meshCol; private BoxCollider boxCol; private SphereCollider sphereCol; private CapsuleCollider capCol; private Vector3 tempVec; private float tempFloat; void Awake () { initialized = false; deathDone = false; rbody = GetComponent<Rigidbody>(); meshCol = GetComponent<MeshCollider>(); boxCol = GetComponent<BoxCollider>(); sphereCol = GetComponent<SphereCollider>(); capCol = GetComponent<CapsuleCollider>(); if (maxhealth < 1) maxhealth = health; if (isNPC) { aic = GetComponent<AIController>(); if (aic == null) Debug.Log("BUG: No AIController script on NPC!"); index = aic.index; // TODO: Uncomment this for final game //if (Const.a.difficultyCombat == 0) { // maxhealth = 1; // health = maxhealth; //} } attacker = null; //searchItems = GetComponent<SearchableItem>(); } void Update () { if (!initialized) { initialized = true; Const.a.RegisterObjectWithHealth(this); } if (health > maxhealth) health = maxhealth; // Don't go past max. Ever. } public void TakeDamage(DamageData dd) { if (health <= 0) return; tempFloat = health; health -= dd.damage; if (debugMessages) Const.sprint("Health before: " + tempFloat.ToString() + "| Health after: " + health.ToString(), Const.a.allPlayers); if (aic != null) aic.goIntoPain = true; attacker = dd.owner; if (applyImpact && rbody != null) { rbody.AddForce(dd.impactVelocity*dd.attacknormal,ForceMode.Impulse); } if (health <= 0f) { if (!deathDone) { if (isObject) ObjectDeath(null); if (isNPC) NPCDeath(null); if (targetOnDeath != null) { if (targetOnDeath.Length > 0) { UseData ud = new UseData(); ud.owner = Const.a.allPlayers; for (int i = 0; i < targetOnDeath.Length; i++) { targetOnDeath[i].SendMessageUpwards("Targetted", ud); } } } } else { if (vaporizeCorpse && health < (0 - (maxhealth / 2))) { GetComponent<MeshRenderer>().enabled = false; GameObject explosionEffect = Const.a.GetObjectFromPool(Const.PoolType.Vaporize); if (explosionEffect != null) { explosionEffect.SetActive(true); tempVec = transform.position; tempVec.y += aic.verticalViewOffset; explosionEffect.transform.position = tempVec; // put vaporization effect at raycast center } } } } } public void NPCDeath (AudioClip deathSound) { switch (index) { case 0: GetComponent<MeshRenderer> ().enabled = false; break; } // Enable death effects (e.g. explosion particle effect) if (deathFX != Const.PoolType.LaserLines) { GameObject explosionEffect = Const.a.GetObjectFromPool(deathFX); if (explosionEffect != null) { explosionEffect.SetActive(true); explosionEffect.transform.position = transform.position; // TODO: Do I need more than one temporary audio entity for this sort of thing? if (deathSound != null) { GameObject tempAud = GameObject.Find ("TemporaryAudio"); tempAud.transform.position = transform.position; AudioSource aS = tempAud.GetComponent<AudioSource> (); aS.PlayOneShot (deathSound); } else { GameObject tempAud = GameObject.Find ("TemporaryAudio"); tempAud.transform.position = transform.position; AudioSource aS = tempAud.GetComponent<AudioSource> (); aS.PlayOneShot (backupDeathSound); } } } if (gibOnDeath) Gib(); } void Gib() { if (gibObjects[0] != null) { for (int i = 0; i < gibObjects.Length; i++) { gibObjects[i].SetActive(true); // turn on all the gibs to fall apart //TODO: add force to gibs? } } } public void ObjectDeath(AudioClip deathSound) { deathDone = true; // Disable collision if (boxCol != null) boxCol.enabled = false; if (meshCol != null) meshCol.enabled = false; if (sphereCol != null) sphereCol.enabled = false; if (capCol != null) capCol.enabled = false; if (securityAmount > 0) LevelManager.a.ReduceCurrentLevelSecurity (securityAmount); // Enabel death effects (e.g. explosion particle effect) if (deathFX != Const.PoolType.LaserLines) { GameObject explosionEffect = Const.a.GetObjectFromPool(deathFX); if (explosionEffect != null) { explosionEffect.SetActive(true); explosionEffect.transform.position = transform.position; // TODO: Do I need more than one temporary audio entity for this sort of thing? if (deathSound != null) { GameObject tempAud = GameObject.Find("TemporaryAudio"); tempAud.transform.position = transform.position; AudioSource aS = tempAud.GetComponent<AudioSource>(); aS.PlayOneShot(deathSound); } } } if (gibOnDeath) Gib(); //gameObject.SetActive(false); // turn off the main object GetComponent<MeshRenderer>().enabled = false; } public void HealingBed(float amount) { health += amount; } } <file_sep>/Assets/Scripts/TextManager.cs using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using UnityEngine; public class TextManager : MonoBehaviour { public string[] stringTable; //Instance container variable public static TextManager a; // Instantiate it so that it can be accessed globally. MOST IMPORTANT PART!! // ========================================================================= void Awake() { a = this; } private void Start() { LoadTextForLanguage(1); //initialize with US English (index 0) } public void LoadTextForLanguage(int lang) { string readline; // variable to hold each string read in from the file int currentline = 0; string sourceFile = "/StreamingAssets/text_english.txt"; // TODO: support other languages switch (lang) { case 0: sourceFile = "/StreamingAssets/text_english.txt"; break; case 1: sourceFile = "/StreamingAssets/text_espanol.txt"; break; case 2: sourceFile = "/StreamingAssets/text_francois.txt"; break; default: sourceFile = "/StreamingAssets/text_english.txt"; break; } StreamReader dataReader = new StreamReader(Application.dataPath + sourceFile, Encoding.Default); using (dataReader) { do { // Read the next line readline = dataReader.ReadLine(); if (currentline < stringTable.Length) stringTable[currentline] = readline; currentline++; } while (!dataReader.EndOfStream); dataReader.Close(); return; } } } <file_sep>/Assets/Scripts/MainMenuHandler.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; //using UnityStandardAssets.ImageEffects; using System.IO; using System.Collections; public class MainMenuHandler : MonoBehaviour { public GameObject Button1; public GameObject Button2; public GameObject Button3; public GameObject Button4; public GameObject startFXObject; public AudioClip StartGameSFX; public GameObject saltTheFries; public GameObject mainCamera; public GameObject singleplayerPage; public GameObject multiplayerPage; public GameObject newgamePage; public GameObject frontPage; public GameObject loadPage; public GameObject savePage; public GameObject optionsPage; public InputField newgameInputText; public StartMenuDifficultyController combat; public StartMenuDifficultyController mission; public StartMenuDifficultyController puzzle; public StartMenuDifficultyController cyber; public PauseScript pauseHandler; private enum Pages {fp,sp,mp,np,lp,op,sv}; private Pages currentPage; private AudioSource StartSFX; private AudioSource BackGroundMusic; private bool returnToPause = false; void Awake () { StartSFX = startFXObject.GetComponent<AudioSource>(); BackGroundMusic = GetComponent<AudioSource>(); GoToFrontPage(); } void Update () { // Escape/back button listener if (Input.GetKeyDown(KeyCode.Escape)) { GoBack(); } if ( (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.P)) || (Input.GetKeyDown(KeyCode.LeftAlt) && Input.GetKey(KeyCode.P)) ) { Debug.Log("Skipping main menu. Debug cheat"); StartGame(true); } } public void StartGame (bool isNew) { StartSFX.PlayOneShot(StartGameSFX); if (isNew) { Const.a.playerName = newgamePage.GetComponentInChildren<InputField>().text; Const.a.difficultyCombat = combat.difficultySetting; Const.a.difficultyMission = mission.difficultySetting; Const.a.difficultyPuzzle = puzzle.difficultySetting; Const.a.difficultyCyber = cyber.difficultySetting; } this.gameObject.SetActive(false); } void ResetPages() { singleplayerPage.SetActive(false); multiplayerPage.SetActive(false); newgamePage.SetActive(false); frontPage.SetActive(false); loadPage.SetActive(false); savePage.SetActive(false); optionsPage.SetActive(false); } public void GoToFrontPage () { ResetPages(); frontPage.SetActive(true); currentPage = Pages.fp; } public void GoToSingleplayerSubmenu () { ResetPages(); singleplayerPage.SetActive(true); currentPage = Pages.sp; } public void GoToMultiplayerSubmenu () { ResetPages(); multiplayerPage.SetActive(true); currentPage = Pages.mp; } public void GoToOptionsSubmenu (bool accessedFromPause) { ResetPages(); optionsPage.SetActive(true); currentPage = Pages.op; returnToPause = accessedFromPause; } public void GoToNewGameSubmenu () { ResetPages(); newgamePage.SetActive(true); newgameInputText.ActivateInputField(); currentPage = Pages.np; } public void GoToLoadGameSubmenu () { ResetPages(); loadPage.SetActive(true); currentPage = Pages.lp; } public void GoToSaveGameSubmenu (bool fromPause) { ResetPages(); savePage.SetActive(true); currentPage = Pages.sv; returnToPause = fromPause; } public void SaveGame (int index) { Const.sprint("Saved game to slot " + index.ToString() + "! (TODO:Actually save)",Const.a.player1); pauseHandler.EnablePauseUI(); this.gameObject.SetActive(false); } public void LoadGame (int index) { //StreamReader sf = Const.a.savedGames[index]; // Do awesome stuff { // ... // } StartGame(false); } void GoBack () { if (returnToPause) { pauseHandler.EnablePauseUI(); this.gameObject.SetActive(false); return; } if (currentPage == Pages.sv) { GoToFrontPage(); return; } // Go Back to front page if (currentPage == Pages.sp || currentPage == Pages.mp || currentPage == Pages.op) { GoToFrontPage(); return; } // Go Back to singlepayer page if (currentPage == Pages.np || currentPage == Pages.lp) { GoToSingleplayerSubmenu(); return; } } public void PlayIntro () { Debug.Log("Playing intro video"); } public void PlayCredits () { Debug.Log("Playing credits"); } public void Quit () { StartCoroutine(quitFunction()); } IEnumerator quitFunction () { BackGroundMusic.Stop(); saltTheFries.SetActive(true); yield return new WaitForSeconds(0.8f); #if UNITY_EDITOR_WIN UnityEditor.EditorApplication.isPlaying = false; #endif Application.Quit(); } } <file_sep>/Assets/Scripts/UseableObjectUse.cs using UnityEngine; using System.Collections; public class UseableObjectUse : MonoBehaviour { public int useableItemIndex; public int customIndex = -1; public int ammo = 0; public bool ammoIsSecondary = false; private Texture2D tex; private MouseLookScript mlook; // was GameObject owner as arguments, now UseData to hold more info public void Use (UseData ud) { tex = Const.a.useableItemsFrobIcons[useableItemIndex]; if (tex != null) ud.owner.GetComponent<PlayerReferenceManager>().playerCursor.GetComponent<MouseCursor>().cursorImage = tex; // set cursor to this object mlook = ud.owner.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<MouseLookScript>(); mlook.ForceInventoryMode(); // inventory mode is turned on when picking something up mlook.holdingObject = true; mlook.heldObjectIndex = useableItemIndex; mlook.heldObjectCustomIndex = customIndex; mlook.heldObjectAmmo = ammo; mlook.heldObjectAmmoIsSecondary = ammoIsSecondary; // should I assign mlook to null at this point so that I don't accidentally have a bug in multiplayer where the wrong player reference gets an object picked up // nah, I trust GetComponent to work for the owner who sent the Use command // well ok sure... mlook = null; this.gameObject.SetActive(false); //we've been picked up, quick hide like you are actually in the player's hand } // ouch! public void TakeDamage (DamageData dd) { Rigidbody rbody = GetComponent<Rigidbody>(); rbody.AddForceAtPosition((dd.attacknormal*dd.damage),dd.hit.point); // knock me around will you } } public class UseData { public GameObject owner = null; // pass main GameObject that contains the script PlayerReferenceManager public int mainIndex = -1; // master index value for lookup in the Const tables public int customIndex = -1; // function for reseting all data if needed public void Reset (UseData ud) { ud.owner = null; ud.mainIndex = -1; ud.customIndex = -1; } } <file_sep>/Assets/Scripts/TextureStaticNoise.cs using UnityEngine; using System.Collections; public class TextureStaticNoise : MonoBehaviour { public int resolution = 64; public float interval = 0.15f; private float updateTime; private Texture2D texture; void Awake () { texture = new Texture2D(resolution, resolution, TextureFormat.RGB24, true); texture.name = "ProceduralStatic"; GetComponent<MeshRenderer>().material.mainTexture = texture; FillTexture(); updateTime = Time.time + interval; } void OnEnable () { texture = new Texture2D(resolution, resolution, TextureFormat.RGB24, true); texture.name = "ProceduralStatic"; GetComponent<MeshRenderer>().material.mainTexture = texture; FillTexture(); updateTime = Time.time + interval; } void FillTexture () { if (texture.width != resolution) texture.Resize(resolution, resolution); //Vector3 point00 = new Vector3(-0.5f,-0.5f); //Vector3 point10 = new Vector3( 0.5f,-0.5f); //Vector3 point01 = new Vector3(-0.5f, 0.5f); //Vector3 point11 = new Vector3( 0.5f, 0.5f); //float stepSize = 1f / resolution; for (int y=0; y<resolution; y++) { //Vector3 point0 = Vector3.Lerp(point00, point01, (y+0.5f) * stepSize); //Vector3 point1 = Vector3.Lerp(point10, point11, (y+0.5f) * stepSize); for (int x=0; x<resolution; x++) { //Vector3 point = Vector3.Lerp(point0, point1, (y+0.5f) * stepSize); texture.SetPixel(x, y, Color.white * Random.value); } } texture.filterMode = FilterMode.Point; texture.Apply(); } void Update () { if (updateTime < Time.time) { updateTime = (Time.time + interval); FillTexture(); } //updateTime += Time.deltaTime; } } <file_sep>/Assets/Scripts/PatchButtonsManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class PatchButtonsManager : MonoBehaviour { public GameObject[] patchButtons; [SerializeField] private GameObject[] patchCountsText; private int index; void LateUpdate() { if (PatchInventory.PatchInvInstance == null) { Const.sprint("ERROR->PatchButtonsManager: PatchInventory is null",Const.a.allPlayers); return; } for (int i=0; i<7; i++) { if (PatchInventory.PatchInvInstance.patchCounts[i] > 0) { if (!patchButtons[i].activeInHierarchy) patchButtons[i].SetActive(true); if (!patchCountsText[i].activeInHierarchy) patchCountsText[i].SetActive(true); } else { if (patchButtons[i].activeInHierarchy) patchButtons[i].SetActive(false); if (patchCountsText[i].activeInHierarchy) patchCountsText[i].SetActive(false); } } } } <file_sep>/Assets/Scripts/MaterialChanger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MaterialChanger : MonoBehaviour { public Texture2D newTexture; public Texture2D[] newTextureRandom; public bool disableImageSequence = true; public bool useRandom = false; public int selectedDigit; public bool sendSelectedDigit; public bool linkSelectedDigit; public GameObject target; private ImageSequenceTextureArray ista; private Texture2D selectedTexture; void Awake () { ista = GetComponent<ImageSequenceTextureArray>(); if (useRandom) { selectedDigit = Random.Range (0, newTextureRandom.Length); selectedTexture = newTextureRandom[selectedDigit]; } else { selectedTexture = newTexture; } } public void Targetted (UseData ud) { ista.enabled = false; // disable automatic texture changing if (ud.mainIndex != -1) { selectedDigit = ud.mainIndex; selectedTexture = newTextureRandom[selectedDigit]; } gameObject.GetComponent<MeshRenderer> ().material.mainTexture = selectedTexture; // set texture to new texture if (linkSelectedDigit) { if (target != null) { ud.mainIndex = selectedDigit; target.SendMessageUpwards ("Targetted", ud); } } if (sendSelectedDigit) { switch (LevelManager.a.currentLevel) { case 1: Const.a.questData.lev1SecCode = selectedDigit; break; case 2: Const.a.questData.lev2SecCode = selectedDigit; break; case 3: Const.a.questData.lev3SecCode = selectedDigit; break; case 4: Const.a.questData.lev4SecCode = selectedDigit; break; case 5: Const.a.questData.lev5SecCode = selectedDigit; break; case 6: Const.a.questData.lev6SecCode = selectedDigit; break; } } } } <file_sep>/Assets/Scripts/GUIState.cs using UnityEngine; using System.Collections; public class GUIState : MonoBehaviour { [SerializeField] public bool isBlocking = false; public static GUIState a; public enum ButtonType {Generic,GeneralInv,Patch,Grenade,Weapon,Search,None}; public ButtonType overButtonType = ButtonType.None; public bool overButton; public GameObject currentButton; void Awake() { a = this; a.currentButton = null; a.overButton = false; a.overButtonType = ButtonType.None; a.isBlocking = false; } public void PtrHandler (bool block, bool overState, ButtonType overType,GameObject button) { isBlocking = block; overButton = overState; overButtonType = overType; currentButton = button; } } <file_sep>/Assets/Scripts/ObjectImpact.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectImpact : MonoBehaviour { [HideInInspector] public Rigidbody rbody; [HideInInspector] public Vector3 oldVelocity; public float impactSoundSpeed = 11.72f; [HideInInspector] public AudioSource SFXSource; public AudioClip SFX; void Awake () { rbody = GetComponent<Rigidbody> (); if (rbody == null) { Const.sprint ("ERROR: No rigidbody found on object with ObjectImpact script!", Const.a.allPlayers); transform.gameObject.SetActive (false); } SFXSource = GetComponent<AudioSource> (); } void FixedUpdate () { // Handle impact sound if (Mathf.Abs ((oldVelocity.y - rbody.velocity.y)) > impactSoundSpeed) { if (SFXSource != null) { SFXSource.PlayOneShot (SFX); // Play sound when object changes velocity significantly enough that it must have hit something } } oldVelocity = rbody.velocity; } } <file_sep>/Assets/Scripts/Const.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.PostProcessing; using System.Text; using System.IO; using System.Collections; using System.Collections.Generic; using System.Globalization; using System; using System.Runtime.Serialization; using UnityStandardAssets.ImageEffects; // Global types public enum Handedness {Center,LH,RH}; public class Const : MonoBehaviour { //Item constants [SerializeField] public QuestBits questData; [SerializeField] public GameObject[] useableItems; [SerializeField] public Texture2D[] useableItemsFrobIcons; [SerializeField] public Sprite[] useableItemsIcons; [SerializeField] public string[] useableItemsNameText; [SerializeField] public Sprite[] searchItemIconSprites; [SerializeField] public string[] genericText; //Audiolog constants [SerializeField] public string[] audiologNames; [SerializeField] public string[] audiologSenders; [SerializeField] public string[] audiologSubjects; [SerializeField] public AudioClip[] audioLogs; [SerializeField] public int[] audioLogType; // 0 = text only, 1 = normal, 2 = email, 3 = vmail [SerializeField] public string[] audioLogSpeech2Text; [SerializeField] public int[] audioLogLevelFound; //Weapon constants [SerializeField] public bool[] isFullAutoForWeapon; [SerializeField] public float[] delayBetweenShotsForWeapon; [SerializeField] public float[] delayBetweenShotsForWeapon2; [SerializeField] public float[] damagePerHitForWeapon; [SerializeField] public float[] damagePerHitForWeapon2; [SerializeField] public float[] damageOverloadForWeapon; [SerializeField] public float[] energyDrainLowForWeapon; [SerializeField] public float[] energyDrainHiForWeapon; [SerializeField] public float[] energyDrainOverloadForWeapon; [SerializeField] public float[] penetrationForWeapon; [SerializeField] public float[] penetrationForWeapon2; [SerializeField] public float[] offenseForWeapon; [SerializeField] public float[] offenseForWeapon2; [SerializeField] public float[] rangeForWeapon; [SerializeField] public int[] magazinePitchCountForWeapon; [SerializeField] public int[] magazinePitchCountForWeapon2; [SerializeField] public float[] recoilForWeapon; public enum AttackType{None,Melee,EnergyBeam,Magnetic,Projectile,ProjectileEnergyBeam}; [SerializeField] public AttackType[] attackTypeForWeapon; //NPC constants [SerializeField] public string[] nameForNPC; [SerializeField] public AttackType[] attackTypeForNPC; [SerializeField] public AttackType[] attackTypeForNPC2; [SerializeField] public AttackType[] attackTypeForNPC3; [SerializeField] public float[] damageForNPC; // Primary attack damage [SerializeField] public float[] damageForNPC2; // Secondary attack damage [SerializeField] public float[] damageForNPC3; // Grenade attack damage [SerializeField] public float[] rangeForNPC; // Primary attack range [SerializeField] public float[] rangeForNPC2; // Secondary attack range [SerializeField] public float[] rangeForNPC3; // Grenade throw range [SerializeField] public float[] healthForNPC; public enum PerceptionLevel{Low,Medium,High,Omniscient}; [SerializeField] public PerceptionLevel[] perceptionForNPC; [SerializeField] public float[] disruptabilityForNPC; [SerializeField] public float[] armorvalueForNPC; [SerializeField] public float[] defenseForNPC; [SerializeField] public float[] randomMinimumDamageModifierForNPC; // minimum value that NPC damage can be [SerializeField] public HealthManager[] healthObjectsRegistration; // List of objects with health, used for fast application of damage in explosions public GameObject[] levelChunks; //System constants public float doubleClickTime = 0.500f; public float frobDistance = 5f; public GameObject player1; public GameObject player2; public GameObject player3; public GameObject player4; public GameObject allPlayers; public float playerCameraOffsetY = 0.84f; //Vertical camera offset from player 0,0,0 position (mid-body) public Color ssYellowText = new Color(0.8902f, 0.8745f, 0f); // Yellow, e.g. for current inventory text public Color ssGreenText = new Color(0.3725f, 0.6549f, 0.1686f); // Green, e.g. for inventory text //Patch constants public float berserkTime = 15.5f; public float detoxTime = 60f; public float geniusTime = 35f; public float mediTime = 35f; public float reflexTime = 155f; public float sightTime= 35f; public float sightSideEffectTime = 10f; public float staminupTime = 60f; public float reflexTimeScale = 0.25f; public float defaultTimeScale = 1.0f; public float berserkDamageMultiplier = 4.0f; //Grenade constants public float nitroMinTime = 1.0f; public float nitroMaxTime = 60.0f; public float nitroDefaultTime = 7.0f; public float earthShMinTime = 4.0f; public float earthShMaxTime = 60.0f; public float earthShDefaultTime = 10.0f; //Pool references public enum PoolType {SparqImpacts,CameraExplosions,ProjEnemShot2,Sec2BotRotMuzBursts,Sec2BotMuzBursts, LaserLines,SparksSmall,BloodSpurtSmall,BloodSpurtSmallYellow,BloodSpurtSmallGreen, SparksSmallBlue,LaserLinesHopper,HopperImpact,GrenadeFragExplosions,Vaporize, LaserLinesBlaster, LaserLinesIon, BlasterImpacts, IonImpacts, MagpulseShots, MagpulseImpacts, StungunShots, StungunImpacts, RailgunShots, RailgunImpacts,PlasmaShots, PlasmaImpacts}; public GameObject Pool_SparqImpacts; public GameObject Pool_CameraExplosions; public GameObject Pool_ProjectilesEnemShot2; public GameObject Pool_Sec2BotRotaryMuzzleBursts; public GameObject Pool_Sec2BotMuzzleBursts; public GameObject Pool_LaserLines; public GameObject Pool_BloodSpurtSmall; public GameObject Pool_SparksSmall; public GameObject Pool_SparksSmallBlue; public GameObject Pool_BloodSpurtSmallYellow; public GameObject Pool_BloodSpurtSmallGreen; public GameObject Pool_LaserLinesHopper; public GameObject Pool_HopperImpact; public GameObject Pool_GrenadeFragExplosions; public GameObject Pool_Vaporize; public GameObject Pool_LaserLinesBlaster; public GameObject Pool_LaserLinesIon; public GameObject Pool_BlasterImpacts; public GameObject Pool_IonImpacts; public GameObject Pool_MagpulseShots; public GameObject Pool_MagpulseImpacts; public GameObject Pool_StungunShots; public GameObject Pool_StungunImpacts; public GameObject Pool_RailgunShots; public GameObject Pool_RailgunImpacts; public GameObject Pool_PlasmaShots; public GameObject Pool_PlasmaImpacts; //Global object references public GameObject statusBar; //Config constants public int difficultyCombat; public int difficultyMission; public int difficultyPuzzle; public int difficultyCyber; public string playerName; public AudioSource mainmenuMusic; public int GraphicsResWidth; public int GraphicsResHeight; public bool GraphicsFullscreen; public bool GraphicsSSAO; public bool GraphicsBloom; public int GraphicsFOV; public int GraphicsGamma; public int AudioSpeakerMode; public bool AudioReverb; public int AudioVolumeMaster; public int AudioVolumeMusic; public int AudioVolumeMessage; public int AudioVolumeEffects; public int AudioLanguage; public bool AudioSubtitles; public int[] InputCodeSettings; public string[] InputCodes; public string[] InputValues; public string[] InputConfigNames; public bool InputInvertLook; public bool InputInvertCyberspaceLook; public bool InputInvertInventoryCycling; public bool InputQuickItemPickup; public bool InputQuickReloadWeapons; public enum aiState{Idle,Walk,Run,Attack1,Attack2,Attack3,Pain,Dying,Dead,Inspect,Interacting}; public enum aiMoveType {Walk,Fly,Swim,Cyber,None}; public Font mainFont1; public Font mainFont2; public Font mainFont3; //Instance container variable public static Const a; // Private CONSTANTS private int MAX_HEALTHOBJECTS = 1024; private int TARGET_FPS = 60; // Instantiate it so that it can be accessed globally. MOST IMPORTANT PART!! // ========================================================================= void Awake() { Application.targetFrameRate = TARGET_FPS; a = this; //for (int i=0;i<Display.displays.Length;i++) { // Display.displays[i].Activate(); //} FindPlayers(); } // ========================================================================= private void FindPlayers() { List<GameObject> playerGameObjects = new List<GameObject>(); // Find all gameobjects with SaveObject script attached GameObject[] getAllGameObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); foreach (GameObject gob in getAllGameObjects) { if (gob.GetComponentInChildren<PlayerReferenceManager>() != null && gob.GetComponent<RuntimeObject>().isRuntimeObject == true) playerGameObjects.Add(gob); } if (playerGameObjects.Count > 0) player1 = playerGameObjects[0]; if (playerGameObjects.Count > 1) player2 = playerGameObjects[1]; if (playerGameObjects.Count > 2) player3 = playerGameObjects[2]; if (playerGameObjects.Count > 3) player4 = playerGameObjects[3]; allPlayers = new GameObject(); allPlayers.name = "<NAME>"; // for use in self printing Sprint() function for sending messages to HUD on all players } void Start() { LoadConfig(); LoadAudioLogMetaData(); LoadItemNamesData(); LoadDamageTablesData(); LoadEnemyTablesData(); questData = new QuestBits (); if (mainFont1 != null) mainFont1.material.mainTexture.filterMode = FilterMode.Point; if (mainFont2 != null) mainFont2.material.mainTexture.filterMode = FilterMode.Point; if (mainFont3 != null) mainFont3.material.mainTexture.filterMode = FilterMode.Point; } private void LoadConfig() { // Graphics Configurations GraphicsResWidth = AssignConfigInt("Graphics","ResolutionWidth"); GraphicsResHeight = AssignConfigInt("Graphics","ResolutionHeight"); GraphicsFullscreen = AssignConfigBool("Graphics","Fullscreen"); GraphicsSSAO = AssignConfigBool("Graphics","SSAO"); GraphicsBloom = AssignConfigBool("Graphics","Bloom"); GraphicsFOV = AssignConfigInt("Graphics","FOV"); GraphicsGamma = AssignConfigInt("Graphics","Gamma"); // Audio Configurations AudioSpeakerMode = AssignConfigInt("Audio","SpeakerMode"); AudioReverb = AssignConfigBool("Audio","Reverb"); AudioVolumeMaster = AssignConfigInt("Audio","VolumeMaster"); AudioVolumeMusic = AssignConfigInt("Audio","VolumeMusic"); AudioVolumeMessage = AssignConfigInt("Audio","VolumeMessage"); AudioVolumeEffects = AssignConfigInt("Audio","VolumeEffects"); AudioLanguage = AssignConfigInt("Audio","Language"); // defaults to 0 = english AudioSubtitles = AssignConfigBool("Audio","Subtitles"); // Input Configurations for (int i=0;i<40;i++) { string inputCapture = INIWorker.IniReadValue("Input",InputCodes[i]); for (int j=0;j<159;j++) { if (InputValues[j] == inputCapture) { InputCodeSettings[i] = j; } } } InputInvertLook = AssignConfigBool("Input","InvertLook"); InputInvertCyberspaceLook = AssignConfigBool("Input","InvertCyberspaceLook"); InputInvertInventoryCycling = AssignConfigBool("Input","InvertInventoryCycling"); InputQuickItemPickup = AssignConfigBool("Input","QuickItemPickup"); InputQuickReloadWeapons = AssignConfigBool("Input","QuickReloadWeapons"); SetVolume(); Screen.SetResolution(GraphicsResWidth,GraphicsResHeight,true); Screen.fullScreen = Const.a.GraphicsFullscreen; } public void WriteConfig() { INIWorker.IniWriteValue("Graphics","ResolutionWidth",GraphicsResWidth.ToString()); INIWorker.IniWriteValue("Graphics","ResolutionHeight",GraphicsResHeight.ToString()); INIWorker.IniWriteValue("Graphics","Fullscreen",GetBoolAsString(GraphicsFullscreen)); INIWorker.IniWriteValue("Graphics","SSAO",GetBoolAsString(GraphicsSSAO)); INIWorker.IniWriteValue("Graphics","Bloom",GetBoolAsString(GraphicsBloom)); INIWorker.IniWriteValue("Graphics","FOV",GraphicsFOV.ToString()); INIWorker.IniWriteValue("Graphics","Gamma",GraphicsGamma.ToString()); INIWorker.IniWriteValue("Audio","SpeakerMode",AudioSpeakerMode.ToString()); INIWorker.IniWriteValue("Audio","Reverb",GetBoolAsString(AudioReverb)); INIWorker.IniWriteValue("Audio","VolumeMaster",AudioVolumeMaster.ToString()); INIWorker.IniWriteValue("Audio","VolumeMusic",AudioVolumeMusic.ToString()); INIWorker.IniWriteValue("Audio","VolumeMessage",AudioVolumeMessage.ToString()); INIWorker.IniWriteValue("Audio","VolumeEffects",AudioVolumeEffects.ToString()); INIWorker.IniWriteValue("Audio","Language",AudioLanguage.ToString()); INIWorker.IniWriteValue("Audio","Subtitles",GetBoolAsString(AudioSubtitles)); for (int i=0;i<40;i++) { INIWorker.IniWriteValue("Input",InputCodes[i],InputValues[InputCodeSettings[i]]); } INIWorker.IniWriteValue("Input","InvertLook",GetBoolAsString(InputInvertLook)); INIWorker.IniWriteValue("Input","InvertCyberspaceLook",GetBoolAsString(InputInvertCyberspaceLook)); INIWorker.IniWriteValue("Input","InvertInventoryCycling",GetBoolAsString(InputInvertInventoryCycling)); INIWorker.IniWriteValue("Input","QuickItemPickup",GetBoolAsString(InputQuickItemPickup)); INIWorker.IniWriteValue("Input","QuickReloadWeapons",GetBoolAsString(InputQuickReloadWeapons)); SetBloom(); SetSSAO(); } private void LoadAudioLogMetaData () { // The following to be assigned to the arrays in the Unity Const data structure int readIndexOfLog; // look-up index for assigning the following data on the line in the file to the arrays string readLogText; // loaded into string audioLogSpeech2Text[] string readline; // variable to hold each string read in from the file int currentline = 0; StreamReader dataReader = new StreamReader(Application.dataPath + "/StreamingAssets/logs_text.txt",Encoding.Default); using (dataReader) { do { int i = 0; // Read the next line readline = dataReader.ReadLine(); if (readline == null) continue; // just in case //char[] delimiters = new char[] {','}; string[] entries = readline.Split(','); readIndexOfLog = GetIntFromString(entries[i],currentline,"logs_text",i); i++; audiologNames[readIndexOfLog] = entries[i]; i++; audiologSenders[readIndexOfLog] = entries[i]; i++; audiologSubjects[readIndexOfLog] = entries[i]; i++; audioLogType[readIndexOfLog] = GetIntFromString(entries[i],currentline,"logs_text",i); i++; audioLogLevelFound[readIndexOfLog] = GetIntFromString(entries[i],currentline,"logs_text",i); i++; readLogText = entries[i]; i++; // handle extra commas within the body text and append remaining portions of the line if (entries.Length > 7) { for (int j=7;j<entries.Length;j++) { //Debug.Log("Combining remaining comma'ed sections of log text: " + j.ToString()); readLogText = (readLogText +"," + entries[j]); // combine remaining portions of text after other commas and add comma back } } audioLogSpeech2Text[readIndexOfLog] = readLogText; currentline++; } while (!dataReader.EndOfStream); dataReader.Close(); return; } } private void LoadItemNamesData () { string readline; // variable to hold each string read in from the file int currentline = 0; StreamReader dataReader = new StreamReader(Application.dataPath + "/StreamingAssets/item_names.txt",Encoding.Default); using (dataReader) { do { // Read the next line readline = dataReader.ReadLine(); if (readline == null) break; // just in case useableItemsNameText[currentline] = readline; currentline++; } while (!dataReader.EndOfStream); dataReader.Close(); return; } } private void LoadDamageTablesData () { string readline; // variable to hold each string read in from the file int currentline = 0; int readInt = 0; StreamReader dataReader = new StreamReader(Application.dataPath + "/StreamingAssets/damage_tables.txt",Encoding.Default); using (dataReader) { do { int i = 0; // Read the next line readline = dataReader.ReadLine(); //char[] delimiters = new char[] {','}; string[] entries = readline.Split(','); //isFullAutoForWeapon[currentline] = GetBoolFromString(entries[i]); i++; isFullAutoForWeapon[currentline] = true; i++; delayBetweenShotsForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; delayBetweenShotsForWeapon2[currentline] = GetFloatFromString(entries[i],currentline); i++; damagePerHitForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; damagePerHitForWeapon2[currentline] = GetFloatFromString(entries[i],currentline); i++; damageOverloadForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; energyDrainLowForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; energyDrainHiForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; energyDrainOverloadForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; penetrationForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; penetrationForWeapon2[currentline] = GetFloatFromString(entries[i],currentline); i++; offenseForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; offenseForWeapon2[currentline] = GetFloatFromString(entries[i],currentline); i++; rangeForWeapon[currentline] = GetFloatFromString(entries[i],currentline); i++; readInt = GetIntFromString(entries[i],currentline,"damage_tables",i); i++; attackTypeForWeapon[currentline] = GetAttackTypeFromInt(readInt); currentline++; } while (!dataReader.EndOfStream); dataReader.Close(); return; } } private void LoadEnemyTablesData() { //case 1: return AttackType.Melee; //case 2: return AttackType.EnergyBeam; //case 3: return AttackType.Magnetic; //case 4: return AttackType.Projectile; //case 5: return AttackType.ProjectileEnergyBeam; //case 1: return PerceptionLevel.Medium; //case 2: return PerceptionLevel.High; //case 3: return PerceptionLevel.Omniscient; string readline; // variable to hold each string read in from the file int currentline = 0; int readInt = 0; StreamReader dataReader = new StreamReader(Application.dataPath + "/StreamingAssets/enemy_tables.txt",Encoding.Default); using (dataReader) { do { int i = 0; // Read the next line readline = dataReader.ReadLine(); string[] entries = readline.Split(','); char[] commentCheck = entries[i].ToCharArray(); if (commentCheck[0] == '/' && commentCheck[1] == '/') { currentline++; continue; // Skip lines that start with '//' } nameForNPC[currentline] = entries[i]; i++; readInt = GetIntFromString(entries[i],currentline,"enemy_tables",i); i++; attackTypeForNPC[currentline] = GetAttackTypeFromInt(readInt); readInt = GetIntFromString(entries[i],currentline,"enemy_tables",i); i++; attackTypeForNPC2[currentline] = GetAttackTypeFromInt(readInt); readInt = GetIntFromString(entries[i],currentline,"enemy_tables",i); i++; attackTypeForNPC3[currentline] = GetAttackTypeFromInt(readInt); damageForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; damageForNPC2[currentline] = GetFloatFromString(entries[i],currentline); i++; damageForNPC3[currentline] = GetFloatFromString(entries[i],currentline); i++; rangeForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; rangeForNPC2[currentline] = GetFloatFromString(entries[i],currentline); i++; rangeForNPC3[currentline] = GetFloatFromString(entries[i],currentline); i++; healthForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; readInt = GetIntFromString(entries[i],currentline,"enemy_tables",i); i++; perceptionForNPC[currentline] = GetPerceptionLevelFromInt(readInt); disruptabilityForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; armorvalueForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; defenseForNPC[currentline] = GetFloatFromString(entries[i],currentline); i++; randomMinimumDamageModifierForNPC[currentline] = GetFloatFromString(entries[i],currentline); currentline++; if (currentline > 23) break; } while (!dataReader.EndOfStream); dataReader.Close(); return; } } // StatusBar Print public static void sprint (string input, GameObject player) { Debug.Log(input); // print to console if (player == null) return; if (a != null) { if (player.name == "All Players") { if (a.player1 != null) a.player1.GetComponent<PlayerReferenceManager>().playerStatusBar.GetComponent<StatusBarTextDecay>().SendText(input); if (a.player2 != null) a.player2.GetComponent<PlayerReferenceManager>().playerStatusBar.GetComponent<StatusBarTextDecay>().SendText(input); if (a.player3 != null) a.player3.GetComponent<PlayerReferenceManager>().playerStatusBar.GetComponent<StatusBarTextDecay>().SendText(input); if (a.player4 != null) a.player4.GetComponent<PlayerReferenceManager>().playerStatusBar.GetComponent<StatusBarTextDecay>().SendText(input); } else { player.GetComponent<PlayerReferenceManager>().playerStatusBar.GetComponent<StatusBarTextDecay>().SendText(input); } } } public GameObject GetObjectFromPool(PoolType pool) { GameObject poolContainer = Pool_SparksSmall; string poolName = " "; switch (pool) { case PoolType.SparksSmall: poolContainer = Pool_SparksSmall; poolName = "SparksSmall "; break; case PoolType.SparqImpacts: poolContainer = Pool_SparqImpacts; poolName = "SparqImpacts "; break; case PoolType.CameraExplosions: poolContainer = Pool_CameraExplosions; poolName = "CameraExplosions "; break; case PoolType.ProjEnemShot2: poolContainer = Pool_ProjectilesEnemShot2; poolName = "ProjectilesEnemShot2 "; break; case PoolType.Sec2BotRotMuzBursts: poolContainer = Pool_Sec2BotRotaryMuzzleBursts; poolName = "Sec2BotRotaryMuzzleBursts "; break; case PoolType.Sec2BotMuzBursts: poolContainer = Pool_Sec2BotMuzzleBursts; poolName = "Sec2BotMuzzleBursts "; break; case PoolType.LaserLines: poolContainer = Pool_LaserLines; poolName = "LaserLines "; break; case PoolType.BloodSpurtSmall: poolContainer = Pool_BloodSpurtSmall; poolName = "BloodSpurtSmall "; break; case PoolType.BloodSpurtSmallYellow: poolContainer = Pool_BloodSpurtSmallYellow; poolName = "BloodSpurtSmallYellow "; break; case PoolType.BloodSpurtSmallGreen: poolContainer = Pool_BloodSpurtSmallGreen; poolName = "BloodSpurtSmallGreen "; break; case PoolType.SparksSmallBlue: poolContainer = Pool_SparksSmallBlue; poolName = "BloodSpurtSmall "; break; case PoolType.LaserLinesHopper: poolContainer = Pool_LaserLinesHopper; poolName = "LaserLinesHopper "; break; case PoolType.HopperImpact: poolContainer = Pool_HopperImpact; poolName = "HopperImpact "; break; case PoolType.GrenadeFragExplosions: poolContainer = Pool_GrenadeFragExplosions; poolName = "GrenadeFragExplosions "; break; case PoolType.Vaporize: poolContainer = Pool_Vaporize; poolName = "Vaporize "; break; case PoolType.LaserLinesBlaster: poolContainer = Pool_LaserLinesBlaster; poolName = "LaserLinesBlaster "; break; case PoolType.LaserLinesIon: poolContainer = Pool_LaserLinesIon; poolName = "LaserLinesIon "; break; case PoolType.BlasterImpacts: poolContainer = Pool_BlasterImpacts; poolName = "BlasterImpacts "; break; case PoolType.IonImpacts: poolContainer = Pool_IonImpacts; poolName = "IonImpacts "; break; case PoolType.MagpulseShots: poolContainer = Pool_MagpulseShots; poolName = "MagpulseShots "; break; case PoolType.MagpulseImpacts: poolContainer = Pool_MagpulseImpacts; poolName = "MagpulseImpacts "; break; case PoolType.StungunShots: poolContainer = Pool_StungunShots; poolName = "StungunShots "; break; case PoolType.StungunImpacts: poolContainer = Pool_StungunImpacts; poolName = "StungunImpacts "; break; case PoolType.RailgunShots: poolContainer = Pool_RailgunShots; poolName = "RailgunShots "; break; case PoolType.RailgunImpacts: poolContainer = Pool_RailgunImpacts; poolName = "RailgunImpacts "; break; case PoolType.PlasmaShots: poolContainer = Pool_PlasmaShots; poolName = "PlasmaShots "; break; case PoolType.PlasmaImpacts: poolContainer = Pool_PlasmaImpacts; poolName = "PlasmaImpacts "; break; } if (poolContainer == null) { sprint("Cannot find " + poolName + "pool",allPlayers); return null; } for (int i=0;i<poolContainer.transform.childCount;i++) { Transform child = poolContainer.transform.GetChild(i); if (child.gameObject.activeInHierarchy == false) { return child.gameObject; } } return null; } // ========================DAMAGE SYSTEM=========================== // 0. First checks against whether the entity is damageable (i.e. not the world) // 1. Armor absorption (see ICE Breaker Guide for all of 4 these) // 2. Weapon vulnerabilities based on attack type and the a_att_type bits stored in the npc // 3. Critical hits, chance for critical hit damage based on defense and offense of attack and target // 4. Random Factor, +/- 10% damage for randomness // 5. Apply velocity for damage, this is after all the above because otherwise the damage multipliers wouldn't affect velocity // 6. Return the damage to original TakeDamage() function public float GetDamageTakeAmount (DamageData dd) { // a_* = attacker float a_damage = dd.damage; float a_offense = dd.offense; float a_penetration = dd.penetration; AttackType a_att_type = dd.attackType; bool a_berserk = dd.berserkActive; // o_* = other (one being attacked) bool o_isnpc = dd.isOtherNPC; float o_armorvalue = dd.armorvalue; float o_defense = dd.defense; float take = 0f; float chance = 0f; float f = 0f; // 1. Armor Absorption if (o_armorvalue > a_penetration) { take = (a_damage - a_penetration); } else { take = a_damage; } // 2. Weapon Vulnerabilities if (a_att_type != AttackType.None) { } // 3. Critical Hits (NPCs only) if (o_isnpc) { f = (a_offense - o_defense); float crit = f; if (f > 0) { // 71% success with 5/6 5 = f, 6 = max offense or defense value // 62% success with 4/6 // 50% success with 3/6 // 24% success with 2/6 // 10% success with 1/6 chance = (f/6); // 5/6|4/6|3/6|2/6|1/6 = .833|.666|.5|.333|.166 if (f == 1) chance = 0.280f; //anything less than 0.25, 0.1666 in this case taken from 1/6, will fail chance = (chance * UnityEngine.Random.Range(0f,1f) * 2); if (chance > 0.5f) { // SUCCESS! Applying critical hit. crit = (take * f); //How many extra damages we add to damage that we will take take = (take + crit); // Maximum extra is 5X + 1X Damage } } } // 4. Random Factor +/- 10% (aka 0.10 damage) chance = (0.1f * UnityEngine.Random.Range(0f,1f)); // 50% chance of being positive or negative f = UnityEngine.Random.Range(0f,1f); if (f > 0.5f) { chance = (chance * (-1)); // Make negative } chance = (chance * take); take = (take + chance); // Add the random factor, anywhere up to +/- 10% if (take <= 0f) return take; // 5. Apply Velocity for Damage Amount // 6. Specialties if (a_berserk) take *= Const.a.berserkDamageMultiplier; // 6. Return the Damage return take; } public static void drawDebugLine(Vector3 start , Vector3 end, Color color,float duration = 0.2f){ GameObject myLine = new GameObject (); myLine.transform.position = start; myLine.AddComponent<LineRenderer> (); LineRenderer lr = myLine.GetComponent<LineRenderer> (); lr.material = new Material (Shader.Find ("Particles/Additive")); lr.startColor = color; lr.endColor = color; lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.SetPosition (0, start); lr.SetPosition (1, end); Destroy(myLine,duration); } // Save the Game // ============================================================================ public void Save(int saveFileIndex) { string[] saveData = new string[4096]; string line; int i,j; int index = 0; Transform tr, trml; List<GameObject> playerGameObjects = new List<GameObject>(); List<GameObject> saveableGameObjects = new List<GameObject>(); // Indicate we are saving sprint("Saving...",allPlayers); // Header // ----------------------------------------------------- // Save Name saveData[index] = "TODO: SAVEGAME NAME ENTRY"; index++; // temp string to hold global states TODO: actually pull in the global states to this string string states = "00000000|00000000|"; // Global states and Difficulties saveData[index] = (LevelManager.a.currentLevel.ToString() + "|" + states + difficultyCombat.ToString() + "|" + difficultyMission.ToString() + "|" + difficultyPuzzle.ToString() + "|" + difficultyCyber.ToString()); index++; // Find all gameobjects with SaveObject script attached GameObject[] getAllGameObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); foreach (GameObject gob in getAllGameObjects) { if (gob.GetComponentInChildren<PlayerReferenceManager>() != null && gob.GetComponent<RuntimeObject>().isRuntimeObject == true) playerGameObjects.Add(gob); if (gob.GetComponent<SaveObject>() != null && gob.GetComponent<RuntimeObject>().isRuntimeObject == true) saveableGameObjects.Add(gob); } sprint("Num players: " + playerGameObjects.Count.ToString(),allPlayers); // Save all the players' data for (i=0;i<playerGameObjects.Count;i++) { // First get all references to relevant componenets on all relevant gameobjects in the player gameobject PlayerReferenceManager PRman = playerGameObjects[i].GetComponent<PlayerReferenceManager>(); GameObject pCap = PRman.playerCapsule; GameObject playerMainCamera = PRman.playerCapsuleMainCamera; GameObject playerInventory = PRman.playerInventory; PlayerHealth ph = pCap.GetComponent<PlayerHealth>(); PlayerEnergy pe = pCap.GetComponent<PlayerEnergy>(); PlayerMovement pm = pCap.GetComponent<PlayerMovement>(); PlayerPatch pp = pCap.GetComponent<PlayerPatch>(); tr = pCap.transform; MouseLookScript ml = playerMainCamera.GetComponent<MouseLookScript>(); trml = playerMainCamera.transform; WeaponInventory wi = playerInventory.GetComponent<WeaponInventory>(); WeaponAmmo wa = playerInventory.GetComponent<WeaponAmmo>(); WeaponCurrent wc = playerInventory.GetComponent<WeaponCurrent>(); GrenadeCurrent gc = playerInventory.GetComponent<GrenadeCurrent>(); GrenadeInventory gi = playerInventory.GetComponent<GrenadeInventory>(); PatchCurrent pc = playerInventory.GetComponent<PatchCurrent>(); PatchInventory pi = playerInventory.GetComponent<PatchInventory>(); LogInventory li = playerInventory.GetComponent<LogInventory>(); HardwareInventory hi = playerInventory.GetComponent<HardwareInventory>(); line = playerGameObjects[i].GetInstanceID().ToString(); line += "|" + Const.a.playerName; line += "|" + ph.hm.health.ToString("0000.00000"); line += "|" + pe.energy.ToString("0000.00000"); line += "|" + pm.currentCrouchRatio.ToString("0000.00000"); line += "|" + pm.bodyState.ToString(); line += "|" + pm.ladderState.ToString(); line += "|" + pm.gravliftState.ToString(); line += "|" + pp.patchActive.ToString(); line += "|" + pp.berserkIncrement.ToString(); line += "|" + pp.sightFinishedTime.ToString("0000.00000"); line += "|" + pp.staminupFinishedTime.ToString("0000.00000"); line += "|" + (tr.localPosition.x.ToString("0000.00000") + "|" + tr.localPosition.y.ToString("0000.00000") + "|" + tr.localPosition.z.ToString("0000.00000")); line += "|" + (tr.localRotation.x.ToString("0000.00000") + "|" + tr.localRotation.y.ToString("0000.00000") + "|" + tr.localRotation.z.ToString("0000.00000") + "|" + tr.localRotation.w.ToString("0000.00000")); line += "|" + (tr.localScale.x.ToString("0000.00000") + "|" + tr.localScale.y.ToString("0000.00000") + "|" + tr.localScale.z.ToString("0000.00000")); line += "|" + (trml.localPosition.x.ToString("0000.00000") + "|" + trml.localPosition.y.ToString("0000.00000") + "|" + trml.localPosition.z.ToString("0000.00000")); line += "|" + (trml.localRotation.x.ToString("0000.00000") + "|" + trml.localRotation.y.ToString("0000.00000") + "|" + trml.localRotation.z.ToString("0000.00000") + "|" + trml.localRotation.w.ToString("0000.00000")); line += "|" + (trml.localScale.x.ToString("0000.00000") + "|" + trml.localScale.y.ToString("0000.00000") + "|" + trml.localScale.z.ToString("0000.00000")); line += "|" + ml.inventoryMode.ToString(); line += "|" + ml.holdingObject.ToString(); line += "|" + ml.heldObjectIndex.ToString(); line += "|" + ml.heldObjectCustomIndex.ToString(); line += "|" + GUIState.a.overButtonType.ToString(); line += "|" + GUIState.a.overButton.ToString(); line += "|" + ml.geniusActive.ToString(); for (j=0;j<7;j++) { line += "|" + wi.weaponInventoryIndices[j].ToString(); } for (j=0;j<7;j++) { line += "|" + wi.weaponInventoryAmmoIndices[j].ToString(); } for (j=0;j<16;j++) { line += "|" + wi.hasWeapon[j].ToString(); } for (j=0;j<16;j++) { line += "|" + wa.wepAmmo[j].ToString(); } line += "|" + wc.weaponCurrent.ToString(); line += "|" + wc.weaponIndex.ToString(); line += "|" + gc.grenadeCurrent.ToString(); line += "|" + gc.grenadeIndex.ToString(); for (j=0;j<7;j++) { line += "|" + gi.grenAmmo[j].ToString(); } line += "|" + pc.patchCurrent.ToString(); line += "|" + pc.patchIndex.ToString(); for (j=0;j<7;j++) { line += "|" + pi.patchCounts[j].ToString(); } for (j=0;j<128;j++) { line += "|" + li.hasLog[j].ToString(); } for (j=0;j<128;j++) { line += "|" + li.readLog[j].ToString(); } for (j=0;j<10;j++) { line += "|" + li.numLogsFromLevel[j].ToString(); } line += "|" + li.lastAddedIndex.ToString(); for (j=0;j<12;j++) { line += "|" + hi.hasHardware[j].ToString(); } for (j=0;j<12;j++) { line += "|" + hi.hardwareVersion[j].ToString(); } saveData[index] = line; index++; } // Save all the objects data for (i=0;i<saveableGameObjects.Count;i++) { line = saveableGameObjects[i].GetComponent<SaveObject>().SaveID.ToString(); line += "|" + saveableGameObjects[i].activeInHierarchy.ToString(); tr = saveableGameObjects[i].GetComponent<Transform>(); line += "|" + (tr.localPosition.x.ToString("0000.00000") + "|" + tr.localPosition.y.ToString("0000.00000") + "|" + tr.localPosition.z.ToString("0000.00000")); line += "|" + (tr.localRotation.x.ToString("0000.00000") + "|" + tr.localRotation.y.ToString("0000.00000") + "|" + tr.localRotation.z.ToString("0000.00000") + "|" + tr.localRotation.w.ToString("0000.00000")); line += "|" + (tr.localScale.x.ToString("0000.00000") + "|" + tr.localScale.y.ToString("0000.00000") + "|" + tr.localScale.z.ToString("0000.00000")); saveData[index] = line; index++; } // Write to file StreamWriter sw = new StreamWriter(Application.streamingAssetsPath + "/sav"+saveFileIndex.ToString()+".txt"); if (sw != null) { using (sw) { for (j=0;j<saveData.Length;j++) { sw.WriteLine(saveData[j]); } sw.Close(); } } // Make "Done!" appear at the end of the line after "Saving..." is finished, stole this from Halo sprint("Saving...Done!",allPlayers); } void LoadPlayerDataToPlayer(GameObject currentPlayer, string[] entries, int currentline) { int index = 1; // Already parsed ID number in main Load() function, skip index 0 int j; float readFloatx; float readFloaty; float readFloatz; float readFloatw; PlayerReferenceManager PRman = currentPlayer.GetComponent<PlayerReferenceManager>(); GameObject pCap = PRman.playerCapsule; GameObject playerMainCamera = PRman.playerCapsuleMainCamera; GameObject playerInventory = PRman.playerInventory; PlayerHealth ph = pCap.GetComponent<PlayerHealth>(); PlayerEnergy pe = pCap.GetComponent<PlayerEnergy>(); PlayerMovement pm = pCap.GetComponent<PlayerMovement>(); PlayerPatch pp = pCap.GetComponent<PlayerPatch>(); Transform tr = pCap.transform; MouseLookScript ml = playerMainCamera.GetComponent<MouseLookScript>(); Transform trml = playerMainCamera.transform; WeaponInventory wi = playerInventory.GetComponent<WeaponInventory>(); WeaponAmmo wa = playerInventory.GetComponent<WeaponAmmo>(); WeaponCurrent wc = playerInventory.GetComponent<WeaponCurrent>(); GrenadeCurrent gc = playerInventory.GetComponent<GrenadeCurrent>(); GrenadeInventory gi = playerInventory.GetComponent<GrenadeInventory>(); PatchCurrent pc = playerInventory.GetComponent<PatchCurrent>(); PatchInventory pi = playerInventory.GetComponent<PatchInventory>(); LogInventory li = playerInventory.GetComponent<LogInventory>(); HardwareInventory hi = playerInventory.GetComponent<HardwareInventory>(); Const.a.playerName = entries[index]; index++; ph.hm.health = GetFloatFromString(entries[index],currentline); index++; pe.energy = GetFloatFromString(entries[index],currentline); index++; pm.currentCrouchRatio = GetFloatFromString(entries[index],currentline); index++; pm.bodyState = GetIntFromString(entries[index],currentline,"savegame",index); index++; pm.ladderState = GetBoolFromString(entries[index]); index++; pm.gravliftState = GetBoolFromString(entries[index]); index++; pp.patchActive = GetIntFromString(entries[index],currentline,"savegame",index); index++; pp.berserkIncrement = GetIntFromString(entries[index],currentline,"savegame",index); index++; pp.sightFinishedTime = GetFloatFromString(entries[index],currentline); index++; pp.staminupFinishedTime = GetFloatFromString(entries[index],currentline); index++; readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; tr.localPosition = new Vector3(readFloatx,readFloaty,readFloatz); readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; readFloatw = GetFloatFromString(entries[index],currentline); index++; tr.localRotation = new Quaternion(readFloatx,readFloaty,readFloatz,readFloatw); readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; tr.localScale = new Vector3(readFloatx,readFloaty,readFloatz); readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; trml.localPosition = new Vector3(readFloatx,readFloaty,readFloatz); readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; readFloatw = GetFloatFromString(entries[index],currentline); index++; trml.localRotation = new Quaternion(readFloatx,readFloaty,readFloatz,readFloatw); readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; trml.localScale = new Vector3(readFloatx,readFloaty,readFloatz); ml.inventoryMode = !GetBoolFromString(entries[index]); index++; // take opposite because we are about to opposite again ml.ToggleInventoryMode(); // correctly set cursor lock state, and opposite again, now it is what was saved ml.holdingObject = GetBoolFromString(entries[index]); index++; ml.heldObjectIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; ml.heldObjectCustomIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; GUIState.ButtonType bt = (GUIState.ButtonType) Enum.Parse(typeof(GUIState.ButtonType), entries[index]); if (Enum.IsDefined(typeof(GUIState.ButtonType),bt)) { GUIState.a.overButtonType = bt; } index++; GUIState.a.overButton = GetBoolFromString(entries[index]); index++; ml.geniusActive = GetBoolFromString(entries[index]); index++; for (j=0;j<7;j++) { wi.weaponInventoryIndices[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } for (j=0;j<7;j++) { wi.weaponInventoryAmmoIndices[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } for (j=0;j<16;j++) { wi.hasWeapon[j] = GetBoolFromString(entries[index]); index++; } for (j=0;j<16;j++) { wa.wepAmmo[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } wc.weaponCurrent = GetIntFromString(entries[index],currentline,"savegame",index); index++; wc.weaponIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; gc.grenadeCurrent = GetIntFromString(entries[index],currentline,"savegame",index); index++; gc.grenadeIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; for (j=0;j<7;j++) { gi.grenAmmo[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } pc.patchCurrent = GetIntFromString(entries[index],currentline,"savegame",index); index++; pc.patchIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; for (j=0;j<7;j++) { pi.patchCounts[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } for (j=0;j<128;j++) { li.hasLog[j] = GetBoolFromString(entries[index]); index++; } for (j=0;j<128;j++) { li.readLog[j] = GetBoolFromString(entries[index]); index++; } for (j=0;j<10;j++) { li.numLogsFromLevel[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } li.lastAddedIndex = GetIntFromString(entries[index],currentline,"savegame",index); index++; for (j=0;j<12;j++) { hi.hasHardware[j] = GetBoolFromString(entries[index]); index++; } for (j=0;j<12;j++) { hi.hardwareVersion[j] = GetIntFromString(entries[index],currentline,"savegame",index); index++; } } void LoadObjectDataToObject(GameObject currentGameObject, string[] entries, int currentline) { int index = 1; // Already parsed ID number in main Load() function, skip index 0 float readFloatx; float readFloaty; float readFloatz; float readFloatw; Vector3 tempvec; // Set active state of GameObject in Hierarchy currentGameObject.SetActive(GetBoolFromString(entries[index])); index++; // Get transform readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; tempvec = new Vector3(readFloatx,readFloaty,readFloatz); currentGameObject.transform.localPosition = tempvec; // Get rotation readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; readFloatw = GetFloatFromString(entries[index],currentline); index++; Quaternion tempquat = new Quaternion(readFloatx,readFloaty,readFloatz,readFloatw); currentGameObject.transform.localRotation = tempquat; // Get scale readFloatx = GetFloatFromString(entries[index],currentline); index++; readFloaty = GetFloatFromString(entries[index],currentline); index++; readFloatz = GetFloatFromString(entries[index],currentline); index++; tempvec = new Vector3(readFloatx,readFloaty,readFloatz); currentGameObject.transform.localScale = tempvec; } public void Load(int saveFileIndex) { string readline; int currentline = 0; sprint("Loading...",allPlayers); List<GameObject> playerGameObjects = new List<GameObject>(); List<GameObject> saveableGameObjects = new List<GameObject>(); // Find all gameobjects with SaveObject script attached GameObject[] getAllGameObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject)); foreach (GameObject gob in getAllGameObjects) { if (gob.GetComponentInChildren<PlayerReferenceManager>() != null && gob.GetComponent<RuntimeObject>().isRuntimeObject == true) { playerGameObjects.Add(gob); } if (gob.GetComponent<SaveObject>() != null && gob.GetComponent<RuntimeObject>().isRuntimeObject == true) { saveableGameObjects.Add(gob); } } StreamReader sr = new StreamReader(Application.streamingAssetsPath + "/sav"+saveFileIndex.ToString()+".txt"); if (sr != null) { using (sr) { do { readline = sr.ReadLine(); if (readline == null) { currentline++; continue; // skip blank lines } string[] entries = readline.Split('|'); // delimited by | character, aka the vertical bar, pipe, obelisk, etc. if (entries.Length <= 1) { currentline++; continue; // Skip save name } if (currentline == 1) { // Read in global states int levelNum = GetIntFromString(entries[0],currentline,"savegame",0); LevelManager.a.LoadLevelFromSave(levelNum); currentline++; continue; } foreach (GameObject pl in playerGameObjects) { if (entries[0] == playerGameObjects[0].GetInstanceID().ToString()) { LoadPlayerDataToPlayer(pl,entries,currentline); break; } } foreach (GameObject ob in saveableGameObjects) { if (entries[0] == ob.GetComponent<SaveObject>().SaveID.ToString()) { LoadObjectDataToObject(ob,entries,currentline); break; } } currentline++; } while (!sr.EndOfStream); sr.Close(); } } sprint("Loading...Done!",allPlayers); } public void SetFOV() { if (player1 != null) player1.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().fieldOfView = GraphicsFOV; if (player2 != null) player2.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().fieldOfView = GraphicsFOV; if (player3 != null) player3.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().fieldOfView = GraphicsFOV; if (player4 != null) player4.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().fieldOfView = GraphicsFOV; } public void SetBloom() { if (player1 != null) player1.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.bloom.enabled = GraphicsBloom; if (player2 != null) player2.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.bloom.enabled = GraphicsBloom; if (player3 != null) player3.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.bloom.enabled = GraphicsBloom; if (player4 != null) player4.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.bloom.enabled = GraphicsBloom; } public void SetSSAO() { if (player1 != null) player1.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.ambientOcclusion.enabled = GraphicsSSAO; if (player2 != null) player2.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.ambientOcclusion.enabled = GraphicsSSAO; if (player3 != null) player3.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.ambientOcclusion.enabled = GraphicsSSAO; if (player4 != null) player4.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<PostProcessingBehaviour>().profile.ambientOcclusion.enabled = GraphicsSSAO; } public void SetBrightness() { float tempf = Const.a.GraphicsGamma; if (tempf < 1) tempf = 0; else tempf = tempf/100; if (player1 != null) player1.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<ColorCurvesManager>().Factor = tempf; if (player2 != null) player2.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<ColorCurvesManager>().Factor = tempf; if (player3 != null) player3.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<ColorCurvesManager>().Factor = tempf; if (player4 != null) player4.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera.GetComponent<Camera>().GetComponent<ColorCurvesManager>().Factor = tempf; } public void SetVolume() { AudioListener.volume = (AudioVolumeMaster/100f); mainmenuMusic.volume = (AudioVolumeMusic/100f); } public void RegisterObjectWithHealth(HealthManager hm) { for (int i=0;i<MAX_HEALTHOBJECTS;i++) { if (healthObjectsRegistration[i] == null) { healthObjectsRegistration[i] = hm; return; } if (i == (MAX_HEALTHOBJECTS - 1)) Debug.Log("WARNING: Could not register object with health. Hit limit of " + MAX_HEALTHOBJECTS.ToString() + "."); } } private int AssignConfigInt(string section, string keyname) { int inputInt = -1; string inputCapture = System.String.Empty; inputCapture = INIWorker.IniReadValue(section,keyname); if (inputCapture == null) inputCapture = "NULL"; bool parsed = Int32.TryParse(inputCapture, out inputInt); if (parsed) return inputInt; else sprint("Warning: Could not parse config key " + keyname + " as integer: " + inputCapture,allPlayers); return 0; } private bool AssignConfigBool(string section, string keyname) { int inputInt = -1; string inputCapture = System.String.Empty; inputCapture = INIWorker.IniReadValue(section,keyname); if (inputCapture == null) inputCapture = "NULL"; bool parsed = Int32.TryParse(inputCapture, out inputInt); if (parsed) { if (inputInt > 0) return true; else return false; } else sprint("Warning: Could not parse config key " + keyname + " as bool: " + inputCapture,allPlayers); return false; } public bool GetBoolFromString(string val) { if (val.ToLower() == "true") return true; else return false; } public int GetIntFromString(string val, int currentline, string source, int index) { bool parsed; int readInt; if (val == "0") return 0; parsed = Int32.TryParse(val,out readInt); if (!parsed) { sprint("BUG: Could not parse int from " + source + " file on line " + currentline.ToString() + ", from index: " + index.ToString(),allPlayers); return 0; } return readInt; } public float GetFloatFromString(string val, int currentline) { bool parsed; float readFloat; parsed = Single.TryParse(val,out readFloat); if (!parsed) { sprint("BUG: Could not parse float from save file on line " + currentline.ToString(),allPlayers); return 0.0f; } return readFloat; } public string GetBoolAsString(bool inputValue) { if (inputValue) return "1"; return "0"; } public AttackType GetAttackTypeFromInt(int att_type_i) { switch(att_type_i) { case 1: return AttackType.Melee; case 2: return AttackType.EnergyBeam; case 3: return AttackType.Magnetic; case 4: return AttackType.Projectile; case 5: return AttackType.ProjectileEnergyBeam; } return AttackType.None; } public PerceptionLevel GetPerceptionLevelFromInt(int percep_i) { switch(percep_i) { case 1: return PerceptionLevel.Medium; case 2: return PerceptionLevel.High; case 3: return PerceptionLevel.Omniscient; } return PerceptionLevel.Low; } public static DamageData SetNPCDamageData (int NPCindex, aiState attackIndex, GameObject ownedBy) { if (NPCindex < 0 || NPCindex > 23) { Debug.Log("BUG: NPCindex set incorrectly on NPC. Not 0 to 23 on NPC at: " + ownedBy.transform.position.x.ToString() + ", " + ownedBy.transform.position.y.ToString() + ", " + ownedBy.transform.position.z + "."); return null; } DamageData dd = new DamageData(); // Attacker (self [a]) data dd.owner = ownedBy; switch (attackIndex) { case aiState.Attack1: dd.damage = Const.a.damageForNPC[NPCindex]; break; case aiState.Attack2: dd.damage = Const.a.damageForNPC2[NPCindex]; break; case aiState.Attack3: dd.damage = Const.a.damageForNPC3[NPCindex]; break; default: Debug.Log("BUG: attackIndex not 0,1, or 2 on NPC! Damage set to 1."); dd.damage = 1f; break; } dd.penetration = 0; dd.offense = 0; return dd; } // Check if particular bit is 1 (ON/TRUE) in binary format of given integer public bool CheckFlags (int checkInt, int flag) { if ((checkInt & flag) != 0) return true; return false; } public static float AngleInDeg(Vector3 vec1, Vector3 vec2) { return ((Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x)) * (180 / Mathf.PI)); } public void UseTargets (UseData ud, GameObject[] targets) { for (int i = 0; i < targets.Length; i++) { if (targets [i] != null) targets [i].SendMessageUpwards ("Targetted", ud); } } public void UseTargets (UseData ud, GameObject target) { if (target != null) target.SendMessageUpwards ("Targetted", ud); } } public class QuestBits { public bool Level1SecNodesDestroyed; public bool Level2SecNodesDestroyed; public bool Level3SecNodesDestroyed; public bool Level4SecNodesDestroyed; public bool Level5SecNodesDestroyed; public bool Level6SecNodesDestroyed; public int lev1SecCode; public int lev2SecCode; public int lev3SecCode; public int lev4SecCode; public int lev5SecCode; public int lev6SecCode; public bool ShieldActivated; public bool LaserSafetyOverriden; public bool LaserDestroyed; public bool BetaGroveCyberUnlocked; public bool GroveAlphaJettisonEnabled; public bool GroveBetaJettisonEnabled; public bool GroveDeltaJettisonEnabled; public bool MasterJettisonBroken; public bool Relay428Fixed; public bool MasterJettisonEnabled; public bool BetaGroveJettisoned; public bool AntennaNorthDestroyed; public bool AntennaSouthDestroyed; public bool AntennaEastDestroyed; public bool AntennaWestDestroyed; public bool SelfDestructActivated; public bool BridgeSeparated; public bool IsolinearChipsetInstalled; }<file_sep>/Assets/Scripts/AIAnimationController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIAnimationController : MonoBehaviour { public float currentClipPercentage; public float clipEndThreshold = 0.99f; private Animator anim; private AnimatorStateInfo anstinfo; private AIController aic; private bool dying; private bool dead; void Awake () { anim = GetComponent<Animator>(); aic = GetComponent<AIController>(); currentClipPercentage = 0f; dead = false; } void Update () { if (dying) { Dying(); } else { if (dead) { Dead(); } else { switch (aic.currentState) { case Const.aiState.Idle: Idle(); break; case Const.aiState.Walk: Walk(); break; case Const.aiState.Run: Run(); break; case Const.aiState.Attack1: Attack1(); break; case Const.aiState.Attack2: Attack2(); break; case Const.aiState.Attack3: Attack3(); break; case Const.aiState.Pain: Pain(); break; case Const.aiState.Dying: Dying(); break; case Const.aiState.Inspect: Inspect(); break; case Const.aiState.Interacting: Interacting(); break; default: Idle(); break; } } } anstinfo = anim.GetCurrentAnimatorStateInfo(0); currentClipPercentage = anstinfo.normalizedTime % 1; } void Idle () { anim.Play("Idle"); } void Run () { anim.Play("Run"); } void Walk () { anim.Play("Walk"); } void Attack1 () { anim.Play("Attack1"); } void Attack2 () { anim.Play("Attack2"); } void Attack3 () { anim.Play("Attack3"); } void Pain () { anim.Play("Pain"); } void Dying () { dying = true; anim.Play("Death"); if (currentClipPercentage > clipEndThreshold) { dying = false; dead = true; } } void Dead () { anim.Play("Death"); anim.speed = 0f; } void Inspect () { anim.Play("Inspect"); } void Interacting () { anim.Play("Interact"); } } <file_sep>/Assets/Scripts/HeadMountedLantern.cs using UnityEngine; using System.Collections; public class HeadMountedLantern : MonoBehaviour { public int lanternState = 0; //public int lanternVersion = 1; //TODO: Set to 0 //public float lanternSetting = 1; public float lanternVersion1Brightness = 2.5f; public float lanternVersion2Brightness = 4; public float lanternVersion3Brightness = 5; [HideInInspector] public Light headlight; void Awake () { headlight = GetComponent<Light>(); } /*void Update (){ if (GetInput.a != null && GetInput.a.Lantern()) { float brightness = 0f; switch(lanternVersion) { case 1: brightness = lanternVersion1Brightness; break; case 2: brightness = lanternVersion2Brightness; break; case 3: brightness = lanternVersion3Brightness; break; default: brightness = 0f; break; } switch(lanternState) { case 0: headlight.intensity = brightness; lanternState = 1; break; default: headlight.intensity = 0f; lanternState = 0; break; } } }*/ }<file_sep>/Assets/Scripts/ConfigInputLabels.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigInputLabels : MonoBehaviour { public Text[] labels; void Start () { for(int i=0;i<labels.Length;i++) { labels[i].text = Const.a.InputCodes[i]; } } } <file_sep>/Assets/Scripts/PauseRigidbody.cs using UnityEngine; using System.Collections; public class PauseRigidbody : MonoBehaviour { private Rigidbody rbody; private Vector3 previousVelocity; private CollisionDetectionMode previouscolDetMode; //public bool justUnPaused = false; //public bool justPaused = false; void Awake () { rbody = GetComponent<Rigidbody>(); //justPaused = true; } public void Pause () { if (rbody != null) { previousVelocity = rbody.velocity; previouscolDetMode = rbody.collisionDetectionMode; rbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; rbody.isKinematic = true; } } public void UnPause () { if (rbody != null) { rbody.isKinematic = false; rbody.collisionDetectionMode = previouscolDetMode; rbody.velocity = previousVelocity; } } } <file_sep>/Assets/Scripts/CenterMFDTabs.cs using UnityEngine; using System.Collections; public class CenterMFDTabs : MonoBehaviour { [SerializeField] public GameObject MainTab = null; // assign in the editor [SerializeField] public GameObject HardwareTab = null; // assign in the editor [SerializeField] public GameObject GeneralTab = null; // assign in the editor [SerializeField] public GameObject SoftwareTab = null; // assign in the editor [SerializeField] public GameObject DataReaderContentTab = null; // assign in the editor public void DisableAllTabs () { MainTab.SetActive(false); HardwareTab.SetActive(false); GeneralTab.SetActive(false); SoftwareTab.SetActive(false); DataReaderContentTab.SetActive(false); } } <file_sep>/Assets/Scripts/LogMoreButton.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; using System.Collections.Generic; public class LogMoreButton : MonoBehaviour { public GameObject logTextOutput; public GameObject multiMediaTab; public MFDManager mfdManager; private string remainder = System.String.Empty; void LogMoreButtonClick() { remainder = logTextOutput.GetComponent<Text>().text; if (remainder.Length>568) { // MORE BUTTON remainder = remainder.Remove(0,568); logTextOutput.GetComponent<Text>().text = remainder; } else { // CLOSE BUTTON multiMediaTab.GetComponent<MultiMediaTabManager>().ResetTabs(); if (mfdManager.leftTC != null) mfdManager.leftTC.ReturnToLastTab(); if (mfdManager.rightTC != null) mfdManager.rightTC.ReturnToLastTab(); mfdManager.ClearDataTab(); } } void Start() { GetComponent<Button>().onClick.AddListener(() => { LogMoreButtonClick(); }); } } <file_sep>/Assets/Scripts/EnergyHeatTickManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnergyHeatTickManager : MonoBehaviour { public Image[] ticks; private float tempFloat; void Awake () { // Note that we only ever affect the last 9 ticks. Tick 1 of 10 stays on so we ignore it. for (int i=0;i<9;i++) { ticks[i].enabled = false; } } // Note that WeaponFire calls this every tick seconds public void HeatBleed (float currentHeat) { tempFloat = 10f; for (int i=0;i<9;i++) { if (currentHeat >= tempFloat) ticks[i].enabled = true; else ticks[i].enabled = false; tempFloat += 10f; } } } <file_sep>/Assets/Scripts/AIController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class AIController : MonoBehaviour { public int index = 0; // NPC reference index for looking up constants in tables in Const.cs public Const.aiState currentState; public Const.aiMoveType moveType; public GameObject enemy; public GameObject searchColliderGO; public float yawspeed = 180f; public float fieldOfViewAngle = 180f; public float fieldOfViewAttack = 80f; public float fieldOfViewStartMovement = 45f; public float distToSeeWhenBehind = 2.5f; public float sightRange = 50f; public float walkSpeed = 0.8f; public float runSpeed = 0.8f; public float meleeSpeed = 0.5f; public float proj1Speed = 0f; public float proj2Speed = 0f; public float meleeRange = 2f; public float proj1Range = 10f; public float proj2Range = 20f; public float attack3Force = 15f; public float attack3Radius = 10f; public float timeToPain = 2f; // time between going into pain animation public float timeBetweenPain = 5f; public float timeTillDead = 1.5f; public float timeTillMeleeDamage = 0.5f; public float timeTillActualAttack2 = 0.5f; public float gracePeriodFinished; [HideInInspector] public float meleeDamageFinished; public float timeBetweenMelee = 1.2f; public float timeBetweenProj1 = 1.5f; public float timeBetweenProj2 = 3f; public float changeEnemyTime = 3f; // Time before enemy will switch to different attacker public float idleSFXTimeMin = 5f; public float idleSFXTimeMax = 12f; public float attack2MinRandomWait = 1f; public float attack2MaxRandomWait = 3f; public float attack2RandomWaitChance = 0.5f; //50% chance of waiting a random amount of time before attacking to allow for movement public float impactMelee = 10f; public float impactMelee2 = 10f; public float verticalViewOffset = 0f; public Const.AttackType attack1Type = Const.AttackType.Melee; public Const.AttackType attack2Type = Const.AttackType.Projectile; public Const.AttackType attack3Type = Const.AttackType.Projectile; public Vector3 explosionOffset; public AudioClip SFXIdle; public AudioClip SFXFootstep; public AudioClip SFXSightSound; public AudioClip SFXAttack1; public AudioClip SFXAttack2; public AudioClip SFXAttack3; public AudioClip SFXPainClip; public AudioClip SFXDeathClip; public AudioClip SFXInspect; public AudioClip SFXInteracting; public bool rememberEnemyIfOutOfSight = false; public bool walkPathOnStart = false; public bool dontLoopWaypoints = false; public bool visitWaypointsRandomly = false; public bool hasMelee = true; public bool hasProj1 = false; public bool hasProj2 = false; public Transform[] walkWaypoints; // point(s) for NPC to walk to when roaming or patrolling public bool inSight = false; public bool infront; public bool inProjFOV; public bool LOSpossible; public bool goIntoPain = false; public bool explodeOnAttack3 = false; public bool ignoreEnemy = false; public float rangeToEnemy = 0f; public GameObject[] meleeDamageColliders; public GameObject muzzleBurst; public GameObject rrCheckPoint; [HideInInspector] public GameObject attacker; private bool hasSFX; public bool firstSighting; private bool dyingSetup; private bool ai_dying; private bool ai_dead; private int currentWaypoint; private float idleTime; private float attack1SoundTime; private float attack2SoundTime; private float attack3SoundTime; private float timeBetweenMeleeFinished; private float timeTillEnemyChangeFinished; private float timeTillDeadFinished; private float timeTillPainFinished; private AudioSource SFX; private NavMeshAgent nav; private Rigidbody rbody; private HealthManager healthManager; private BoxCollider boxCollider; private CapsuleCollider capsuleCollider; private SphereCollider sphereCollider; private MeshCollider meshCollider; private float tick; private float tickFinished; public float huntTime = 5f; public float huntFinished; private float breadFinished; private float breadCrumbTick = 2f; // "drop" a breadcrumb and store it in the list every 2 seconds private bool hadEnemy; private Vector3 lastKnownEnemyPos; private List<Vector3> enemyBreadcrumbs; private Vector3 tempVec; private bool randSpin = false; private bool shotFired = false; private DamageData damageData; private RaycastHit tempHit; private bool useBlood; private HealthManager tempHM; private float randomWaitForNextAttack2Finished; public GameObject visibleMeshEntity; public GameObject gunPoint; public Vector3 idealTransformForward; public Vector3 idealPos; public float attackFinished; public float attack2Finished; public float attack3Finished; public Vector3 targettingPosition; // Initialization and find components void Awake () { //resetPosition = new Vector3(0f,-100000f,0f); // Null position below playable area nav = GetComponent<UnityEngine.AI.NavMeshAgent>(); nav.updatePosition = true; nav.angularSpeed = yawspeed; nav.speed = 0; nav.SetDestination(transform.position); nav.updateRotation = false; //anim = GetComponent<Animator>(); rbody = GetComponent<Rigidbody>(); rbody.isKinematic = true; healthManager = GetComponent<HealthManager>(); boxCollider = GetComponent<BoxCollider>(); sphereCollider = GetComponent<SphereCollider>(); meshCollider = GetComponent<MeshCollider>(); capsuleCollider = GetComponent<CapsuleCollider>(); if (searchColliderGO != null) searchColliderGO.SetActive(false); for (int i = 0; i < meleeDamageColliders.Length; i++) { meleeDamageColliders[i].SetActive(false); // turn off melee colliders } currentState = Const.aiState.Idle; currentWaypoint = 0; enemy = null; firstSighting = true; inSight = false; hasSFX = false; goIntoPain = false; dyingSetup = false; ai_dead = false; ai_dying = false; attacker = null; shotFired = false; idleTime = Time.time + Random.Range(idleSFXTimeMin,idleSFXTimeMax); attack1SoundTime = Time.time; attack2SoundTime = Time.time; attack3SoundTime = Time.time; timeBetweenMeleeFinished = Time.time; timeTillEnemyChangeFinished = Time.time; huntFinished = Time.time; attackFinished = Time.time; attack2Finished = Time.time; attack3Finished = Time.time; timeTillPainFinished = Time.time; timeTillDeadFinished = Time.time; meleeDamageFinished = Time.time; gracePeriodFinished = Time.time; randomWaitForNextAttack2Finished = Time.time; breadFinished = Time.time; enemyBreadcrumbs = new List<Vector3>(); damageData = new DamageData(); tempHit = new RaycastHit(); tempVec = new Vector3(0f, 0f, 0f); SFX = GetComponent<AudioSource>(); if (SFX == null) Debug.Log("WARNING: No audio source for npc at: " + transform.position.x.ToString() + ", " + transform.position.y.ToString() + ", " + transform.position.z + "."); else hasSFX = true; if (walkWaypoints.Length > 0 && walkWaypoints[currentWaypoint] != null && walkPathOnStart) { nav.SetDestination(walkWaypoints[currentWaypoint].transform.position); currentState = Const.aiState.Walk; // If waypoints are set, start walking them from the get go } else { currentState = Const.aiState.Idle; // No waypoints, stay put } //RuntimeAnimatorController ac = anim.runtimeAnimatorController; //for (int i=0;i<ac.animationClips.Length;i++) { // if (ac.animationClips[i].name == "Death") { // timeTillDead = ac.animationClips[i].length; // break; // } //} tick = 0.05f; tickFinished = Time.time + tick; //QUAKE based AI attackFinished = Time.time + 1f; idealTransformForward = transform.forward; } void FixedUpdate () { if (PauseScript.a != null && PauseScript.a.paused) { //anim.speed = 0f; // don't animate, we're paused nav.isStopped = true; // don't move, we're paused return; // don't do any checks or anything else...we're paused! } else { //anim.speed = 1f; //nav.isStopped = false; } if(moveType == Const.aiMoveType.None) nav.isStopped = true; // Only think every tick seconds to save on CPU and prevent race conditions if (tickFinished < Time.time) { Think(); tickFinished = Time.time + tick; } // Rotation and Special movement that must be done every FixedUpdate if (currentState != Const.aiState.Dead) { if (currentState != Const.aiState.Idle) { idealTransformForward = nav.destination - transform.position; idealTransformForward.y = 0; Quaternion rot = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(idealTransformForward), yawspeed * Time.deltaTime); transform.rotation = rot; } if (moveType == Const.aiMoveType.Fly) { float distUp = 0; float distDn = 0; tempVec = transform.position; tempVec.y += verticalViewOffset; Vector3 floorPoint = new Vector3(); floorPoint = Vector3.zero; int layMask = 1 << 9; //layMask = -layMask; if (Physics.Raycast(tempVec, transform.up * -1, out tempHit, sightRange)) { //drawMyLine(tempVec, tempHit.point, Color.green, 2f); distDn = Vector3.Distance(tempVec, tempHit.point); floorPoint = tempHit.point; } if (Physics.Raycast(tempVec, transform.up, out tempHit, sightRange, layMask)) { //drawMyLine(tempVec, tempHit.point, Color.green, 2f); distUp = Vector3.Distance(tempVec, tempHit.point); } float distT = (distUp + distDn) * 0.75f; //Debug.Log("(" + distUp.ToString() + " + " + distDn.ToString() + ") * 0.25f = " + distT.ToString()); idealPos = floorPoint + new Vector3(0,distT, 0); visibleMeshEntity.transform.position = Vector3.MoveTowards(visibleMeshEntity.transform.position, idealPos, runSpeed * Time.deltaTime); } } } void Think () { if (healthManager.health <= 0) { // If we haven't gone into dying and we aren't dead, going into dying if (!ai_dying && !ai_dead) { ai_dying = true; //no going back currentState = Const.aiState.Dying; //start to collapse in a heap, melt, explode, etc. } } switch (currentState) { case Const.aiState.Idle: Idle(); break; case Const.aiState.Walk: Walk(); break; case Const.aiState.Run: Run(); break; case Const.aiState.Attack1: Attack1(); break; case Const.aiState.Attack2: Attack2(); break; case Const.aiState.Attack3: Attack3(); break; case Const.aiState.Pain: Pain(); break; case Const.aiState.Dying: Dying(); break; case Const.aiState.Dead: Dead(); break; case Const.aiState.Inspect: Inspect(); break; case Const.aiState.Interacting: Interacting(); break; default: Idle(); break; } if (currentState == Const.aiState.Dead || currentState == Const.aiState.Dying) return; // Don't do any checks, we're dead inSight = CheckIfPlayerInSight(); //if (inSight) backTurned = CheckIfBackIsTurned(); if (enemy != null) { infront = enemyInFront(enemy); inProjFOV = enemyInProjFOV(enemy); rangeToEnemy = Vector3.Distance(enemy.transform.position, transform.position); } else { infront = false; rangeToEnemy = sightRange; } } bool CheckPain() { if (goIntoPain) { currentState = Const.aiState.Pain; if (attacker != null) { if (timeTillEnemyChangeFinished < Time.time) { timeTillEnemyChangeFinished = Time.time + changeEnemyTime; enemy = attacker; // Switch to whoever just attacked us } } goIntoPain = false; timeTillPainFinished = Time.time + timeToPain; return true; } return false; } void Idle() { if (enemy != null) { currentState = Const.aiState.Run; return; } nav.isStopped = true; nav.speed = 0; if (idleTime < Time.time && SFXIdle) { SFX.PlayOneShot(SFXIdle); idleTime = Time.time + Random.Range(idleSFXTimeMin, idleSFXTimeMax); } if (CheckPain()) return; // Go into pain if we just got hurt, data is sent by the HealthManager CheckIfPlayerInSight(); } void Walk() { if (CheckPain()) return; // Go into pain if we just got hurt, data is sent by the HealthManager if (inSight || enemy != null) { currentState = Const.aiState.Run; return; } if (moveType == Const.aiMoveType.None) return; nav.speed = walkSpeed; if (WithinAngleToTarget()) { nav.isStopped = false; } else { nav.isStopped = true; } if (Vector3.Distance(transform.position, walkWaypoints[currentWaypoint].position) < nav.stoppingDistance) { if (visitWaypointsRandomly) { currentWaypoint = Random.Range(0, walkWaypoints.Length); } else { currentWaypoint++; if ((currentWaypoint >= walkWaypoints.Length) || (walkWaypoints[currentWaypoint] == null)) { if (dontLoopWaypoints) { currentState = Const.aiState.Idle; // Reached end of waypoints, just stop return; } else { currentWaypoint = 0; // Wrap around if (walkWaypoints[currentWaypoint] == null) { currentState = Const.aiState.Idle; return; } } } } nav.isStopped = true; nav.SetDestination(walkWaypoints[currentWaypoint].transform.position); } } void Run() { if (CheckPain()) return; // Go into pain if we just got hurt, data is sent by the HealthManager if (inSight) { huntFinished = Time.time + huntTime; if (rangeToEnemy < meleeRange) { if (hasMelee && infront) { nav.speed = meleeSpeed; timeBetweenMeleeFinished = Time.time + timeBetweenMelee; currentState = Const.aiState.Attack1; return; } } else { if (rangeToEnemy < proj1Range) { if (hasProj1 && infront && inProjFOV && (randomWaitForNextAttack2Finished < Time.time)) { nav.speed = proj1Speed; shotFired = false; attackFinished = Time.time + timeBetweenProj1 + timeTillActualAttack2; gracePeriodFinished = Time.time + timeTillActualAttack2; targettingPosition = enemy.transform.position; currentState = Const.aiState.Attack2; return; } } else { if (rangeToEnemy < proj2Range) { if (hasProj2 && infront) { nav.speed = proj2Speed; currentState = Const.aiState.Attack3; return; } } } } if (WithinAngleToTarget()) { nav.isStopped = false; } else { nav.isStopped = true; } nav.speed = runSpeed; nav.SetDestination(enemy.transform.position); if (moveType == Const.aiMoveType.None) nav.isStopped = true; lastKnownEnemyPos = enemy.transform.position; randSpin = false; if (breadFinished < Time.time) { breadFinished = Time.time + breadCrumbTick; enemyBreadcrumbs.Add(enemy.transform.position); } } else { if (huntFinished > Time.time) { Hunt(); } else { enemy = null; currentState = Const.aiState.Idle; return; } } } void Hunt() { if (WithinAngleToTarget()) { nav.isStopped = false; } else { nav.isStopped = true; } nav.speed = runSpeed; if (!randSpin && Vector3.Distance(transform.position, lastKnownEnemyPos) < nav.stoppingDistance) { randSpin = true; // only set destination point once so we aren't chasing our tail spinning in circles nav.SetDestination(rrCheckPoint.transform.position); } else { nav.SetDestination(lastKnownEnemyPos); } } void Attack1() { // Used for melee if (attack1SoundTime < Time.time && SFXAttack1) { SFX.PlayOneShot(SFXAttack1); attack1SoundTime = Time.time + timeBetweenMelee; for (int i = 0; i < meleeDamageColliders.Length; i++) { meleeDamageColliders[i].SetActive(true); meleeDamageColliders[i].GetComponent<AIMeleeDamageCollider>().MeleeColliderSetup(index, meleeDamageColliders.Length, impactMelee, gameObject); } } if (WithinAngleToTarget()) { nav.isStopped = false; } else { nav.isStopped = true; } nav.speed = meleeSpeed; nav.SetDestination(enemy.transform.position); if (timeBetweenMeleeFinished < Time.time) { for (int i = 0; i < meleeDamageColliders.Length; i++) { meleeDamageColliders[i].SetActive(false); // turn off melee colliders } goIntoPain = false; //prevent going into pain after attack currentState = Const.aiState.Run; return; // Done with attack } } bool WithinAngleToTarget () { if (Quaternion.Angle(transform.rotation, Quaternion.LookRotation(idealTransformForward)) < fieldOfViewStartMovement) { return true; } return false; } bool DidRayHit(Vector3 targPos, float dist) { tempVec = targPos; tempVec.y += verticalViewOffset; tempVec = tempVec - gunPoint.transform.position; int layMask = 10; layMask = -layMask; if (Physics.Raycast(gunPoint.transform.position, tempVec.normalized, out tempHit, sightRange, layMask)) { drawMyLine(gunPoint.transform.position,tempHit.point, Color.green, 2f); tempHM = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (tempHit.transform.gameObject.GetComponent<HealthManager>() != null) { useBlood = true; } return true; } return false; } GameObject GetImpactType(HealthManager hm) { if (hm == null) return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); switch (hm.bloodType) { case HealthManager.BloodType.None: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); case HealthManager.BloodType.Red: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmall); case HealthManager.BloodType.Yellow: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallYellow); case HealthManager.BloodType.Green: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallGreen); case HealthManager.BloodType.Robot: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmallBlue); } return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); } void CreateStandardImpactEffects(bool onlyBloodIfHitHasHM) { // Determine blood type of hit target and spawn corresponding blood particle effect from the Const.Pool if (useBlood) { GameObject impact = GetImpactType(tempHM); if (impact != null) { tempVec = tempHit.normal; impact.transform.position = tempHit.point + tempVec; impact.transform.rotation = Quaternion.FromToRotation(Vector3.up, tempHit.normal); impact.SetActive(true); } } else { // Allow for skipping adding sparks after special override impact effects per attack functions below if (!onlyBloodIfHitHasHM) { GameObject impact = Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); //Didn't hit an object with a HealthManager script, use sparks if (impact != null) { tempVec = tempHit.normal; impact.transform.position = tempHit.point + tempVec; impact.transform.rotation = Quaternion.FromToRotation(Vector3.up, tempHit.normal); impact.SetActive(true); } } } } void Attack2() { if (gracePeriodFinished < Time.time) { if (!shotFired) { shotFired = true; // Typically used for normal projectile attack if (attack2SoundTime < Time.time && SFXAttack2) { SFX.PlayOneShot(SFXAttack2); attack2SoundTime = Time.time + timeBetweenProj1; } if (attack2Type == Const.AttackType.Projectile) { muzzleBurst.SetActive(true); if (DidRayHit(targettingPosition, proj1Range)) { CreateStandardImpactEffects(false); damageData.other = tempHit.transform.gameObject; if (tempHit.transform.gameObject.tag == "NPC") { damageData.isOtherNPC = true; } else { damageData.isOtherNPC = false; } damageData.hit = tempHit; tempVec = transform.position; tempVec.y += verticalViewOffset; tempVec = (enemy.transform.position - tempVec); damageData.attacknormal = tempVec; damageData.damage = 15f; damageData.damage = Const.a.GetDamageTakeAmount(damageData); damageData.owner = gameObject; damageData.attackType = Const.AttackType.Projectile; HealthManager hm = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (hm == null) return; hm.TakeDamage(damageData); } } } } if (attackFinished < Time.time) { if (Random.Range(0f,1f) < attack2RandomWaitChance) { randomWaitForNextAttack2Finished = Time.time + Random.Range(attack2MinRandomWait, attack2MaxRandomWait); } else { randomWaitForNextAttack2Finished = Time.time; } muzzleBurst.SetActive(false); goIntoPain = false; //prevent going into pain after attack currentState = Const.aiState.Run; return; } } void Attack3() { // Typically used for secondary projectile or grenade attack if (attack3SoundTime < Time.time && SFXAttack3) { SFX.PlayOneShot(SFXAttack3); attack3SoundTime = Time.time + timeBetweenProj2; } if (explodeOnAttack3) { ExplosionForce ef = GetComponent<ExplosionForce>(); DamageData ddNPC = Const.SetNPCDamageData(index, Const.aiState.Attack3,gameObject); float take = Const.a.GetDamageTakeAmount(ddNPC); ddNPC.other = gameObject; ddNPC.damage = take; //enemy.GetComponent<HealthManager>().TakeDamage(ddNPC); Handled by ExplodeInner if (ef != null) ef.ExplodeInner(transform.position+explosionOffset, attack3Force, attack3Radius, ddNPC); healthManager.ObjectDeath(SFXDeathClip); return; } } void Pain() { if (timeTillPainFinished < Time.time) { currentState = Const.aiState.Run; // go into run after we get hurt goIntoPain = false; timeTillPainFinished = Time.time + timeBetweenPain; } } void Dying() { if (!dyingSetup) { dyingSetup = true; SFX.PlayOneShot(SFXDeathClip); // Turn off normal NPC collider and enable corpse collider for searching if (boxCollider != null) boxCollider.enabled = false; if (sphereCollider != null) sphereCollider.enabled = false; if (meshCollider != null) meshCollider.enabled = false; if (capsuleCollider != null) capsuleCollider.enabled = false; if (searchColliderGO != null) searchColliderGO.SetActive(true); gameObject.tag = "Searchable"; // Enable searching nav.speed = nav.speed * 0.5f; // half the speed while collapsing or whatever timeTillDeadFinished = Time.time + timeTillDead; // wait for death animation to finish before going into Dead() } if (timeTillDeadFinished < Time.time) { ai_dead = true; ai_dying = false; currentState = Const.aiState.Dead; } } void Dead() { nav.isStopped = true; // Stop moving //anim.speed = 0f; // Stop animation ai_dead = true; ai_dying = false; rbody.isKinematic = true; currentState = Const.aiState.Dead; firstSighting = false; if (healthManager.gibOnDeath) { ExplosionForce ef = GetComponent<ExplosionForce>(); DamageData ddNPC = Const.SetNPCDamageData(index, Const.aiState.Attack3,gameObject); float take = Const.a.GetDamageTakeAmount(ddNPC); ddNPC.other = gameObject; ddNPC.damage = take; if (ef != null) ef.ExplodeInner(transform.position+explosionOffset, attack3Force, attack3Radius, ddNPC); healthManager.ObjectDeath(SFXDeathClip); } } void Inspect() { if (CheckPain()) return; // Go into pain if we just got hurt, data is sent by the HealthManager } void Interacting() { if (CheckPain()) return; // Go into pain if we just got hurt, data is sent by the HealthManager } bool CheckIfEnemyInSight() { Vector3 checkline = enemy.transform.position - transform.position; // Get vector line made from enemy to found player int layMask = 10; layMask = -layMask; RaycastHit hit; if (Physics.Raycast(transform.position + transform.up, checkline.normalized, out hit, sightRange, layMask)) { LOSpossible = true; if (hit.collider.gameObject == enemy) return true; } LOSpossible = false; return false; } bool CheckIfPlayerInSight () { if (ignoreEnemy) return false; if (enemy != null) return CheckIfEnemyInSight(); GameObject playr1 = Const.a.player1; GameObject playr2 = Const.a.player2; GameObject playr3 = Const.a.player3; GameObject playr4 = Const.a.player4; if (playr1 == null) { Debug.Log("WARNING: NPC sight check - no host player 1."); return false; } // No host player if (playr1 != null) {playr1 = playr1.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr2 != null) {playr2 = playr2.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr3 != null) {playr3 = playr3.GetComponent<PlayerReferenceManager>().playerCapsule;} if (playr4 != null) {playr4 = playr4.GetComponent<PlayerReferenceManager>().playerCapsule;} GameObject tempent = null; LOSpossible = false; for (int i=0;i<4;i++) { tempent = null; // Cycle through all the players to see if we can see anybody. Defaults to earlier joined players. TODO: Add randomization if multiple players are visible. if (playr1 != null && i == 0) tempent = playr1; if (playr2 != null && i == 1) tempent = playr2; if (playr3 != null && i == 2) tempent = playr3; if (playr4 != null && i == 4) tempent = playr4; if (tempent == null) continue; tempVec = tempent.transform.position; tempVec.y += verticalViewOffset; Vector3 checkline = tempVec - transform.position; // Get vector line made from enemy to found player int layMask = 10; layMask = -layMask; // Check for line of sight RaycastHit hit; if (Physics.Raycast(transform.position, checkline.normalized, out hit, sightRange,layMask)) { //drawMyLine(transform.position,hit.point, Color.green, 2f); if (hit.collider.gameObject == tempent) LOSpossible = true; // Clear path from enemy to found player } float dist = Vector3.Distance(tempent.transform.position,transform.position); // Get distance between enemy and found player float angle = Vector3.Angle(checkline,transform.forward); // If clear path to found player, and either within view angle or right behind the enemy if (LOSpossible) { if (angle < (fieldOfViewAngle * 0.5f)) { enemy = tempent; if (firstSighting) { firstSighting = false; if (hasSFX) SFX.PlayOneShot(SFXSightSound); } return true; } else { if (dist < distToSeeWhenBehind) { enemy = tempent; if (firstSighting) { firstSighting = false; if (hasSFX) SFX.PlayOneShot(SFXSightSound); } return true; } } } } return false; } bool enemyInFront (GameObject target) { Vector3 vec = Vector3.Normalize(target.transform.position - transform.position); float dot = Vector3.Dot(vec,transform.forward); if (dot > 0.300) return true; // enemy is within 27 degrees of forward facing vector return false; } bool enemyInProjFOV(GameObject target) { Vector3 vec = Vector3.Normalize(target.transform.position - transform.position); float dot = Vector3.Dot(vec, transform.forward); if (dot > 0.800) return true; // enemy is within 27 degrees of forward facing vector return false; } void drawMyLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f) { StartCoroutine(drawLine(start, end, color, duration)); } IEnumerator drawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f) { GameObject myLine = new GameObject(); myLine.transform.position = start; myLine.AddComponent<LineRenderer>(); LineRenderer lr = myLine.GetComponent<LineRenderer>(); lr.material = new Material(Shader.Find("Particles/Additive")); lr.startColor = color; lr.endColor = color; lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.SetPosition(0, start); lr.SetPosition(1, end); yield return new WaitForSeconds(duration); GameObject.Destroy(myLine); } } <file_sep>/Assets/Scripts/KeycodeButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class KeycodeButton : MonoBehaviour { public GameObject playerCamera; public GameObject keycodeController; public int index; public void PtrEnter () { GUIState.a.PtrHandler(true,true,GUIState.ButtonType.Generic,gameObject); } public void PtrExit () { GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } void KeycodeButtonClick () { keycodeController.GetComponent<KeypadKeycodeButtons>().Keypress(index); } void Start() { GetComponent<Button>().onClick.AddListener(() => { KeycodeButtonClick(); }); } } <file_sep>/Assets/Scripts/ConfigKeybindButton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigKeybindButton : MonoBehaviour { private Button self; private bool enterMode; private bool firstFrame; private Text selfText; public int index; void Awake () { self = GetComponent<Button>(); selfText = GetComponentInChildren<Text>(); enterMode = false; firstFrame = true; } void Start () { selfText.text = Const.a.InputConfigNames[Const.a.InputCodeSettings[index]]; } public void KeybindButtonClick() { if (!enterMode) { self.GetComponentInChildren<Text>().text = "..."; enterMode = true; } } void Update () { if (enterMode) { if (firstFrame) { firstFrame = false; return; // prevent capturing the click in input check } for (int i=0;i<159;i++) { if (Input.GetKeyUp(Const.a.InputValues[i])) { selfText.text = Const.a.InputConfigNames[i]; Const.a.InputCodeSettings[index] = i; Const.a.WriteConfig(); enterMode = false; firstFrame = true; return; } } } } } <file_sep>/Assets/Scripts/ConfigSliderValueDisplay.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigSliderValueDisplay : MonoBehaviour { public Slider slideControl; private Text self; void Awake () { self = GetComponent<Text>(); if (self == null) { Debug.Log("ERROR: No slider for object with ConfigSliderValueDisplay script"); } } void Update () { self.text = slideControl.value.ToString(); } } <file_sep>/Assets/Scripts/GeneralInventory.cs using UnityEngine; using System.Collections; public class GeneralInventory : MonoBehaviour { public int[] generalInventoryIndexRef; public static GeneralInventory GeneralInventoryInstance; void Awake() { GeneralInventoryInstance = this; for (int i = 0; i < 14; i++) { GeneralInventoryInstance.generalInventoryIndexRef[i] = -1; } } } <file_sep>/Assets/Scripts/WeaponButtonsManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class WeaponButtonsManager : MonoBehaviour { [SerializeField] public GameObject[] wepButtons; [SerializeField] private GameObject[] wepCountsText; public GameObject ammoiconman; void Update() { if (WeaponInventory.WepInventoryInstance == null) { Const.sprint("ERROR->WeaponButtonsManager: WeaponInventory instance failed to initialize!",transform.parent.gameObject); return; } for (int i=0; i<7; i++) { if (WeaponInventory.WepInventoryInstance.weaponInventoryIndices[i] > 0) { if (!wepButtons[i].activeInHierarchy) wepButtons[i].SetActive(true); wepButtons[i].GetComponent<WeaponButton>().useableItemIndex = WeaponInventory.WepInventoryInstance.weaponInventoryIndices[i]; if (!wepCountsText[i].activeInHierarchy) wepCountsText[i].SetActive(true); } else { if (wepButtons[i].activeInHierarchy) wepButtons[i].SetActive(false); wepButtons[i].GetComponent<WeaponButton>().useableItemIndex = -1; if (wepCountsText[i].activeInHierarchy) wepCountsText[i].SetActive(false); } } if (GetInput.a.WeaponCycUp ()) { int i = WeaponCurrent.WepInstance.weaponCurrent; i++; int numberOfWeapons = 0; for (int j=0;j<7;j++) { if (WeaponInventory.WepInventoryInstance.weaponInventoryIndices [j] != -1) numberOfWeapons++; } if (numberOfWeapons == 0) return; if (i == numberOfWeapons) i = 0; // Check that the index we are going to is different than what we are on if (i != WeaponCurrent.WepInstance.weaponCurrent) { //WeaponCurrent.WepInstance.weaponCurrent = i; wepButtons [i].GetComponent<WeaponButton> ().WeaponInvClick (); } int invslot = WeaponInventory.WepInventoryInstance.weaponInventoryIndices[i]; if (invslot >= 0) ammoiconman.GetComponent<AmmoIconManager>().SetAmmoIcon(invslot, WeaponCurrent.WepInstance.weaponIsAlternateAmmo); } if (GetInput.a.WeaponCycDown ()) { int i = WeaponCurrent.WepInstance.weaponCurrent; i--; int numberOfWeapons = 0; for (int j=0;j<7;j++) { if (WeaponInventory.WepInventoryInstance.weaponInventoryIndices [j] != -1) numberOfWeapons++; } if (numberOfWeapons == 0) return; if (i < 0) i = (numberOfWeapons - 1); // Check that the index we are going to is different than what we are on if (i != WeaponCurrent.WepInstance.weaponCurrent) { //WeaponCurrent.WepInstance.weaponCurrent = i; wepButtons [i].GetComponent<WeaponButton> ().WeaponInvClick (); } } } } <file_sep>/Assets/Scripts/EnergySlider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnergySlider : MonoBehaviour { public WeaponCurrent currentWeapon; Slider slideS; private int index; private float ener_min; private float ener_max; private float val; void Awake () { slideS = GetComponent<Slider>(); index = -1; ener_min = 2f; ener_max = 130f; val = 0; } public void SetValue() { index = WeaponFire.Get16WeaponIndexFromConstIndex(currentWeapon.weaponIndex); ener_min = Const.a.energyDrainLowForWeapon[index]; ener_max = Const.a.energyDrainHiForWeapon[index]; val = slideS.value / 100f; val = (val*(ener_max - ener_min)) + ener_min; currentWeapon.weaponEnergySetting[index] = val; } } <file_sep>/Assets/Scripts/PuzzleWire.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PuzzleWire : MonoBehaviour { public bool[] wireIsActive; public bool[] nodeRowIsActive; public GameObject[] leftNodes; public GameObject[] rightNodes; //public int[] targetPositionsLeft; //public int[] targetPositionsRight; public Image[] leftNodeSelectedIndicators; public Image[] rightNodeSelectedIndicators; public Slider slider; public int wire1LHPosition; public int wire1RHPosition; public int wire2LHPosition; public int wire2RHPosition; public int wire3LHPosition; public int wire3RHPosition; public int wire4LHPosition; public int wire4RHPosition; public int wire5LHPosition; public int wire5RHPosition; public int wire6LHPosition; public int wire6RHPosition; public int wire7LHPosition; public int wire7RHPosition; public int wire1LHTarget; public int wire1RHTarget; public int wire2LHTarget; public int wire2RHTarget; public int wire3LHTarget; public int wire3RHTarget; public int wire4LHTarget; public int wire4RHTarget; public int wire5LHTarget; public int wire5RHTarget; public int wire6LHTarget; public int wire6RHTarget; public int wire7LHTarget; public int wire7RHTarget; public LineRenderer[] wires; public float nodeYOffset = 26f; public float nodeXOffset = 106f; public float blinkTime = 0.5f; public bool Solved = false; public float shakeMultiplier = 0.05f; private bool wireWasDisplaced; private int tempInt; // don't make garbage to collect private float tempF; private int selectedWire; private bool selectedWireLH; private Vector3 tempVec; private bool blinkState; private float blinkTimeFinished; public float actualValue; private int numberOfWires; private AudioSource SFXSource; public AudioClip SFX; public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; private UseData udSender; public bool geniusActive; public Image[] geniusHintsLH; public Image[] geniusHintsRH; void Awake () { selectedWire = -1; blinkState = false; CheckEnabledNodes(); ChangeAppearance(); DisableAllSelectedIndicators(); DisableGeniusHints(); SFXSource = GetComponent<AudioSource>(); EvaluatePuzzle(); } void DisableGeniusHints () { for (tempInt = 0; tempInt < 7; tempInt++) { geniusHintsLH[tempInt].enabled = false; geniusHintsRH[tempInt].enabled = false; } } void DisableAllSelectedIndicators () { for (tempInt = 0; tempInt < 7; tempInt++) { leftNodeSelectedIndicators[tempInt].enabled = false; rightNodeSelectedIndicators[tempInt].enabled = false; } } void Update () { if (Solved) return; if (selectedWire != -1) { if (blinkTimeFinished < Time.time) { BlinkSelectedIndicator(); blinkState = !blinkState; blinkTimeFinished = Time.time + blinkTime; } } else { DisableAllSelectedIndicators(); } if (geniusActive) { numberOfWires = 0; for (int tempInt = 0; tempInt < 7; tempInt++) { if (wireIsActive[tempInt]) numberOfWires++; } for (tempInt = 0; tempInt < 7; tempInt++) { if (wireIsActive[tempInt]) { switch (tempInt) { case 0: geniusHintsLH[wire1LHTarget].enabled = true; geniusHintsRH[wire1RHTarget].enabled = true; break; case 1: geniusHintsLH[wire2LHTarget].enabled = true; geniusHintsRH[wire2RHTarget].enabled = true; break; case 2: geniusHintsLH[wire3LHTarget].enabled = true; geniusHintsRH[wire3RHTarget].enabled = true; break; case 3: geniusHintsLH[wire4LHTarget].enabled = true; geniusHintsRH[wire4RHTarget].enabled = true; break; case 4: geniusHintsLH[wire5LHTarget].enabled = true; geniusHintsRH[wire5RHTarget].enabled = true; break; case 5: geniusHintsLH[wire6LHTarget].enabled = true; geniusHintsRH[wire6RHTarget].enabled = true; break; case 6: geniusHintsLH[wire7LHTarget].enabled = true; geniusHintsRH[wire7RHTarget].enabled = true; break; } } } } else { DisableGeniusHints(); } if (!Solved) { slider.value = actualValue + Random.Range(0f,shakeMultiplier); if (slider.value > 100f) { slider.value = 100f; } if (slider.value < 0) { slider.value = 0; } } } private void BlinkSelectedIndicator() { if (selectedWireLH) { switch (selectedWire) { case 0: leftNodeSelectedIndicators[wire1LHPosition].enabled = blinkState; break; case 1: leftNodeSelectedIndicators[wire2LHPosition].enabled = blinkState; break; case 2: leftNodeSelectedIndicators[wire3LHPosition].enabled = blinkState; break; case 3: leftNodeSelectedIndicators[wire4LHPosition].enabled = blinkState; break; case 4: leftNodeSelectedIndicators[wire5LHPosition].enabled = blinkState; break; case 5: leftNodeSelectedIndicators[wire6LHPosition].enabled = blinkState; break; case 6: leftNodeSelectedIndicators[wire7LHPosition].enabled = blinkState; break; } } else { switch (selectedWire) { case 0: rightNodeSelectedIndicators[wire1RHPosition].enabled = blinkState; break; case 1: rightNodeSelectedIndicators[wire2RHPosition].enabled = blinkState; break; case 2: rightNodeSelectedIndicators[wire3RHPosition].enabled = blinkState; break; case 3: rightNodeSelectedIndicators[wire4RHPosition].enabled = blinkState; break; case 4: rightNodeSelectedIndicators[wire5RHPosition].enabled = blinkState; break; case 5: rightNodeSelectedIndicators[wire6RHPosition].enabled = blinkState; break; case 6: rightNodeSelectedIndicators[wire7RHPosition].enabled = blinkState; break; } } } public void SendPuzzleData(bool[] sentWiresOn, bool[] sentNodeRowsActive, int[] sentCurrentPositionsLeft, int[] sentCurrentPositionsRight, int[] sentTargetsLeft, int[] sentTargetsRight, UseData udSent) { wireIsActive = sentWiresOn; nodeRowIsActive = sentNodeRowsActive; wire1LHPosition = sentCurrentPositionsLeft[0]; wire2LHPosition = sentCurrentPositionsLeft[1]; wire3LHPosition = sentCurrentPositionsLeft[2]; wire4LHPosition = sentCurrentPositionsLeft[3]; wire5LHPosition = sentCurrentPositionsLeft[4]; wire6LHPosition = sentCurrentPositionsLeft[5]; wire7LHPosition = sentCurrentPositionsLeft[6]; wire1RHPosition = sentCurrentPositionsRight[0]; wire2RHPosition = sentCurrentPositionsRight[1]; wire3RHPosition = sentCurrentPositionsRight[2]; wire4RHPosition = sentCurrentPositionsRight[3]; wire5RHPosition = sentCurrentPositionsRight[4]; wire6RHPosition = sentCurrentPositionsRight[5]; wire7RHPosition = sentCurrentPositionsRight[6]; wire1LHTarget = sentTargetsLeft[0]; wire2LHTarget = sentTargetsLeft[1]; wire3LHTarget = sentTargetsLeft[2]; wire4LHTarget = sentTargetsLeft[3]; wire5LHTarget = sentTargetsLeft[4]; wire6LHTarget = sentTargetsLeft[5]; wire7LHTarget = sentTargetsLeft[6]; wire1RHTarget = sentTargetsRight[0]; wire2RHTarget = sentTargetsRight[1]; wire3RHTarget = sentTargetsRight[2]; wire4RHTarget = sentTargetsRight[3]; wire5RHTarget = sentTargetsRight[4]; wire6RHTarget = sentTargetsRight[5]; wire7RHTarget = sentTargetsRight[6]; udSender = udSent; CheckEnabledNodes(); ChangeAppearance(); } private Vector3 GetPositionOfLHNode(int index) { tempVec = Vector3.zero; tempVec.x = 0; tempVec.y = nodeYOffset * -1 * index; return tempVec; } private Vector3 GetPositionOfRHNode(int index) { tempVec = Vector3.zero; tempVec.x = nodeXOffset; tempVec.y = nodeYOffset * -1 * index; return tempVec; } public void ChangeAppearance() { CheckEnabledNodes(); wires[0].SetPosition(0,GetPositionOfLHNode(wire1LHPosition)); wires[0].SetPosition(1,GetPositionOfRHNode(wire1RHPosition)); wires[1].SetPosition(0,GetPositionOfLHNode(wire2LHPosition)); wires[1].SetPosition(1,GetPositionOfRHNode(wire2RHPosition)); wires[2].SetPosition(0,GetPositionOfLHNode(wire3LHPosition)); wires[2].SetPosition(1,GetPositionOfRHNode(wire3RHPosition)); wires[3].SetPosition(0,GetPositionOfLHNode(wire4LHPosition)); wires[3].SetPosition(1,GetPositionOfRHNode(wire4RHPosition)); wires[4].SetPosition(0,GetPositionOfLHNode(wire5LHPosition)); wires[4].SetPosition(1,GetPositionOfRHNode(wire5RHPosition)); wires[5].SetPosition(0,GetPositionOfLHNode(wire6LHPosition)); wires[5].SetPosition(1,GetPositionOfRHNode(wire6RHPosition)); wires[6].SetPosition(0,GetPositionOfLHNode(wire7LHPosition)); wires[6].SetPosition(1,GetPositionOfRHNode(wire7RHPosition)); } public void CheckEnabledNodes() { for (tempInt = 0; tempInt < 7; tempInt++) { if (wireIsActive[tempInt]) { wires[tempInt].enabled = true; } else { wires[tempInt].enabled = false; } if (nodeRowIsActive[tempInt]) { leftNodes[tempInt].SetActive(true); rightNodes[tempInt].SetActive(true); } else { leftNodes[tempInt].SetActive(false); rightNodes[tempInt].SetActive(false); } } } public void ClickLHNode(int spot) { if (Solved) return; if (selectedWireLH) { if (selectedWire < 0) { SelectWireLH(spot); } else { MoveEndpointLeft(spot); } } else { SelectWireLH(spot); } } public void ClickRHNode(int spot) { if (Solved) return; if (!selectedWireLH) { if (selectedWire < 0) { SelectWireRH(spot); } else { MoveEndpointRight(spot); } } else { SelectWireRH(spot); } } public void SelectWireLH(int spot) { selectedWire = -1; // Check LH spots and see which wire we have if (wire1LHPosition == spot && wireIsActive[0]) selectedWire = 0; if (wire2LHPosition == spot && wireIsActive[1]) selectedWire = 1; if (wire3LHPosition == spot && wireIsActive[2]) selectedWire = 2; if (wire4LHPosition == spot && wireIsActive[3]) selectedWire = 3; if (wire5LHPosition == spot && wireIsActive[4]) selectedWire = 4; if (wire6LHPosition == spot && wireIsActive[5]) selectedWire = 5; if (wire7LHPosition == spot && wireIsActive[6]) selectedWire = 6; if (selectedWire == -1) return; DisableAllSelectedIndicators(); selectedWireLH = true; blinkState = true; blinkTimeFinished = Time.time + blinkTime; BlinkSelectedIndicator(); ChangeAppearance(); EvaluatePuzzle(); } public void SelectWireRH(int spot) { selectedWire = -1; // Check RH spots and see which wire we have if (wire1RHPosition == spot && wireIsActive[0]) selectedWire = 0; if (wire2RHPosition == spot && wireIsActive[1]) selectedWire = 1; if (wire3RHPosition == spot && wireIsActive[2]) selectedWire = 2; if (wire4RHPosition == spot && wireIsActive[3]) selectedWire = 3; if (wire5RHPosition == spot && wireIsActive[4]) selectedWire = 4; if (wire6RHPosition == spot && wireIsActive[5]) selectedWire = 5; if (wire7RHPosition == spot && wireIsActive[6]) selectedWire = 6; if (selectedWire == -1) return; DisableAllSelectedIndicators(); selectedWireLH = false; blinkState = true; blinkTimeFinished = Time.time + blinkTime; BlinkSelectedIndicator(); ChangeAppearance(); EvaluatePuzzle(); } public void MoveEndpointLeft(int newSpot) { if (selectedWire == -1) return; switch (selectedWire) { case 0: if (wire2LHPosition == newSpot) wire2LHPosition = wire1LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire1LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire1LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire1LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire1LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire1LHPosition; wire1LHPosition = newSpot; break; case 1: if (wire1LHPosition == newSpot) wire1LHPosition = wire2LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire2LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire2LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire2LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire2LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire2LHPosition; wire2LHPosition = newSpot; break; case 2: if (wire1LHPosition == newSpot) wire1LHPosition = wire3LHPosition; if (wire2LHPosition == newSpot) wire2LHPosition = wire3LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire3LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire3LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire3LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire3LHPosition; wire3LHPosition = newSpot; break; case 3: if (wire1LHPosition == newSpot) wire1LHPosition = wire4LHPosition; if (wire2LHPosition == newSpot) wire2LHPosition = wire4LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire4LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire4LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire4LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire4LHPosition; wire4LHPosition = newSpot; break; case 4: if (wire1LHPosition == newSpot) wire1LHPosition = wire5LHPosition; if (wire2LHPosition == newSpot) wire2LHPosition = wire5LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire5LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire5LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire5LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire5LHPosition; wire5LHPosition = newSpot; break; case 5: if (wire1LHPosition == newSpot) wire1LHPosition = wire6LHPosition; if (wire2LHPosition == newSpot) wire2LHPosition = wire6LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire6LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire6LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire6LHPosition; if (wire7LHPosition == newSpot) wire7LHPosition = wire6LHPosition; wire6LHPosition = newSpot; break; case 6: if (wire1LHPosition == newSpot) wire1LHPosition = wire7LHPosition; if (wire2LHPosition == newSpot) wire2LHPosition = wire7LHPosition; if (wire3LHPosition == newSpot) wire3LHPosition = wire7LHPosition; if (wire4LHPosition == newSpot) wire4LHPosition = wire7LHPosition; if (wire5LHPosition == newSpot) wire5LHPosition = wire7LHPosition; if (wire6LHPosition == newSpot) wire6LHPosition = wire7LHPosition; wire7LHPosition = newSpot; break; } selectedWire = -1; selectedWireLH = false; for (tempInt = 0; tempInt < 7; tempInt++) { leftNodeSelectedIndicators[tempInt].enabled = false; rightNodeSelectedIndicators[tempInt].enabled = false; } ChangeAppearance(); EvaluatePuzzle(); } public void MoveEndpointRight(int newSpot) { if (selectedWire == -1) return; switch (selectedWire) { case 0: if (wire2RHPosition == newSpot) wire2RHPosition = wire1RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire1RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire1RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire1RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire1RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire1RHPosition; wire1RHPosition = newSpot; break; case 1: if (wire1RHPosition == newSpot) wire1RHPosition = wire2RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire2RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire2RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire2RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire2RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire2RHPosition; wire2RHPosition = newSpot; break; case 2: if (wire1RHPosition == newSpot) wire1RHPosition = wire3RHPosition; if (wire2RHPosition == newSpot) wire2RHPosition = wire3RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire3RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire3RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire3RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire3RHPosition; wire3RHPosition = newSpot; break; case 3: if (wire1RHPosition == newSpot) wire1RHPosition = wire4RHPosition; if (wire2RHPosition == newSpot) wire2RHPosition = wire4RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire4RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire4RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire4RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire4RHPosition; wire4RHPosition = newSpot; break; case 4: if (wire1RHPosition == newSpot) wire1RHPosition = wire5RHPosition; if (wire2RHPosition == newSpot) wire2RHPosition = wire5RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire5RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire5RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire5RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire5RHPosition; wire5RHPosition = newSpot; break; case 5: if (wire1RHPosition == newSpot) wire1RHPosition = wire6RHPosition; if (wire2RHPosition == newSpot) wire2RHPosition = wire6RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire6RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire6RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire6RHPosition; if (wire7RHPosition == newSpot) wire7RHPosition = wire6RHPosition; wire6RHPosition = newSpot; break; case 6: if (wire1RHPosition == newSpot) wire1RHPosition = wire7RHPosition; if (wire2RHPosition == newSpot) wire2RHPosition = wire7RHPosition; if (wire3RHPosition == newSpot) wire3RHPosition = wire7RHPosition; if (wire4RHPosition == newSpot) wire4RHPosition = wire7RHPosition; if (wire5RHPosition == newSpot) wire5RHPosition = wire7RHPosition; if (wire6RHPosition == newSpot) wire6RHPosition = wire7RHPosition; wire7RHPosition = newSpot; break; } selectedWire = -1; for (tempInt = 0; tempInt < 7; tempInt++) { leftNodeSelectedIndicators[tempInt].enabled = false; rightNodeSelectedIndicators[tempInt].enabled = false; } ChangeAppearance(); EvaluatePuzzle(); } void EvaluatePuzzle() { tempF = 0; //numberOfWires = 0; //for (int tempInt = 0; tempInt < 7; tempInt++) { // if (wireIsActive[tempInt]) numberOfWires++; //} /* if (wire1LHPosition == wire1LHTarget) tempF += (1 / numberOfWires)/2; if (wire2LHPosition == wire2LHTarget) tempF += (1 / numberOfWires)/2; if (wire3LHPosition == wire3LHTarget) tempF += (1 / numberOfWires)/2; if (wire4LHPosition == wire4LHTarget) tempF += (1 / numberOfWires)/2; if (wire5LHPosition == wire5LHTarget) tempF += (1 / numberOfWires)/2; if (wire6LHPosition == wire6LHTarget) tempF += (1 / numberOfWires)/2; if (wire7LHPosition == wire7LHTarget) tempF += (1 / numberOfWires)/2; if (wire1RHPosition == wire1RHTarget) tempF += (1 / numberOfWires)/2; if (wire2RHPosition == wire2RHTarget) tempF += (1 / numberOfWires)/2; if (wire3RHPosition == wire3RHTarget) tempF += (1 / numberOfWires)/2; if (wire4RHPosition == wire4RHTarget) tempF += (1 / numberOfWires)/2; if (wire5RHPosition == wire5RHTarget) tempF += (1 / numberOfWires)/2; if (wire6RHPosition == wire6RHTarget) tempF += (1 / numberOfWires)/2; if (wire7RHPosition == wire7RHTarget) tempF += (1 / numberOfWires)/2; */ if (wire1LHPosition == wire1LHTarget) tempF += 0.19f; if (wire2LHPosition == wire2LHTarget) tempF += 0.19f; if (wire3LHPosition == wire3LHTarget) tempF += 0.19f; if (wire4LHPosition == wire4LHTarget) tempF += 0.19f; if (wire5LHPosition == wire5LHTarget) tempF += 0.19f; if (wire6LHPosition == wire6LHTarget) tempF += 0.19f; if (wire7LHPosition == wire7LHTarget) tempF += 0.19f; if (wire1RHPosition == wire1RHTarget) tempF += 0.19f; if (wire2RHPosition == wire2RHTarget) tempF += 0.19f; if (wire3RHPosition == wire3RHTarget) tempF += 0.19f; if (wire4RHPosition == wire4RHTarget) tempF += 0.19f; if (wire5RHPosition == wire5RHTarget) tempF += 0.19f; if (wire6RHPosition == wire6RHTarget) tempF += 0.19f; if (wire7RHPosition == wire7RHTarget) tempF += 0.19f; //Const.sprint("Puzzle value: " + tempF.ToString(),Const.a.allPlayers); if (tempF > 0.95f) { tempF = 1f; } actualValue = tempF; if (actualValue > 0.92f) { PuzzleSolved(); } } void PuzzleSolved() { actualValue = 1f; slider.value = actualValue; Solved = true; SFXSource.PlayOneShot(SFX,1.0f); UseTargets (udSender); } public void UseTargets (UseData ud) { if (target != null) { target.SendMessageUpwards("Targetted", ud); } if (target1 != null) { target1.SendMessageUpwards("Targetted", ud); } if (target2 != null) { target2.SendMessageUpwards("Targetted", ud); } if (target3 != null) { target3.SendMessageUpwards("Targetted", ud); } } } <file_sep>/Assets/Scripts/CameraLayers.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraLayers : MonoBehaviour { void Awake () { Camera cam = GetComponent<Camera>(); cam.layerCullSpherical = true; float[] distPerLayer = new float[32]; for (int i = 0; i < distPerLayer.Length; i++) { distPerLayer [i] = 0; // default to far plane distance } // Tweaked layer settings distPerLayer[15] = 1350f; cam.layerCullDistances = distPerLayer; } } <file_sep>/Assets/StreamingAssets/Config.ini // Citadel Configuration File [Graphics] ResolutionWidth = 1680 ResolutionHeight = 1050 Fullscreen = 1 SSAO = 1 Bloom = 1 FOV = 65 Brightness = 50 Gamma = 54 [Audio] Gamma = 50 SpeakerMode = 1 Reverb = 1 VolumeMaster = 100 VolumeMusic = 91 VolumeMessage = 100 VolumeEffects = 100 Language = 0 Subtitles = 1 [Input] Subtitles = 0 Forward = w Strafe Left = a Backpedal = s Strafe Right = d Jump = space Crouch = c Prone = x Lean Left = q Lean Right = e Sprint = left shift Toggle Sprint = z Turn Left = left Turn Right = right Look Up = up Look Down = down Recent Log = u Biomonitor = 1 Sensaround = 2 Lantern = 3 Shield = 4 Infrared = 5 Email = 6 Booster = 7 Jumpjets = 8 Attack = mouse 0 Use = mouse 1 Menu/Back = escape Toggle Mode = tab Reload = r Weapon + = t Weapon - = b Grenade = g Grenade + = y Grenade - = n HW Version - = - Patch Use = f Patch + = h Patch - = v Full Map = m InvertLook = 0 InvertCyberspaceLook = 0 InvertInventoryCycling = 0 QuickItemPickup = 0 QuickReloadWeapons = 1 E-reader = ` HW Version + = a <file_sep>/Assets/Scripts/AnimDisplayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimDisplayer : MonoBehaviour { public string[] animName; private Animation anim; public int currentIndex = 0; public float timeStamp; void Start () { anim = GetComponent<Animation>(); Debug.Log(anim.name); currentIndex = 0; timeStamp = 0f; } // Update is called once per frame void Update () { anim[animName[currentIndex]].wrapMode = WrapMode.Loop; anim.Play(animName[currentIndex]); timeStamp = anim[animName[currentIndex]].normalizedTime; if (timeStamp > 0.9f) { currentIndex++; if (currentIndex >= animName.Length) { currentIndex = 0; } } } } <file_sep>/Assets/Scripts/ImageSequenceTextureArrayUI.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ImageSequenceTextureArrayUI : MonoBehaviour { //An array of Objects that stores the results of the Resources.LoadAll() method private Object[] objects; //Each returned object is converted to a Texture and stored in this array private Sprite[] sprites; //With this Material object, a reference to the game object Material can be stored private Image goImage; //An integer to advance frames private int frameCounter = 0; public string resourceFolder; public float frameDelay = 0.35f; void Awake() { //Get a reference to the Material of the game object this script is attached to. this.goImage = this.GetComponent<Image>(); //gameObject.SetActive (false); } void Start () { //Load all textures found on the Sequence folder, that is placed inside the resources folder this.objects = Resources.LoadAll(resourceFolder, typeof(Sprite)); //Initialize the array of textures with the same size as the objects array this.sprites = new Sprite[objects.Length]; //Cast each Object to Texture and store the result inside the Textures array for(int i=0; i < objects.Length;i++) { this.sprites[i] = (Sprite)this.objects[i]; } } void Update () { //Call the 'PlayLoop' method as a coroutine with a float delay StartCoroutine("PlayLoop", frameDelay); //Set the material's texture to the current value of the frameCounter variable goImage.overrideSprite = sprites[frameCounter]; } //The following methods return a IEnumerator so they can be yielded: //A method to play the animation in a loop IEnumerator PlayLoop(float delay) { //Wait for the time defined at the delay parameter yield return new WaitForSeconds(delay); //Advance one frame frameCounter = (++frameCounter)%sprites.Length; //Stop this coroutine StopCoroutine("PlayLoop"); } //A method to play the animation just once IEnumerator Play(float delay) { //Wait for the time defined at the delay parameter yield return new WaitForSeconds(delay); //If the frame counter isn't at the last frame if(frameCounter < sprites.Length-1) { //Advance one frame ++frameCounter; } //Stop this coroutine StopCoroutine("PlayLoop"); } }<file_sep>/Assets/Scripts/TouchHurt.cs using UnityEngine; using System.Collections; public class TouchHurt : MonoBehaviour { public float damage = 1; // assign in the editor void OnCollisionEnter ( Collision col ){ if (col.gameObject.tag == "Player") { DamageData dd = new DamageData(); dd.damage = damage; dd.owner = gameObject; dd.attackType = Const.AttackType.Melee; dd.isOtherNPC = false; col.gameObject.GetComponent<PlayerHealth>().TakeDamage(dd); } } }<file_sep>/Assets/Scripts/AIMeleeDamageCollider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIMeleeDamageCollider : MonoBehaviour { private int index; private int meleeColliderCounter = 0; private float impactMelee = 0f; private GameObject ownedBy; private AIController ownerAIC; private MeshCollider meshCollider; private BoxCollider boxCollider; private SphereCollider sphereCollider; private CapsuleCollider capCollider; public void MeleeColliderSetup (int ind, int colCount, float impact, GameObject sourceOwner) { index = ind; meleeColliderCounter = colCount; impactMelee = impact; ownedBy = sourceOwner; ownerAIC = ownedBy.GetComponent<AIController>(); meshCollider = GetComponent<MeshCollider>(); boxCollider = GetComponent<BoxCollider>(); sphereCollider = GetComponent<SphereCollider>(); capCollider = GetComponent<CapsuleCollider>(); if (meshCollider != null) meshCollider.isTrigger = true; if (boxCollider != null) boxCollider.isTrigger = true; if (sphereCollider != null) sphereCollider.isTrigger = true; if (capCollider != null) capCollider.isTrigger = true; } void OnTriggerEnter (Collider other) { if (other.tag == "Player" || other.tag == "NPC") { if (ownerAIC.meleeDamageFinished < Time.time) { ownerAIC.meleeDamageFinished = Time.time + ownerAIC.timeTillMeleeDamage; //Debug.Log("aimelee collider collided!"); DamageData ddNPC = Const.SetNPCDamageData(index, Const.aiState.Attack1, ownedBy); ddNPC.other = gameObject; ddNPC.attacknormal = Vector3.Normalize(other.transform.position - transform.position); ddNPC.impactVelocity = impactMelee; ddNPC.damage = 11f; float take = Const.a.GetDamageTakeAmount(ddNPC); take = (take / meleeColliderCounter); //split it for multiple tap melee attacks, e.g. double paw swipe ddNPC.damage = take; other.GetComponent<HealthManager>().TakeDamage(ddNPC); } } } } <file_sep>/Assets/Scripts/ItemTabManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ItemTabManager : MonoBehaviour { public GameObject iconManager; public GameObject textManager; public GameObject vaporizeButton; public GameObject applyButton; public GameObject useButton; public GameObject eReaderSectionsContainer; public int itemTabType; //TODO: what's this? private string nullstr; void Start () { nullstr = ""; Reset(); } public void Reset () { eReaderSectionsContainer.SetActive(false); iconManager.GetComponent<Image>().overrideSprite = Const.a.useableItemsIcons[0]; //nullsprite textManager.GetComponent<Text>().text = nullstr; applyButton.SetActive(false); vaporizeButton.SetActive(false); useButton.SetActive(false); } public void EReaderSectionSContainerOpen () { //Const.sprint("openingEreaderSectioninMFDLH",Const.a.player1); eReaderSectionsContainer.SetActive(true); iconManager.GetComponent<Image>().overrideSprite = Const.a.useableItemsIcons[23]; //datareader textManager.GetComponent<Text>().text = Const.a.useableItemsNameText[23]; } public void SendItemDataToItemTab(int constIndex) { eReaderSectionsContainer.SetActive(false); if (Const.a.useableItemsIcons[constIndex] != null) iconManager.GetComponent<Image>().overrideSprite = Const.a.useableItemsIcons[constIndex]; //datareader textManager.GetComponent<Text>().text = Const.a.useableItemsNameText[constIndex]; } } <file_sep>/Assets/Scripts/Unused/CameraFarPlaneOcclussion.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFarPlaneOcclussion : MonoBehaviour { public bool makeRaysVisible = false; public int defaultFarPlane = 100; public int minDistance = 20; public int maxDistance = 200; public int farPlaneBuffer = 10; public int rateOfReceding = 16; public Camera cameraAffected; public int distance; private float[] rayGridY = new float[] {1.00f, 0.60f, 0.59f, 0.58f, 0.57f, 0.56f, 0.55f, 0.54f, 0.53f, 0.52f, 0.51f, 0.50f, 0.49f, 0.48f, 0.47f, 0.46f, 0.45f, 0.44f, 0.43f, 0.42f, 0.41f, 0.40f, 0.00f}; private float[] rayGridX = new float[] {0.00f, 0.01f, 0.06f, 0.11f, 0.16f, 0.21f, 0.26f, 0.31f, 0.36f, 0.41f, 0.43f, 0.45f, 0.47f, 0.48f, 0.49f, 0.50f, 0.51f, 0.52f, 0.53f, 0.55f, 0.57f, 0.59f, 0.64f, 0.69f, 0.74f, 0.79f, 0.84f, 0.89f, 0.94f, 0.99f, 1.00f}; void Start () { cameraAffected.farClipPlane = defaultFarPlane; StartCoroutine (AdjustFarPlane()); } IEnumerator AdjustFarPlane () { while (true) { int farPlane = (int) cameraAffected.farClipPlane + farPlaneBuffer; distance = minDistance; bool ExtendFarPlane = false; foreach (float y in rayGridY) { foreach (float x in rayGridX) { int tempDist = CastOcclusionRay (x, y); if (tempDist >= farPlane) { distance = tempDist; ExtendFarPlane = true; goto SHIFT_FAR_PLANE; } } yield return 0; } SHIFT_FAR_PLANE: // Far plane should extend instantly, but recede slowly. if (ExtendFarPlane == false) { cameraAffected.farClipPlane -= rateOfReceding; if (cameraAffected.farClipPlane < minDistance) cameraAffected.farClipPlane = minDistance; } else { cameraAffected.farClipPlane = distance; } } } int CastOcclusionRay (float graphX, float graphY) { Ray ray = cameraAffected.ViewportPointToRay (new Vector3 (graphX, graphY, 0)); if (makeRaysVisible == true) Debug.DrawRay (ray.origin, ray.direction*20, Color.red); RaycastHit hit; if (Physics.Raycast (ray, out hit) && hit.distance < maxDistance) { return (int) hit.distance + farPlaneBuffer; } else { return (int) maxDistance; } } } <file_sep>/Assets/Scripts/ButtonListenPgUpDn.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ButtonListenPgUpDn : MonoBehaviour { public Button[] button; private int curTab = 0; // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.PageUp)) { curTab--; if (curTab < 0) curTab = 3; // Wrap around button[curTab].onClick.Invoke(); } if (Input.GetKeyDown(KeyCode.PageDown)) { curTab++; if (curTab > 3) curTab = 0; // Wrap around button[curTab].onClick.Invoke(); } } } <file_sep>/Assets/Scripts/HealingBed.cs using UnityEngine; using System.Collections; public class HealingBed : MonoBehaviour { public float amount = 170; //default to 2/3 of 255, the total player can have //public float resetTime = 150; //150 seconds //public bool requireReset; public int minSecurityLevel = 0; public bool broken = false; public AudioClip SFX; //private float nextthink; private float give; private AudioSource SFXSource; void Awake () { SFXSource = GetComponent<AudioSource>(); } public void Use (UseData ud) { if (LevelManager.a.GetCurrentLevelSecurity() <= minSecurityLevel) { if (!broken) { ud.owner.GetComponent<PlayerReferenceManager>().playerCapsule.GetComponent<PlayerHealth>().HealingBed(amount); Const.sprint("Automatic healing process activated.",ud.owner); SFXSource.PlayOneShot(SFX); } else { Const.sprint("Healing bed is broken beyond repair",ud.owner); } } } } <file_sep>/Assets/Scripts/GravityLift.cs using UnityEngine; using System.Collections; public class GravityLift : MonoBehaviour { public float strength = 30f; private Rigidbody otherRbody; private float modulatedStrengthY; void OnTriggerStay (Collider other) { otherRbody = other.gameObject.GetComponent<Rigidbody>(); // TODO check if flier bot, avian mutant, or projectile and return without affecting it if (otherRbody != null) { if (otherRbody.velocity.y < strength) otherRbody.AddForce(new Vector3(0f, (strength-otherRbody.velocity.y), 0f)); } } } <file_sep>/Assets/Scripts/AccessCardInventory.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AccessCardInventory : MonoBehaviour { public Door.accessCardType[] accessCardsOwned; private int i = 0; private int defIndex = 0; void Awake() { for (i=defIndex;i<accessCardsOwned.Length;i++) { accessCardsOwned[i] = Door.accessCardType.None; } } public bool HasAccessCard(Door.accessCardType card) { for (i=defIndex;i<accessCardsOwned.Length;i++) { if (accessCardsOwned[i] == card) return true; } return false; } public bool AddCardToInventory(Door.accessCardType card) { for (i=defIndex;i<accessCardsOwned.Length;i++) { if (accessCardsOwned[i] == Door.accessCardType.None) { accessCardsOwned[i] = card; return true; } } return false; } } <file_sep>/Assets/Scripts/SimpleSpriteDestroy.cs using UnityEngine; using System.Collections; public class SimpleSpriteDestroy : MonoBehaviour { public void DestroySprite() { Destroy(gameObject); } } <file_sep>/Assets/Scripts/GeneralInventoryButtonsManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class GeneralInventoryButtonsManager : MonoBehaviour { public GameObject[] genButtons; void Update() { for (int i=0; i<14; i++) { if (GeneralInventory.GeneralInventoryInstance.generalInventoryIndexRef[i] > -1) { if (!genButtons[i].activeInHierarchy) genButtons[i].SetActive(true); } else { if (genButtons[i].activeInHierarchy) genButtons[i].SetActive(false); } } } } <file_sep>/Assets/Scripts/PauseScript.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class PauseScript : MonoBehaviour { public Text pauseText; public bool paused = false; public static PauseScript a; public MouseLookScript mouselookScript; public MouseCursor mouseCursor; public GameObject[] disableUIOnPause; private bool previousInvMode = false; private Texture2D previousCursorImage; public GameObject saltTheFries; public GameObject[] enableUIOnPause; public GameObject mainMenu; public GameObject saveDialog; public bool onSaveDialog; void Awake() {a = this;} void Update () { if (mainMenu == null) { Const.sprint("ERROR->PauseScript: mainMenu is null!",Const.a.allPlayers); return; } if (mainMenu.activeSelf == false) { if (GetInput.a.Menu()) { if (onSaveDialog) { ExitSaveDialog(); } else { PauseToggle(); } } if (Input.GetKeyDown(KeyCode.Home)) { PauseEnable(); } if (Input.GetKeyDown(KeyCode.Menu)) { PauseEnable(); } } } public void PauseToggle() { if (paused == true) PauseDisable(); else PauseEnable(); } void PauseEnable() { previousInvMode = mouselookScript.inventoryMode; if (mouselookScript.inventoryMode == false) { mouselookScript.ToggleInventoryMode(); } paused = true; pauseText.enabled = true; previousCursorImage = mouseCursor.cursorImage; mouseCursor.cursorImage = mouselookScript.cursorDefaultTexture; for (int i=0;i<disableUIOnPause.Length;i++) { disableUIOnPause[i].SetActive(false); } EnablePauseUI(); PauseRigidbody[] prb = FindObjectsOfType<PauseRigidbody>(); for (int k=0;k<prb.Length;k++) { prb[k].Pause(); } } void PauseDisable() { paused = false; pauseText.enabled = false; if (previousInvMode != mouselookScript.inventoryMode) { mouselookScript.ToggleInventoryMode(); } mouseCursor.cursorImage = previousCursorImage; for (int i=0;i<disableUIOnPause.Length;i++) { disableUIOnPause[i].SetActive(true); } for (int j=0;j<enableUIOnPause.Length;j++) { enableUIOnPause[j].SetActive(false); } PauseRigidbody[] prb = FindObjectsOfType<PauseRigidbody>(); for (int k=0;k<prb.Length;k++) { prb[k].UnPause(); } } public void OpenSaveDialog() { onSaveDialog = true; saveDialog.SetActive(true); } public void ExitSaveDialog() { saveDialog.SetActive(false); onSaveDialog = false; } public void SavePauseQuit() { for (int i=0;i<enableUIOnPause.Length;i++) { enableUIOnPause[i].SetActive(false); } saveDialog.SetActive(false); // turn off dialog mainMenu.SetActive(true); mainMenu.GetComponent<MainMenuHandler>().GoToSaveGameSubmenu(true); } public void NoSavePauseQuit () { //StartCoroutine(quitFunction()); for (int i=0;i<enableUIOnPause.Length;i++) { enableUIOnPause[i].SetActive(false); } saveDialog.SetActive(false); // turn off dialog mainMenu.SetActive(true); mainMenu.GetComponent<MainMenuHandler>().GoToFrontPage(); } public void EnablePauseUI () { for (int i=0;i<enableUIOnPause.Length;i++) { enableUIOnPause[i].SetActive(true); } } public void PauseOptions () { for (int i=0;i<enableUIOnPause.Length;i++) { enableUIOnPause[i].SetActive(false); } mainMenu.SetActive(true); mainMenu.GetComponent<MainMenuHandler>().GoToOptionsSubmenu(true); } } <file_sep>/Assets/Scripts/EnergyOverloadButton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnergyOverloadButton : MonoBehaviour { public Color textClickableColor; public Color textDisabledColor; public Color textOverloadColor; public Color textEnergySetting; public Color textEnergyOverloaded; public Sprite normalButtonSprite; public Sprite overloadButtonSprite; public WeaponFire wf; public Text buttonText; public Text energySettingText; private Image buttonSprite; private void Awake() { buttonSprite = GetComponent<Image>(); buttonSprite.overrideSprite = normalButtonSprite; buttonText.color = textClickableColor; } public void OverloadEnergyClick() { if (wf.GetHeatForCurrentWeapon() > 25f) { Const.sprint("Weapon too hot for overload", Const.a.allPlayers); return; } if (wf.overloadEnabled) { Const.sprint("Weapon normal setting", Const.a.allPlayers); wf.overloadEnabled = false; buttonSprite.overrideSprite = normalButtonSprite; buttonText.color = textClickableColor; energySettingText.color = textEnergySetting; energySettingText.text = "ENERGY SETTING"; } else { Const.sprint("Weapon overload enabled", Const.a.allPlayers); wf.overloadEnabled = true; buttonSprite.overrideSprite = overloadButtonSprite; buttonText.color = textOverloadColor; energySettingText.color = textEnergyOverloaded; energySettingText.text = "OVERLOAD ENABLED"; } } public void OverloadFired() { buttonSprite.overrideSprite = normalButtonSprite; buttonText.color = textDisabledColor; } void Start() { GetComponent<Button>().onClick.AddListener(() => { OverloadEnergyClick(); }); } } <file_sep>/Assets/Resources/DataReaderTextContainer.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; using System.IO; [XmlRoot("AudioLogsCollection")] public class DataReaderTextContainer { [XmlArray("AudioLogs")] [XmlArrayItem("LogContent")] public List <Log> audioLogs = new List<Log>(); public static DataReaderTextContainer Load(string path) { TextAsset _xml = Resources.Load <TextAsset> (path); XmlSerializer serializer = new XmlSerializer (typeof(DataReaderTextContainer)); StringReader reader = new StringReader (_xml.text); DataReaderTextContainer audioLogs = serializer.Deserialize(reader) as DataReaderTextContainer; //DataReaderTextContainer logTexts = serializer.Deserialize(reader) as DataReaderTextContainer; reader.Close(); return audioLogs; } }<file_sep>/Assets/Scripts/ConfigurationMenuVideo.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigurationMenuVideo : MonoBehaviour { public Resolution[] resolutions; private Dropdown resSelector; void Awake () { //List<int> widths = new List<int>(); //List<int> heights = new List<int>(); resolutions = Screen.resolutions; resSelector = GetComponent<Dropdown>(); List<string> resList = new List<string>(); for (int i=0;i<resolutions.Length;i++) { //widths.Add(resolutions[i].width); resList.Add(resolutions[i].width.ToString() + "x" + resolutions[i].height); } resSelector.ClearOptions(); resSelector.AddOptions(resList); } } <file_sep>/Assets/Scripts/MouseLookScript.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using System.Collections; public class MouseLookScript : MonoBehaviour { // Internal to Prefab // ------------------------------------------------------------------------ public GameObject player; public float recompile; [Tooltip("Shows current state of Inventory Mode (Don't set yourself!)")] public bool inventoryMode; [Tooltip("Shows current state of Holding an Object (Don't set yourself!)")] public bool holdingObject; [Tooltip("The current cursor texture (For Reference or Testing)")] public Texture2D cursorTexture; [Tooltip("The default cursor texture (Developer sets default)")] public Texture2D cursorDefaultTexture; [HideInInspector] public Vector2 cursorHotspot; [Tooltip("Mouselook sensitivity (Developer sets default)")] public float lookSensitivity = 5; [Tooltip("Sound effect to play when searching an object")] public AudioClip SearchSFX; [Tooltip("Sound effect to play when picking-up/frobbing an object")] public AudioClip PickupSFX; [Tooltip("Sound effect to play when picking-up/frobbing a hardware item")] public AudioClip hwPickupSFX; [Tooltip("Distance from player origin to spawn objects when tossing them")] public float tossOffset = 0.10f; [Tooltip("Force given to spawned objects when tossing them")] public float tossForce = 200f; //[HideInInspector] public int heldObjectIndex; public int heldObjectCustomIndex; public int heldObjectAmmo; public bool heldObjectAmmoIsSecondary; public bool firstTimePickup; public bool firstTimeSearch; public bool grenadeActive; public bool inCyberSpace; [HideInInspector] public float yRotation; [Tooltip("Initial camera x rotation")] public float startxRotation = 0f; [Tooltip("Initial camera y rotation")] public float startyRotation = 0f; [Tooltip("Indicates whether genius patch is active for reversing LH & RH")] public bool geniusActive; [Tooltip("How far player can reach to use, pickup, search, etc. objects")] public float frobDistance = 4.5f; [Tooltip("Speed multiplier for turning the view with the keyboard")] public float keyboardTurnSpeed = 1.5f; public float xRotation; [HideInInspector] public Vector3 cyberLookDir; public Vector3 cameraFocusPoint; private int tempindex; private float zRotation; private float yRotationV; private float xRotationV; private float zRotationV; private float currentZRotation; private string mlookstring1; private Camera playerCamera; private GameObject heldObject; private bool itemAdded = false; private int indexAdjustment; private Quaternion tempQuat; private Vector3 tempVec; private Vector3 cameraDefaultLocalPos; //private Quaternion cameraDefaultLocalRot; private Vector3 cameraRecoilLerpPos; [SerializeField] private bool recoiling; private Door.accessCardType doorAccessTypeAcquired; // External to Prefab // ------------------------------------------------------------------------ public MouseCursor mouseCursor; public GameObject canvasContainer; public GameObject compassContainer; public GameObject compassMidpoints; public GameObject compassLargeTicks; public GameObject compassSmallTicks; [Tooltip("Game object that houses the MFD tabs")] public GameObject tabControl; [Tooltip("Text in the data tab in the MFD that displays when searching an object containing no items")] public Text dataTabNoItemsText; public DataTab dataTabControl; public LogContentsButtonsManager logContentsManager; public AudioSource SFXSource; [SerializeField] private CenterTabButtons centerTabButtonsControl; [SerializeField] private MFDManager mfdManager; [SerializeField] private GameObject iconman; [SerializeField] private GameObject itemiconman; [SerializeField] private GameObject itemtextman; [SerializeField] private GameObject ammoiconman; [SerializeField] private GameObject weptextman; [SerializeField] private GameObject ammoClipBox; [SerializeField] private GrenadeCurrent grenadeCurrent; [HideInInspector] public GameObject currentButton; [HideInInspector] public GameObject currentSearchItem; [HideInInspector] //public GameObject mouseCursor; public GameObject weaponButtonsManager; public GameObject mainInventory; [HideInInspector] public LogInventory logInventory; public AccessCardInventory accessCardInventory; public GameObject[] hardwareButtons; public GameObject mainMenu; public WeaponMagazineCounter wepmagCounter; public PlayerMovement playerMovement; //float headbobSpeed = 1; //float headbobStepCounter; //float headbobAmountX = 1; //float headbobAmountY = 1; //Vector3 parentLastPos; //float eyeHeightRatio = 0.9f; //void Awake (){ //parentLastPos = transform.parent.position; //} void Start (){ //mouseCursor = GameObject.Find("MouseCursorHandler"); // if (mouseCursor == null) // Const.sprint("BUG: Could Not Find object 'MouseCursorHandler' in scene",player); ResetCursor(); Cursor.lockState = CursorLockMode.None; inventoryMode = true; // Start with inventory mode turned on playerCamera = GetComponent<Camera>(); frobDistance = Const.a.frobDistance; holdingObject = false; heldObjectIndex = -1; heldObjectAmmo = 0; heldObjectAmmoIsSecondary = false; grenadeActive = false; yRotation = startyRotation; xRotation = startxRotation; cyberLookDir = Vector3.zero; logInventory = mainInventory.GetComponent<LogInventory>(); if (canvasContainer == null) Const.sprint("BUG: No canvas given for camera to display UI",player); canvasContainer.SetActive(true); //enable UI cameraDefaultLocalPos = transform.localPosition; //cameraDefaultLocalRot = transform.localRotation; recoiling = false; firstTimePickup = true; firstTimeSearch = true; } public void Recoil (int i) { float strength = Const.a.recoilForWeapon[i]; //Debug.Log("Recoil from gun index: "+i.ToString()+" with strength of " +strength.ToString()); if (strength <= 0f) return; if (playerMovement.fatigue > 80) strength = strength * 2f; //Vector3 cameraJoltPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, (transform.localPosition.z - strength)); //transform.localPosition = cameraJoltPosition; recoiling = true; } void Update () { Cursor.visible = false; // Hides hardware cursor so we can show custom cursor textures if (recoiling && !inCyberSpace) { //float x = transform.localPosition.x; // side to side //float y = transform.localPosition.y; // up and down //float z = transform.localPosition.z; // forward and back //z = Mathf.Lerp(z,cameraDefaultLocalPos.z,Time.deltaTime); //tempVec = new Vector3(x,y,z); //transform.localPosition = tempVec; } //Debug.Log("MouseLookScript:: Input.mousePosition.x: " + Input.mousePosition.x.ToString() + ", Input.mousePosition.y: " + Input.mousePosition.y.ToString()); //if (transform.parent.GetComponent<PlayerMovement>().grounded) //headbobStepCounter += (Vector3.Distance(parentLastPos, transform.parent.position) * headbobSpeed); //transform.localPosition.x = (Mathf.Sin(headbobStepCounter) * headbobAmountX); //transform.localPosition.y = (Mathf.Cos(headbobStepCounter * 2) * headbobAmountY * -1) + (transform.localScale.y * eyeHeightRatio) - (transform.localScale.y / 2); //parentLastPos = transform.parent.position; // Spring Back to Rest from Recoil TODO only do this when necessary and add some private variables to prevent GarbageCollector float camz = Mathf.Lerp(transform.localPosition.z,0f,0.1f); Vector3 camPos = new Vector3(0f,Const.a.playerCameraOffsetY,camz); transform.localPosition = camPos; // Draw line from cursor - used for projectile firing, e.g. magpulse/stugngun/railgun/plasma RaycastHit rayhit = new RaycastHit(); Vector3 cursorPoint0 = new Vector3(MouseCursor.drawTexture.x + (MouseCursor.drawTexture.width / 2), MouseCursor.drawTexture.y + (MouseCursor.drawTexture.height / 2), 0); cursorPoint0.y = Screen.height - cursorPoint0.y; // Flip it. Rect uses y=0 UL corner, ScreenPointToRay uses y=0 LL corner if (Physics.Raycast(playerCamera.ScreenPointToRay(cursorPoint0), out rayhit, Mathf.Infinity)) { cameraFocusPoint = rayhit.point; //drawMyLine(playerCamera.transform.position, rayhit.point, Color.red, .1f); } if (mainMenu.activeSelf == true) return; // ignore mouselook when main menu is still up if (Input.GetKeyUp("f6")) { Const.a.Save(7); } if (Input.GetKeyUp("f9")) { Const.a.Load(7); } if (inventoryMode == false) { if (PauseScript.a != null && !PauseScript.a.paused) { float dx = Input.GetAxisRaw("Mouse X"); float dy = Input.GetAxisRaw("Mouse Y"); yRotation += (dx * lookSensitivity); xRotation -= (dy * lookSensitivity); if (!inCyberSpace) xRotation = Mathf.Clamp(xRotation, -90f, 90f); // Limit up and down angle transform.parent.transform.parent.transform.localRotation = Quaternion.Euler(0f, yRotation, 0f); // left right component applied to capsule transform.localRotation = Quaternion.Euler(xRotation,0f,0f); // Up down component only applied to camera if (inCyberSpace) cyberLookDir = Vector3.Normalize (transform.forward); if (compassContainer.activeInHierarchy) { compassContainer.transform.rotation = Quaternion.Euler(0f, -yRotation + 180f, 0f); } } else { Const.sprint("ERROR: Paused is true and inventoryMode is false",player); } } else { if (Input.GetButton("Yaw")) { if (!PauseScript.a.paused) { if (Input.GetAxisRaw("Yaw") > 0) { yRotation += keyboardTurnSpeed * lookSensitivity; tempQuat = transform.rotation; transform.parent.transform.parent.transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0); transform.parent.transform.parent.transform.localRotation = tempQuat; // preserve x axis, hacky } else { if (Input.GetAxisRaw("Yaw") < 0) { yRotation -= keyboardTurnSpeed * lookSensitivity; tempQuat = transform.rotation; transform.parent.transform.parent.transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0); transform.parent.transform.parent.transform.localRotation = tempQuat; // preserve x axis, hacky } } } } if (Input.GetButton("Pitch")) { if (!PauseScript.a.paused) { if (Input.GetAxisRaw("Pitch") > 0) { xRotation += keyboardTurnSpeed * lookSensitivity; transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0); } else { xRotation -= keyboardTurnSpeed * lookSensitivity; transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0); } } } } // Toggle inventory mode<->shoot mode if (GetInput.a != null && PauseScript.a != null) { if(GetInput.a.ToggleMode() && !PauseScript.a.paused) { ToggleInventoryMode(); } } // Frob/use if the cursor is not on the UI if (!GUIState.a.isBlocking) { if (!PauseScript.a.paused) { currentButton = null; if(GetInput.a.Use()) { if (!holdingObject) { // Send out Frob/use raycast to use whatever is under the cursor, if in reach RaycastHit hit = new RaycastHit(); Vector3 cursorPoint = new Vector3(MouseCursor.drawTexture.x+(MouseCursor.drawTexture.width/2),MouseCursor.drawTexture.y+(MouseCursor.drawTexture.height/2),0); cursorPoint.y = Screen.height - cursorPoint.y; // Flip it. Rect uses y=0 UL corner, ScreenPointToRay uses y=0 LL corner if (Physics.Raycast(playerCamera.ScreenPointToRay(cursorPoint), out hit, frobDistance)) { //Debug.Log("Screen.width = " + Screen.width.ToString() + ", Screen.height = " + Screen.height.ToString() +", Camera.pixelWidth = " + playerCamera.pixelWidth.ToString() + ", Camera.pixelHeight = " + playerCamera.pixelHeight.ToString() + ", drawTexture.x = " +MouseCursor.drawTexture.x.ToString() + ", drawTexture.y = " + MouseCursor.drawTexture.y.ToString()); //drawMyLine(playerCamera.transform.position,hit.point,Color.green,10f); if (hit.collider == null) return; // Check if object is usable then use it if (hit.collider.tag == "Usable") { //Debug.Log("Raycast hit a usable!"); UseData ud = new UseData (); ud.owner = player; //hit.transform.SendMessageUpwards("Use", ud); // send Use with self as owner of message DIE SendMessage DIE!!! if (hit.transform.GetComponent<UseHandler>() != null) { //Debug.Log("Found a UseHandler!"); hit.transform.GetComponent<UseHandler>().Use(ud); // Just plain use it, handler checks for and has any and all scripts run their Use(UseData ud) function, passing along ud } else { //Debug.Log("Couldn't find a UseHandler"); if (hit.transform.GetComponent<UseHandlerRelay>() != null) { hit.transform.GetComponent<UseHandlerRelay>().referenceUseHandler.Use(ud); //Debug.Log("Found a UseHandlerRelay!"); } else { //Debug.Log("Warning: could not find UseHandler or UseHandlerRelay on hit.transform"); } } return; } // Check if object is searchable then search it if (hit.collider.tag == "Searchable") { currentSearchItem = hit.collider.gameObject; SearchObject(currentSearchItem.GetComponent<SearchableItem>().lookUpIndex); return; } // If we can't use it, Give info about what we are looking at (e.g. "Molybdenum panelling") UseName un = hit.collider.gameObject.GetComponent<UseName> (); if (un != null) { Const.sprint("Can't use " + un.name,player); } } if (Physics.Raycast(playerCamera.ScreenPointToRay(MouseCursor.drawTexture.center), out hit, 50f)) { //drawMyLine(playerCamera.transform.position,hit.point,Color.green,10f); // TIP: Use Camera.main.ViewportPointToRay for center of screen if (hit.collider == null) return; // Check if object is usable then use it if (hit.collider.tag == "Usable" || hit.collider.tag == "Searchable") { Const.sprint("You are too far away from that",player); return; } } } else { // First check and see if we can apply held object in a use, or else Drop the object we are holding if (heldObjectIndex != -1) { if (heldObjectIndex == 54 || heldObjectIndex == 56 || heldObjectIndex == 57 || heldObjectIndex == 61 || heldObjectIndex == 64) { RaycastHit hit = new RaycastHit(); Vector3 cursorPoint = new Vector3(MouseCursor.drawTexture.x+(MouseCursor.drawTexture.width/2),MouseCursor.drawTexture.y+(MouseCursor.drawTexture.height/2),0); cursorPoint.y = Screen.height - cursorPoint.y; // Flip it. Rect uses y=0 UL corner, ScreenPointToRay uses y=0 LL corner if (Physics.Raycast(playerCamera.ScreenPointToRay(cursorPoint), out hit, frobDistance)) { //Debug.Log("Screen.width = " + Screen.width.ToString() + ", Screen.height = " + Screen.height.ToString() +", Camera.pixelWidth = " + playerCamera.pixelWidth.ToString() + ", Camera.pixelHeight = " + playerCamera.pixelHeight.ToString() + ", drawTexture.x = " +MouseCursor.drawTexture.x.ToString() + ", drawTexture.y = " + MouseCursor.drawTexture.y.ToString()); //drawMyLine(playerCamera.transform.position,hit.point,Color.green,10f); // Check if object is usable then use it if (hit.collider.tag == "Usable") { UseData ud = new UseData (); ud.owner = player; ud.mainIndex = heldObjectIndex; ud.customIndex = heldObjectCustomIndex; hit.transform.SendMessageUpwards("Use", ud); // send Use with self as owner of message return; } } ResetHeldItem(); ResetCursor (); } else { // Drop it DropHeldItem (); ResetHeldItem (); ResetCursor (); } } } } } } else { //We are holding cursor over the GUI if(GetInput.a.Use()) { if (holdingObject && !PauseScript.a.paused) { AddItemToInventory(heldObjectIndex); ResetHeldItem(); ResetCursor(); } else { if (GUIState.a.overButton && GUIState.a.overButtonType != GUIState.ButtonType.None) { // overButtonTypes: // -1 Not over a button // 0 WeaponButton // 1 GrenadeButton // 2 PatchButton // 3 GeneralInventoryButton // 4 Search contents button if (!PauseScript.a.paused) { switch(GUIState.a.overButtonType) { case GUIState.ButtonType.Weapon: WeaponButton wepbut = currentButton.GetComponent<WeaponButton>(); cursorTexture = Const.a.useableItemsFrobIcons[wepbut.useableItemIndex]; heldObjectIndex = wepbut.useableItemIndex; indexAdjustment = wepbut.WepButtonIndex; WeaponInventory.WepInventoryInstance.weaponInventoryIndices[indexAdjustment] = -1; WeaponInventory.WepInventoryInstance.weaponInventoryText[indexAdjustment] = "-"; indexAdjustment--; if (indexAdjustment < 0) indexAdjustment = 0; WeaponCurrent.WepInstance.weaponCurrent = indexAdjustment; GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); break; case GUIState.ButtonType.Grenade: GrenadeButton grenbut = currentButton.GetComponent<GrenadeButton>(); cursorTexture = Const.a.useableItemsFrobIcons[grenbut.useableItemIndex]; heldObjectIndex = grenbut.useableItemIndex; GrenadeInventory.GrenadeInvInstance.grenAmmo[grenbut.GrenButtonIndex]--; if (GrenadeInventory.GrenadeInvInstance.grenAmmo[grenbut.GrenButtonIndex] <= 0) { GrenadeInventory.GrenadeInvInstance.grenAmmo[grenbut.GrenButtonIndex] = 0; for (int i = 0; i < 7; i++) { if (GrenadeInventory.GrenadeInvInstance.grenAmmo[i] > 0) { mainInventory.GetComponent<GrenadeCurrent>().grenadeCurrent = i; } } } break; case GUIState.ButtonType.Patch: PatchButton patbut = currentButton.GetComponent<PatchButton>(); cursorTexture = Const.a.useableItemsFrobIcons[patbut.useableItemIndex]; heldObjectIndex = patbut.useableItemIndex; PatchInventory.PatchInvInstance.patchCounts[patbut.PatchButtonIndex]--; if (PatchInventory.PatchInvInstance.patchCounts[patbut.PatchButtonIndex] <= 0) { PatchInventory.PatchInvInstance.patchCounts[patbut.PatchButtonIndex] = 0; GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); for (int i = 0; i < 7; i++) { if (PatchInventory.PatchInvInstance.patchCounts[i] > 0) { mainInventory.GetComponent<PatchCurrent>().patchCurrent = i; } } } break; case GUIState.ButtonType.GeneralInv: GeneralInvButton genbut = currentButton.GetComponent<GeneralInvButton>(); cursorTexture = Const.a.useableItemsFrobIcons[genbut.useableItemIndex]; heldObjectIndex = genbut.useableItemIndex; GeneralInventory.GeneralInventoryInstance.generalInventoryIndexRef[genbut.GeneralInvButtonIndex] = -1; break; case GUIState.ButtonType.Search: SearchButton sebut = currentButton.GetComponentInParent<SearchButton>(); int tempButtonindex = currentButton.GetComponent<SearchContainerButton>().refIndex; cursorTexture = Const.a.useableItemsFrobIcons[sebut.contents[tempButtonindex]]; heldObjectIndex = sebut.contents[tempButtonindex]; heldObjectCustomIndex = sebut.customIndex[tempButtonindex]; currentSearchItem.GetComponent<SearchableItem>().contents[tempButtonindex] = -1; currentSearchItem.GetComponent<SearchableItem>().customIndex[tempButtonindex] = -1; sebut.contents[tempButtonindex] = -1; sebut.customIndex[tempButtonindex] = -1; sebut.GetComponentInParent<DataTab>().searchItemImages[tempButtonindex].SetActive(false); sebut.CheckForEmpty(); GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); break; } if (GUIState.a.overButtonType != GUIState.ButtonType.Generic) { mouseCursor.cursorImage = cursorTexture; ForceInventoryMode(); holdingObject = true; } } } } } } } // Add usable items to inventory: // ============================================== void AddGenericObjectToInventory(int index) { if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (2); centerTabButtonsControl.NotifyToCenterTab(2); } itemAdded = false; //prevent false positive for (int i=0;i<14;i++) { if (GeneralInventory.GeneralInventoryInstance.generalInventoryIndexRef[i] == -1) { GeneralInventory.GeneralInventoryInstance.generalInventoryIndexRef[i] = index; Const.sprint("Item added to general inventory",player); itemAdded = true; break; } } if (!itemAdded) { DropHeldItem(); ResetHeldItem(); ResetCursor(); Const.sprint("Inventory full, item dropped",player); return; } mainInventory.GetComponent<GeneralInvCurrent>().generalInvCurrent = index; mfdManager.SendInfoToItemTab(index); centerTabButtonsControl.NotifyToCenterTab(2); } void AddWeaponToInventory(int index) { if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (0); mfdManager.OpenTab (0, true, MFDManager.TabMSG.None, 0,MFDManager.handedness.LeftHand); centerTabButtonsControl.NotifyToCenterTab(0); } itemAdded = false; //prevent false positive for (int i=0;i<7;i++) { if (WeaponInventory.WepInventoryInstance.weaponInventoryIndices[i] < 0) { WeaponInventory.WepInventoryInstance.weaponInventoryIndices[i] = index; WeaponInventory.WepInventoryInstance.weaponInventoryText[i] = WeaponInventory.WepInventoryInstance.weaponInvTextSource[(index - 36)]; WeaponCurrent.WepInstance.weaponCurrent = i; WeaponCurrent.WepInstance.weaponIndex = index; weaponButtonsManager.GetComponent<WeaponButtonsManager>().wepButtons[i].GetComponent<WeaponButton>().useableItemIndex = index; if (!ammoClipBox.activeInHierarchy) ammoClipBox.SetActive(true); if (ammoiconman.activeInHierarchy) ammoiconman.GetComponent<AmmoIconManager>().SetAmmoIcon(index, false); if (iconman.activeInHierarchy) iconman.GetComponent<WeaponIconManager>().SetWepIcon(index); //Set weapon icon for MFD if (weptextman.activeInHierarchy) weptextman.GetComponent<WeaponTextManager>().SetWepText(index); //Set weapon text for MFD if (itemiconman.activeInHierarchy) itemiconman.SetActive(false); //Set weapon icon for MFD if (itemtextman.activeInHierarchy) itemtextman.GetComponent<ItemTextManager>().SetItemText(index); //Set weapon text for MFD Const.sprint("Weapon added to inventory",player); itemAdded = true; centerTabButtonsControl.NotifyToCenterTab(0); tempindex = WeaponFire.Get16WeaponIndexFromConstIndex(index); if (heldObjectAmmo > 0) { int extra = 0; if (heldObjectAmmoIsSecondary) { if (heldObjectAmmo > Const.a.magazinePitchCountForWeapon2[tempindex]) { extra = (heldObjectAmmo - Const.a.magazinePitchCountForWeapon2[tempindex]); heldObjectAmmo = Const.a.magazinePitchCountForWeapon2[tempindex]; } } else { if (heldObjectAmmo > Const.a.magazinePitchCountForWeapon[tempindex]) { extra = (heldObjectAmmo - Const.a.magazinePitchCountForWeapon[tempindex]); heldObjectAmmo = Const.a.magazinePitchCountForWeapon[tempindex]; } } if (WeaponCurrent.WepInstance.weaponIsAlternateAmmo) { if (WeaponCurrent.WepInstance.currentMagazineAmount2[tempindex] <=0) { WeaponCurrent.WepInstance.currentMagazineAmount2[tempindex] = heldObjectAmmo; // Update the counter MFDManager.a.UpdateHUDAmmoCounts(WeaponCurrent.WepInstance.currentMagazineAmount2[tempindex]); } } else { if (WeaponCurrent.WepInstance.currentMagazineAmount[tempindex] <=0) { WeaponCurrent.WepInstance.currentMagazineAmount[tempindex] = heldObjectAmmo; // Update the counter MFDManager.a.UpdateHUDAmmoCounts(WeaponCurrent.WepInstance.currentMagazineAmount[tempindex]); } } if (heldObjectAmmoIsSecondary && extra > 0) { WeaponAmmo.a.wepAmmoSecondary[tempindex] += extra; } else { WeaponAmmo.a.wepAmmo[tempindex] += extra; } } if (!WeaponInventory.WepInventoryInstance.weaponFound [tempindex]) WeaponInventory.WepInventoryInstance.weaponFound [tempindex] = true; break; } } if (!itemAdded) { DropHeldItem(); ResetHeldItem(); ResetCursor(); Const.sprint("Inventory full, item dropped",player); return; } mfdManager.SendInfoToItemTab(index); } void AddAmmoToInventory (int index, int amount, bool isSecondary) { if (index == -1) return; if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (0); centerTabButtonsControl.NotifyToCenterTab(0); } if (isSecondary) { WeaponAmmo.a.wepAmmoSecondary [index] += amount; } else { WeaponAmmo.a.wepAmmo [index] += amount; } centerTabButtonsControl.NotifyToCenterTab(0); mfdManager.SendInfoToItemTab(index); } void AddGrenadeToInventory (int index) { if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (0); centerTabButtonsControl.NotifyToCenterTab(0); } GrenadeInventory.GrenadeInvInstance.grenAmmo[index]++; grenadeCurrent.grenadeCurrent = index; Const.sprint("Grenade added to inventory",player); centerTabButtonsControl.NotifyToCenterTab(0); mfdManager.SendInfoToItemTab(index); } void AddPatchToInventory (int index) { if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (0); centerTabButtonsControl.NotifyToCenterTab(0); } PatchInventory.PatchInvInstance.AddPatchToInventory(index); //PatchInventory.PatchInvInstance.patchCounts[index]++; PatchCurrent.PatchInstance.patchCurrent = index; mfdManager.SendInfoToItemTab(index); Const.sprint("Patch added to inventory",player); } void AddAudioLogToInventory () { if ((heldObjectCustomIndex != -1) && (logInventory != null)) { logInventory.hasLog[heldObjectCustomIndex] = true; logInventory.lastAddedIndex = heldObjectCustomIndex; int levelnum = Const.a.audioLogLevelFound[heldObjectCustomIndex]; logInventory.numLogsFromLevel[levelnum]++; logContentsManager.InitializeLogsFromLevelIntoFolder(); string audName = Const.a.audiologNames[heldObjectCustomIndex]; string logPlaybackKey = Const.a.InputConfigNames[20]; Const.sprint("Audio log " + audName + " picked up. Press '" + logPlaybackKey + "' to playback.",player); } else { if (logInventory == null) { Const.sprint("Warning: logInventory is null",player); } else { Const.sprint("Warning: Audio log picked up has no assigned index (-1)",player); } } } void AddAccessCardToInventory (int index) { if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (2); } bool alreadyHave = false; bool accessAdded = false; switch (index) { case 81: doorAccessTypeAcquired = Door.accessCardType.Standard; break; case 82: doorAccessTypeAcquired = Door.accessCardType.Group1; break; case 83: doorAccessTypeAcquired = Door.accessCardType.Science; break; case 84: doorAccessTypeAcquired = Door.accessCardType.Group3; break; case 85: doorAccessTypeAcquired = Door.accessCardType.Engineering; break; case 86: doorAccessTypeAcquired = Door.accessCardType.Standard; break; case 87: doorAccessTypeAcquired = Door.accessCardType.Standard; break; case 88: doorAccessTypeAcquired = Door.accessCardType.Standard; break; case 89: doorAccessTypeAcquired = Door.accessCardType.Medical; break; case 90: doorAccessTypeAcquired = Door.accessCardType.Standard; break; case 91: doorAccessTypeAcquired = Door.accessCardType.Per1; break; } for (int j = 0; j < accessCardInventory.accessCardsOwned.Length; j++) { if (accessCardInventory.accessCardsOwned [j] == doorAccessTypeAcquired) alreadyHave = true; // check if we already have this card } for (int i = 0; i < accessCardInventory.accessCardsOwned.Length; i++) { if (accessCardInventory.accessCardsOwned [i] == Door.accessCardType.None) { if (!alreadyHave) { accessCardInventory.accessCardsOwned [i] = doorAccessTypeAcquired; accessAdded = true; break; } } } if (alreadyHave) { Const.sprint ("Already have that access.", player); return; } if (accessAdded && !alreadyHave) { Const.sprint ("New accesses gained: " + doorAccessTypeAcquired.ToString(), player); } centerTabButtonsControl.NotifyToCenterTab(2); mfdManager.SendInfoToItemTab(index); } void AddHardwareToInventory (int index) { int hwversion = heldObjectCustomIndex; if (hwversion < 0) { Const.sprint("Warning: Hardware picked up has no assigned versioning, defaulting to 1",player); hwversion = 1; } switch(index) { case 0: // System Analyzer if (hwversion <= HardwareInventory.a.hardwareVersion[0]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[0] = true; HardwareInventory.a.hardwareVersion[0] = hwversion; //HardwareInvCurrent.a.hardwareInvIndex Const.sprint(Const.a.useableItemsNameText[21] + " v" + hwversion.ToString(),player); break; case 1: // Navigation Unit if (hwversion <= HardwareInventory.a.hardwareVersion[1]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[1] = true; HardwareInventory.a.hardwareVersion[1] = hwversion; Const.sprint(Const.a.useableItemsNameText[22] + " v" + hwversion.ToString(),player); compassContainer.SetActive(true); // Turn on HUD compass if (hwversion == 2) { compassMidpoints.SetActive(true); } if (hwversion > 2) { compassSmallTicks.SetActive(true); compassLargeTicks.SetActive(true); } break; case 2: // Datareader if (hwversion <= HardwareInventory.a.hardwareVersion[2]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[2] = true; HardwareInventory.a.hardwareVersion[2] = hwversion; Const.sprint(Const.a.useableItemsNameText[23] + " v" + hwversion.ToString(),player); hardwareButtons[5].SetActive(true); // Enable HUD button break; case 3: // Sensaround if (hwversion <= HardwareInventory.a.hardwareVersion[3]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[3] = true; HardwareInventory.a.hardwareVersion[3] = hwversion; Const.sprint(Const.a.useableItemsNameText[24] + " v" + hwversion.ToString(),player); hardwareButtons[1].SetActive(true); // Enable HUD button break; case 4: // Target Identifier if (hwversion <= HardwareInventory.a.hardwareVersion[4]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[4] = true; HardwareInventory.a.hardwareVersion[4] = hwversion; Const.sprint(Const.a.useableItemsNameText[25] + " v" + hwversion.ToString(),player); break; case 5: // Energy Shield if (hwversion <= HardwareInventory.a.hardwareVersion[5]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[5] = true; HardwareInventory.a.hardwareVersion[5] = hwversion; Const.sprint(Const.a.useableItemsNameText[26] + " v" + hwversion.ToString(),player); hardwareButtons[3].SetActive(true); // Enable HUD button break; case 6: // Biomonitor if (hwversion <= HardwareInventory.a.hardwareVersion[6]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[6] = true; HardwareInventory.a.hardwareVersion[6] = hwversion; Const.sprint(Const.a.useableItemsNameText[27] + " v" + hwversion.ToString(),player); hardwareButtons[0].SetActive(true); // Enable HUD button break; case 7: // Head Mounted Lantern if (hwversion <= HardwareInventory.a.hardwareVersion[7]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[7] = true; HardwareInventory.a.hardwareVersion[7] = hwversion; Const.sprint(Const.a.useableItemsNameText[28] + " v" + hwversion.ToString(),player); hardwareButtons[2].SetActive(true); // Enable HUD button break; case 8: // Envirosuit if (hwversion <= HardwareInventory.a.hardwareVersion[8]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[8] = true; HardwareInventory.a.hardwareVersion[8] = hwversion; Const.sprint(Const.a.useableItemsNameText[29] + " v" + hwversion.ToString(),player); break; case 9: // Turbo Motion Booster if (hwversion <= HardwareInventory.a.hardwareVersion[9]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[9] = true; HardwareInventory.a.hardwareVersion[9] = hwversion; Const.sprint(Const.a.useableItemsNameText[30] + " v" + hwversion.ToString(),player); hardwareButtons[6].SetActive(true); // Enable HUD button break; case 10: // Jump Jet Boots if (hwversion <= HardwareInventory.a.hardwareVersion[10]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[10] = true; HardwareInventory.a.hardwareVersion[10] = hwversion; Const.sprint(Const.a.useableItemsNameText[31] + " v" + hwversion.ToString(),player); hardwareButtons[7].SetActive(true); // Enable HUD button break; case 11: // Infrared Night Vision Enhancement if (hwversion <= HardwareInventory.a.hardwareVersion[11]) { Const.sprint("THAT WARE IS OBSOLETE. DISCARDED.",player); return; } HardwareInventory.a.hasHardware[11] = true; HardwareInventory.a.hardwareVersion[11] = hwversion; Const.sprint(Const.a.useableItemsNameText[32] + " v" + hwversion.ToString(),player); hardwareButtons[4].SetActive(true); // Enable HUD button break; } if (firstTimePickup) { firstTimePickup = false; centerTabButtonsControl.TabButtonClickSilent (1); } HardwareInventory.a.hwButtonsManager.ActivateHardwareButton(index); mfdManager.SendInfoToItemTab(index); centerTabButtonsControl.NotifyToCenterTab(1); } void AddItemToInventory (int index) { AudioClip pickclip; pickclip = PickupSFX; switch (index) { case 0: AddGenericObjectToInventory(0); break; case 1: AddGenericObjectToInventory(1); break; case 2: AddGenericObjectToInventory(2); break; case 3: AddGenericObjectToInventory(3); break; case 4: AddGenericObjectToInventory(4); break; case 5: AddGenericObjectToInventory(5); break; case 6: AddAudioLogToInventory(); break; case 7: AddGrenadeToInventory(0); // Frag break; case 8: AddGrenadeToInventory(3); // Concussion break; case 9: AddGrenadeToInventory(1); // EMP break; case 10: AddGrenadeToInventory(6); // Earth Shaker break; case 11: AddGrenadeToInventory(4); // Land Mine break; case 12: AddGrenadeToInventory(5); // Nitropak break; case 13: AddGrenadeToInventory(2); // Gas break; case 14: AddPatchToInventory(2); break; case 15: AddPatchToInventory(6); break; case 16: AddPatchToInventory(5); break; case 17: AddPatchToInventory(3); break; case 18: AddPatchToInventory(4); break; case 19: AddPatchToInventory(1); break; case 20: AddPatchToInventory(0); break; case 21: AddHardwareToInventory(0); break; case 22: AddHardwareToInventory(1); break; case 23: AddHardwareToInventory(2); break; case 24: AddHardwareToInventory(3); break; case 25: AddHardwareToInventory(4); break; case 26: AddHardwareToInventory(5); break; case 27: AddHardwareToInventory(6); break; case 28: AddHardwareToInventory(7); break; case 29: AddHardwareToInventory(8); break; case 30: AddHardwareToInventory(9); break; case 31: AddHardwareToInventory(10); break; case 32: AddHardwareToInventory(11); break; case 33: AddGenericObjectToInventory(33); break; case 34: AddGenericObjectToInventory(34); break; case 35: AddGenericObjectToInventory(35); break; case 36: AddWeaponToInventory(36); break; case 37: AddWeaponToInventory(37); break; case 38: AddWeaponToInventory(38); break; case 39: AddWeaponToInventory(39); break; case 40: AddWeaponToInventory(40); break; case 41: AddWeaponToInventory(41); break; case 42: AddWeaponToInventory(42); break; case 43: AddWeaponToInventory(43); break; case 44: AddWeaponToInventory(44); break; case 45: AddWeaponToInventory(45); break; case 46: AddWeaponToInventory(46); break; case 47: AddWeaponToInventory(47); break; case 48: AddWeaponToInventory(48); break; case 49: AddWeaponToInventory(49); break; case 50: AddWeaponToInventory(50); break; case 51: AddWeaponToInventory(51); break; case 52: AddGenericObjectToInventory(52); break; case 53: AddGenericObjectToInventory(53); break; case 54: AddGenericObjectToInventory(54); break; case 55: AddGenericObjectToInventory(55); break; case 56: AddGenericObjectToInventory(56); break; case 57: AddGenericObjectToInventory(57); break; case 58: AddGenericObjectToInventory(58); break; case 61: AddGenericObjectToInventory(61); break; case 62: AddGenericObjectToInventory(62); break; case 63: AddGenericObjectToInventory(63); break; case 64: AddGenericObjectToInventory(64); break; case 65: AddAmmoToInventory(8, Const.a.magazinePitchCountForWeapon2[8], true); // magpulse cartridge super break; case 66: AddAmmoToInventory(2, Const.a.magazinePitchCountForWeapon[2], false); // needle darts break; case 67: AddAmmoToInventory(2, Const.a.magazinePitchCountForWeapon2[2], true); // tranquilizer darts break; case 68: AddAmmoToInventory(9, Const.a.magazinePitchCountForWeapon[9], false); // standard bullets break; case 69: AddAmmoToInventory(9, Const.a.magazinePitchCountForWeapon2[9], true); // teflon bullets break; case 70: AddAmmoToInventory(7, Const.a.magazinePitchCountForWeapon[7], false); // hollow point rounds break; case 71: AddAmmoToInventory(7, Const.a.magazinePitchCountForWeapon2[7], true); // slug rounds break; case 72: AddAmmoToInventory(0, Const.a.magazinePitchCountForWeapon[0], false); // magnesium tipped slugs break; case 73: AddAmmoToInventory(0, Const.a.magazinePitchCountForWeapon2[0], true); // penetrator slugs break; case 74: AddAmmoToInventory(3, Const.a.magazinePitchCountForWeapon[3], false); // hornet clip break; case 75: AddAmmoToInventory(3, Const.a.magazinePitchCountForWeapon2[3], true); // splinter clip break; case 76: AddAmmoToInventory(11, Const.a.magazinePitchCountForWeapon[11], false); // rail rounds break; case 77: AddAmmoToInventory(13, Const.a.magazinePitchCountForWeapon[13], false); // slag magazine break; case 78: AddAmmoToInventory(13, Const.a.magazinePitchCountForWeapon2[13], true); // large slag magazine break; case 79: AddAmmoToInventory(8, Const.a.magazinePitchCountForWeapon[8], false); // magpulse cartridges break; case 80: AddAmmoToInventory(8, Const.a.magazinePitchCountForWeapon2[8], false); // small magpulse cartridges break; case 81: AddAccessCardToInventory(81); break; case 82: AddAccessCardToInventory(82); break; case 83: AddAccessCardToInventory(83); break; case 84: AddAccessCardToInventory(84); break; case 85: AddAccessCardToInventory(85); break; case 86: AddAccessCardToInventory(86); break; case 87: AddAccessCardToInventory(87); break; case 88: AddAccessCardToInventory(88); break; case 89: AddAccessCardToInventory(89); break; case 90: AddAccessCardToInventory(90); break; case 91: AddAccessCardToInventory(91); break; case 113: AddAmmoToInventory(12, Const.a.magazinePitchCountForWeapon[12], false); // rubber slugs break; } SFXSource.PlayOneShot(pickclip); firstTimePickup = false; } void DropHeldItem() { heldObject = Const.a.useableItems[heldObjectIndex]; if (heldObject != null) { GameObject tossObject = null; bool freeObjectInPoolFound = false; GameObject levelDynamicContainer = LevelManager.a.GetCurrentLevelDynamicContainer(); if (levelDynamicContainer == null) { Const.sprint("BUG: Failed to find dynamicObjectContainer for level: " + LevelManager.a.currentLevel.ToString(),player); return; } for (int i=0;i<levelDynamicContainer.transform.childCount;i++) { Transform tr = levelDynamicContainer.transform.GetChild(i); GameObject go = tr.gameObject; UseableObjectUse reference = go.GetComponent<UseableObjectUse>(); if (reference != null) { if (reference.useableItemIndex == heldObjectIndex && go.activeSelf == false) { reference.customIndex = heldObjectCustomIndex; tossObject = go; freeObjectInPoolFound = true; break; } } } if (freeObjectInPoolFound) { tossObject.transform.position = (transform.position + (transform.forward * tossOffset)); } else { tossObject = Instantiate(heldObject,(transform.position + (transform.forward * tossOffset)),Quaternion.identity) as GameObject; //effect if (tossObject == null) { Const.sprint("BUG: Failed to instantiate object being dropped!",player); return; } } if (tossObject.activeSelf != true) { tossObject.SetActive(true); } tossObject.transform.SetParent(levelDynamicContainer.transform,true); tossObject.GetComponent<Rigidbody>().velocity = transform.forward * tossForce; tossObject.GetComponent<UseableObjectUse>().customIndex = heldObjectCustomIndex; tossObject.GetComponent<UseableObjectUse>().ammo = heldObjectAmmo; if (grenadeActive) { grenadeActive = false; GrenadeActivate ga = tossObject.GetComponent<GrenadeActivate>(); if (ga != null) { ga.Activate(grenadeCurrent); // time to boom } mouseCursor.liveGrenade = false; } } else { Const.sprint("Warning: Object "+heldObjectIndex.ToString()+" not assigned, vaporized.",player); } } void ResetHeldItem() { //yield return new WaitForSeconds(0.05f); heldObjectIndex = -1; heldObjectCustomIndex = -1; heldObjectAmmo = 0; heldObjectAmmoIsSecondary = false; holdingObject = false; mouseCursor.justDroppedItemInHelper = true; } void ResetCursor () { if (mouseCursor != null) { cursorTexture = cursorDefaultTexture; mouseCursor.cursorImage = cursorTexture; mouseCursor.liveGrenade = false; } else { Const.sprint("Warning: Could Not Find object 'MouseCursorHandler' in scene\n",Const.a.allPlayers); } } public void ToggleInventoryMode (){ if (inventoryMode) { ForceShootMode(); } else { ForceInventoryMode(); } } public void ForceShootMode() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; inventoryMode = false; } public void ForceInventoryMode() { Cursor.lockState = CursorLockMode.None; Cursor.visible = false; inventoryMode = true; } void SearchObject ( int index ){ SearchableItem curSearchScript = currentSearchItem.GetComponent<SearchableItem>(); curSearchScript.searchableInUse = true; curSearchScript.currentPlayerCapsule = transform.parent.gameObject; // Get playerCapsule of player this is attached to // Fill container with random items, overrides manually entered data if (curSearchScript.generateContents) { if (curSearchScript.lookUpIndex >= 0) { // Refer to lookUp tables // TODO: create lookUp tables for generic randomized search items such as NPCs } else { // Use random items chosen for (int movingIndex=0;movingIndex<curSearchScript.numSlots;movingIndex++) { if (Random.Range(0f,1f) < 0.5f) { curSearchScript.contents[movingIndex] = curSearchScript.randomItem[movingIndex]; curSearchScript.customIndex[movingIndex] = curSearchScript.randomItemCustomIndex[movingIndex]; movingIndex++; } else { curSearchScript.contents[movingIndex] = -1; curSearchScript.customIndex[movingIndex] = -1; movingIndex++; } } } } // Play search sound SFXSource.PlayOneShot(SearchSFX); // Search through array to see if any items are in the container int numberFoundContents = 0; int[] resultContents = {-1,-1,-1,-1}; // create blanked container for search results int[] resultCustomIndex = {-1,-1,-1,-1}; // create blanked container for search results custom indices for (int i=curSearchScript.numSlots - 1;i>=0;i--) { //Const.sprint("Search index = " + i.ToString() + ", and SearchableItem.customIndex.Length = " + currentSearchItem.GetComponent<SearchableItem>().customIndex.Length.ToString()); resultContents[i] = curSearchScript.contents[i]; resultCustomIndex[i] = curSearchScript.customIndex[i]; if (resultContents[i] > -1) { numberFoundContents++; // if something was found, add 1 to count } } if (firstTimeSearch) { firstTimeSearch = false; mfdManager.OpenTab (4, true, MFDManager.TabMSG.Search, -1,MFDManager.handedness.LeftHand); } MFDManager.a.SendSearchToDataTab(curSearchScript.objectName, numberFoundContents, resultContents, resultCustomIndex); ForceInventoryMode(); } // Returns string for describing the walls/floors/etc. based on the material name string GetTextureDescription (string material_name){ string retval = System.String.Empty; // temporary string to hold the return value if (material_name.StartsWith("+")) retval = "normal screens"; if (material_name.Contains("fan")) retval = "field generation rotor"; // handle wierd case of animated texture having same name as plain one, oops. if ((material_name.StartsWith("+")) &&(material_name.Contains("eng2_5"))) { retval = "power exchanger"; return retval; } if (material_name.Contains("lift")) retval = "repulsor lift"; if (material_name.Contains("alert")) retval = "warning indicator"; if (material_name.Contains("telepad")) retval = "jump disk"; if (material_name.Contains("crate")) retval = "storage crate"; switch(material_name) { case "bridg1_2": retval = "biological infestation"; break; case "bridg1_3": retval = "biological infestation"; break; case "bridg1_3b": retval = "biological infestation"; break; case "bridg1_4": retval = "biological infestation"; break; case "bridg1_5": retval = "data transfer schematic"; break; case "bridg2_1": retval = "monitoring port"; break; case "bridg2_2": retval = "stone mosaic tiling"; break; case "bridg2_3": retval = "monitoring post"; break; case "bridg2_4": retval = "video observation screen"; break; case "bridg2_5": retval = "cyber station"; break; case "bridg2_6": retval = "burnished platinum panelling"; break; case "bridg2_7": retval = "burnished platinum panelling"; break; case "bridg2_8": retval = "SHODAN neural bud"; break; case "bridg2_9": retval = "computer"; break; case "cabinet": retval = "cabinet"; break; case "charge_stat": retval = "energy charge station"; break; case "citmat1_1": retval = "CPU node"; break; case "citmat1_2": retval = "chair"; break; case "citmat1_3": retval = "catwalk"; break; case "citmat1_4": retval = "catwalk"; break; case "citmat1_5": retval = "surface"; break; case "citmat1_6": retval = "cabinet"; break; case "citmat1_7": retval = "catwalk"; break; case "citmat1_8": retval = "table top"; break; case "citmat1_9": retval = "catwalk"; break; case "citmat2_1": retval = "catwalk"; break; case "citmat2_2": retval = "cabinet"; break; case "citmat2_3": retval = "cabinet"; break; case "citmat2_4": retval = "cabinet"; break; case "console1_1": retval = "computer"; break; case "console1_2": retval = "computer"; break; case "console1_3": retval = "cart"; break; case "console1_4": retval = "computer"; break; case "console1_5": retval = "computer"; break; case "console1_6": retval = "console"; break; case "console1_7": retval = "console"; break; case "console1_8": retval = "console"; break; case "console1_9": retval = "console"; break; case "console2_1": retval = "console panel"; break; case "console2_2": retval = "desk"; break; case "console2_3": retval = "computer panel"; break; case "console2_4": retval = "computer panel"; break; case "console2_5": retval = "computer console"; break; case "console2_6": retval = "console controls"; break; case "console2_7": retval = "console"; break; case "console2_8": retval = "console controls"; break; case "console2_9": retval = "console"; break; case "console3_1": retval = "cyber space port"; break; case "console3_2": retval = "computer"; break; case "console3_3": retval = "computer"; break; case "console3_4": retval = "keyboard"; break; case "console3_5": retval = "computer panelling"; break; case "console3_6": retval = "normal screens"; break; case "console3_7": retval = "destroyed screen"; break; case "console3_8": retval = "desk"; break; case "console3_9": retval = "desk"; break; case "console4_1": retval = "console controls"; break; case "cyber": retval = "x-ray machine"; break; case "d_arrow1": retval = "repulsor lights"; break; case "d_arrow2": retval = "repulsor lights"; break; case "eng1_1": retval = "environmental regulator"; break; case "eng1_1d": retval = "atmospheric regulator"; break; case "eng1_2": retval = "fluid transport pipes"; break; case "eng1_2d": retval = "fluid transport pipes"; break; case "eng1_3": retval = "engineering panelling"; break; case "eng1_3d": retval = "fluid transport pipes"; break; case "eng1_4": retval = "ladder"; break; case "eng1_5": retval = "engineering panelling"; break; case "eng1_5d": retval = "panelling"; break; case "eng1_6": retval = "system function gauges"; break; case "eng1_6d": retval = "instruments"; break; case "eng1_7": retval = "engineering instruments"; break; case "eng1_7d": retval = "instruments"; break; case "eng1_8": retval = "electric cable access"; break; case "eng1_9": retval = "data circuit access port"; break; case "eng1_9d": retval = "data access ports"; break; case "eng2_1": retval = "hi-grip surface"; break; case "eng2_1d": retval = "hi-grip surface"; break; case "eng2_2": retval = "halogen light fixture"; break; case "eng2_2d": retval = "damaged light fixture"; break; case "eng2_3": retval = "observation station"; break; case "eng2_3d": retval = "instruments"; break; case "eng2_4": retval = "thick rug"; break; case "eng2_5": retval = "modular panelling"; break; case "exec1_1": retval = "soft panelling"; break; case "exec1_1d": retval = "burnt panelling"; break; case "exec1_2": retval = "tech-rack"; break; case "exec1_2d": retval = "tech-rack"; break; case "exec2_1": retval = "corridor wall"; break; case "exec2_2": retval = "corridor wall"; break; case "exec2_2d": retval = "corridor wall"; break; case "exec2_3": retval = "oak panelling"; break; case "exec2_4": retval = "titanium panelling"; break; case "exec2_5": retval = "molybdenum panelling"; break; case "exec2_6": retval = "molybdenum panelling"; break; case "exec2_7": retval = "light fixture"; break; case "exec3_1": retval = "corridor wall"; break; case "exec3_1d": retval = "corridor wall"; break; case "exec3_2": retval = "corridor wall"; break; case "exec3_4": retval = "carpet"; break; case "exec4_1": retval = "automatic teller machine"; break; case "exec4_2": retval = "elevator panelling"; break; case "exec4_3": retval = "elevator panelling"; break; case "exec4_4": retval = "duct"; break; case "exec4_5": retval = "carpet"; break; case "exec4_6": retval = "marble slab"; break; case "exec6_1": retval = "display screen"; break; case "flight1_1": retval = "energ-light"; break; case "flight1_1b": retval = "energ-light"; break; case "flight1_2": retval = "non-dent steel panelling"; break; case "flight1_3": retval = "non-dent steel panelling"; break; case "flight1_4": retval = "non-dent steel panelling"; break; case "flight1_5": retval = "non-dent steel panelling"; break; case "flight1_6": retval = "environmental regulator"; break; case "flight2_1": retval = "grip surface"; break; case "flight2_2": retval = "energ-light"; break; case "flight2_3": retval = "energ-light"; break; case "grate1_1": retval = "grating"; break; case "grate1_2": retval = "grating"; break; case "grate1_3": retval = "grating"; break; case "grove1_1": retval = "observation ceiling"; break; case "grove1_2": retval = "grass"; break; case "grove1_3": retval = "grass"; break; case "grove1_4": retval = "wet grass"; break; case "grove1_5": retval = "virus infestation"; break; case "grove1_6": retval = "virus infestation"; break; case "grove1_7": retval = "virus infestation"; break; case "grove2_1": retval = "environment pod wall"; break; case "grove2_2": retval = "overgrowth"; break; case "grove2_3": retval = "environment pod wall"; break; case "grove2_4": retval = "overgrown panel"; break; case "grove2_5": retval = "environment regulator"; break; case "grove2_6": retval = "overgrowth"; break; case "grove2_7": retval = "sprinkler system"; break; case "grove2_8": retval = "overgrowth"; break; case "grove2_9": retval = "virus infestation"; break; case "grove2_9b": retval = "virus infestation"; break; case "grove2_9c": retval = "virus infestation"; break; case "maint1_1": retval = "industrial tiles"; break; case "maint1_2": retval = "storage area"; break; case "maint1_2d": retval = "storage area"; break; case "maint1_3": retval = "chemical storage"; break; case "maint1_3b": retval = "chemical dispensory"; break; case "maint1_4": retval = "repair station"; break; case "maint1_4b": retval = "repair station"; break; case "maint1_5": retval = "chemical dispensory"; break; case "maint1_6": retval = "robot diagnostic system"; break; case "maint1_7": retval = "repair station"; break; case "maint1_9": retval = "industrial tiles"; break; case "maint1_9d": retval = "industrial tiles"; break; case "maint2_1": retval = "quartz light fixture"; break; case "maint2_1b": retval = "ladder"; break; case "maint2_1d": retval = "quartz light fixture"; break; case "maint2_2": retval = "incandescent light"; break; case "maint2_3": retval = "grating"; break; case "maint2_3d": retval = "access station"; break; case "maint2_4": retval = "access station"; break; case "maint2_5": retval = "access station"; break; case "maint2_5d": retval = "fluid transport pipes"; break; case "maint2_6": retval = "fluid transport pipes"; break; case "maint2_6d": retval = "access station"; break; case "maint2_7": retval = "access station"; break; case "maint2_7d": retval = "fluid transport pipes"; break; case "maint2_8": retval = "fluid transport pipes"; break; case "maint2_9": retval = "power conduits"; break; case "maint3_1": retval = "duralloy panelling"; break; case "maint3_1d": retval = "duralloy panelling"; break; case "maint24_d": retval = "access station"; break; case "med1_1": retval = "soft panelling"; break; case "med1_1d": retval = "soft panelling"; break; case "med1_2": retval = "comm port"; break; case "med1_2d": retval = "comm port"; break; case "med1_3": retval = "environmental regulator"; break; case "med1_3d": retval = "environmental regulator"; break; case "med1_4": retval = "sof-impac panelling"; break; case "med1_5": retval = "flourescent light"; break; case "med1_6": retval = "flourescent light"; break; case "med1_7": retval = "tile panelling"; break; case "med1_7d": retval = "tile panelling"; break; case "med1_8": retval = "flourescent lighting"; break; case "med1_8d": retval = "flourescent lighting"; break; case "med1_9": retval = "flourescent lighting"; break; case "med1_9d": retval = "rubberized panelling"; break; case "med2_1": retval = "medical diagnostic tools"; break; case "med2_1d": retval = "clinical panelling"; break; case "med2_2": retval = "clinical panelling"; break; case "med2_2d": retval = "clinical panelling"; break; case "med2_3": retval = "clinical panelling"; break; case "med2_3d": retval = "clinical panelling"; break; case "med2_4": retval = "medical computer"; break; case "med2_5": retval = "healing incubator"; break; case "med2_6": retval = "clinical panelling"; break; case "med2_7": retval = "restoration bay"; break; case "med2_8": retval = "clinical panelling"; break; case "med2_9": retval = "environmental regulator"; break; case "med2_9d": retval = "environmental regulator"; break; case "med3_1": retval = "flood light"; break; case "rad1_1": retval = "cracked radiation tile"; break; case "rad1_2": retval = "cracked radiation tile"; break; case "reac1_1": retval = "molybdenum panelling"; break; case "reac1_2": retval = "power coupling"; break; case "reac1_3": retval = "halogen lighting"; break; case "reac1_4": retval = "circuit relay"; break; case "reac1_5": retval = "relay access port"; break; case "reac1_6": retval = "power monitor"; break; case "reac1_7": retval = "data transfer array"; break; case "reac1_8": retval = "diagnostic module"; break; case "reac1_9": retval = "comm panel"; break; case "reac2_1": retval = "energy conduits"; break; case "reac2_1b": retval = "energy conduits"; break; case "reac2_2": retval = "energy conduits"; break; case "reac2_4": retval = "energy conduits"; break; case "reac2_5": retval = "equipment storage"; break; case "reac2_6": retval = "energy conduits"; break; case "reac2_7": retval = "energy monitoring station"; break; case "reac2_8": retval = "rad observation console"; break; case "reac2_9": retval = "high energy transformer"; break; case "reac3_1": retval = "molybdenum panelling"; break; case "reac3_2": retval = "molybdenum panelling"; break; case "reac3_3": retval = "cable access port"; break; case "reac3_4": retval = "duct"; break; case "reac3_5": retval = "molybdenum panelling"; break; case "reac3_6": retval = "molybdenum panelling"; break; case "reac3_7": retval = "relay network"; break; case "reac4_1": retval = "sensor grid"; break; case "reac4_2": retval = "halogen lamp"; break; case "reac5_1": retval = "magnetic containment system"; break; case "reac5_2": retval = "magnetic containment system"; break; case "reac5_3": retval = "magnetic containment system"; break; case "reac6_1": retval = "hi-grip surface"; break; case "reac6_2": retval = "quartz light fixture"; break; case "reac6_3": retval = "duct"; break; case "sci1_1": retval = "aluminum panelling"; break; case "sci1_1d": retval = "aluminum panelling"; break; case "sci1_2": retval = "aluminum panelling"; break; case "sci1_2d": retval = "damaged panelling"; break; case "sci1_3": retval = "matter converter"; break; case "sci1_4": retval = "matter converter"; break; case "sci1_5": retval = "aluminum panelling"; break; case "sci1_6": retval = "aluminum panelling"; break; case "sci1_7": retval = "environmental regulator"; break; case "sci1_7d": retval = "instruments"; break; case "sci1_8": retval = "molecular analyzer"; break; case "sci1_8d": retval = "instrument panel"; break; case "sci1_9": retval = "flourescent lighting"; break; case "sci1_9d": retval = "flourescent lighting"; break; case "sci2_1": retval = "duct"; break; case "sci2_1d": retval = "duct"; break; case "sci2_2": retval = "environmental regulator"; break; case "sci2_2d": retval = "damaged regulator"; break; case "sci2_3": retval = "aluminum panelling"; break; case "sci2_4": retval = "aluminum panelling"; break; case "sci2_5": retval = "high-power light"; break; case "sci2_5d": retval = "high-power light"; break; case "sci3_1": retval = "diagnostic panel"; break; case "sci3_1d": retval = "instrument panel"; break; case "sci3_2": retval = "composite panelling"; break; case "sci3_3": retval = "diagnostic panel"; break; case "sci3_4": retval = "data conduit"; break; case "sci3_5": retval = "atmospheric regulator"; break; case "sci3_6": retval = "comm port"; break; case "sec1_1": retval = "trioptimum logo"; break; case "sec1_1b": retval = "trioptimum logo"; break; case "sec1_1c": retval = "obsidian slab"; break; case "sec1_2": retval = "silver panelling"; break; case "sec1_2b": retval = "silver panelling"; break; case "sec1_3": retval = "light fixture"; break; case "stor1_1": retval = "no-scrape storeroom wall"; break; case "stor1_2": retval = "no-scrape storeroom wall"; break; case "stor1_3": retval = "no-scrape storeroom wall"; break; case "stor1_4": retval = "no-scrape storeroom wall"; break; case "stor1_5": retval = "no-scrape storeroom wall"; break; case "stor1_6": retval = "structural pillar"; break; case "stor1_7": retval = "industrial tiles"; break; case "stor1_7d": retval = "industrial tiles"; break; default: retval = System.String.Empty; break; } return retval; } static Mesh GetMesh(GameObject go) { if (go) { MeshFilter mf = go.GetComponent<MeshFilter>(); if (mf) { Mesh m = mf.sharedMesh; if (!m) m = mf.mesh; if (m) return m; } } return (Mesh)null; } public void UseGrenade (int index) { if (heldObject) return; ForceInventoryMode(); // inventory mode is turned on when picking something up ResetHeldItem(); holdingObject = true; heldObjectIndex = index; mouseCursor.cursorImage = Const.a.useableItemsFrobIcons[index]; mouseCursor.liveGrenade = true; grenadeActive = true; } void drawMyLine(Vector3 start , Vector3 end, Color color,float duration = 0.2f){ StartCoroutine( drawLine(start, end, color, duration)); } IEnumerator drawLine(Vector3 start , Vector3 end, Color color,float duration = 0.2f){ GameObject myLine = new GameObject (); myLine.transform.position = start; myLine.AddComponent<LineRenderer> (); LineRenderer lr = myLine.GetComponent<LineRenderer> (); lr.material = new Material (Shader.Find ("Legacy Shaders/Particles/Additive")); lr.startColor = color; lr.endColor = color; lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.SetPosition (0, start); lr.SetPosition (1, end); yield return new WaitForSeconds(duration); GameObject.Destroy (myLine); } }<file_sep>/Assets/Scripts/CenterTabButtons.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class CenterTabButtons : MonoBehaviour { [SerializeField] private CenterMFDTabs TabManager = null; // assign in the editor [SerializeField] private Button MainTabButton = null; // assign in the editor [SerializeField] private Button HardwareTabButton = null; // assign in the editor [SerializeField] private Button GeneralTabButton = null; // assign in the editor [SerializeField] private Button SoftwareTabButton = null; // assign in the editor [SerializeField] private Sprite MFDSprite = null; // assign in the editor [SerializeField] private Sprite MFDSpriteSelected = null; // assign in the editor [SerializeField] private Sprite MFDSpriteNotification = null; // assign in the editor [SerializeField] private AudioSource TabSFX = null; // assign in the editor [SerializeField] private AudioClip TabSFXClip = null; // assign in the editor [SerializeField] private int curTab = 0; [SerializeField] private float tickTime = 0.5f; [SerializeField] private int numTicks = 14; private bool[] tabNotified; private float tickFinished; private bool[] highlightStatus; private int[] highlightTickCount; void Awake () { tabNotified = new bool[] {false, false, false, false}; tickFinished = Time.time; tabNotified = new bool[] {false, false, false, false}; highlightStatus = new bool[] {false, false, false, false}; highlightTickCount = new int[] {0,0,0,0}; } void Update () { if (tickFinished < Time.time) { for (int i=0;i<4;i++) { if (tabNotified[i]) { ToggleHighlightOnButton(i); } } tickFinished = Time.time + tickTime; } } void ToggleHighlightOnButton (int buttonIndex) { Image buttonImage = null; switch (buttonIndex) { case 0: buttonImage = MainTabButton.image; break; case 1: buttonImage = HardwareTabButton.image; break; case 2: buttonImage = GeneralTabButton.image; break; case 3: buttonImage = SoftwareTabButton.image; break; } if (buttonImage == null) return; if (highlightStatus[buttonIndex]) { buttonImage.overrideSprite = MFDSpriteNotification; } else { if (curTab == buttonIndex) { buttonImage.overrideSprite = MFDSpriteSelected; } else { buttonImage.overrideSprite = MFDSprite; } } highlightTickCount[buttonIndex]++; highlightStatus[buttonIndex] = (!highlightStatus[buttonIndex]); if (highlightTickCount[buttonIndex] >= numTicks) { highlightStatus[buttonIndex] = false; highlightTickCount[buttonIndex] = 0; tabNotified[buttonIndex] = false; // stop blinking if (curTab == buttonIndex) { buttonImage.overrideSprite = MFDSpriteSelected; // If we are on this tab, return to selected } else { buttonImage.overrideSprite = MFDSprite; // Return to normal } } } public void NotifyToCenterTab(int tabNum) { //if (curTab == tabNum) return; tabNotified[tabNum] = true; tickFinished = Time.time + tickTime; ToggleHighlightOnButton (tabNum); } public void TabButtonClick (int tabNum) { TabSFX.PlayOneShot(TabSFXClip); TabButtonClickSilent(tabNum); } public void TabButtonClickSilent (int tabNum) { bool wasActive = false; switch (tabNum) { case 0: wasActive = TabManager.MainTab.activeInHierarchy; TabManager.DisableAllTabs(); if (curTab == 0) { if (wasActive) { break; } else { TabManager.MainTab.SetActive(true); break; } } MainTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.DisableAllTabs(); TabManager.MainTab.SetActive(true); HardwareTabButton.image.overrideSprite = MFDSprite; GeneralTabButton.image.overrideSprite = MFDSprite; SoftwareTabButton.image.overrideSprite = MFDSprite; curTab = 0; break; case 1: wasActive = TabManager.HardwareTab.activeInHierarchy; TabManager.DisableAllTabs(); if (curTab == 1) { if (wasActive) { break; } else { TabManager.HardwareTab.SetActive(true); break; } } HardwareTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.DisableAllTabs(); TabManager.HardwareTab.SetActive(true); MainTabButton.image.overrideSprite = MFDSprite; GeneralTabButton.image.overrideSprite = MFDSprite; SoftwareTabButton.image.overrideSprite = MFDSprite; curTab = 1; break; case 2: wasActive = TabManager.GeneralTab.activeInHierarchy; TabManager.DisableAllTabs(); if (curTab == 2) { if (wasActive) { break; } else { TabManager.GeneralTab.SetActive(true); break; } } GeneralTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.DisableAllTabs(); TabManager.GeneralTab.SetActive(true); MainTabButton.image.overrideSprite = MFDSprite; HardwareTabButton.image.overrideSprite = MFDSprite; SoftwareTabButton.image.overrideSprite = MFDSprite; curTab = 2; break; case 3: wasActive = TabManager.SoftwareTab.activeInHierarchy; TabManager.DisableAllTabs(); if (curTab == 3) { if (wasActive) { break; } else { TabManager.SoftwareTab.SetActive(true); break; } } SoftwareTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.DisableAllTabs(); TabManager.SoftwareTab.SetActive(true); MainTabButton.image.overrideSprite = MFDSprite; HardwareTabButton.image.overrideSprite = MFDSprite; GeneralTabButton.image.overrideSprite = MFDSprite; curTab = 3; break; case 4: TabManager.DisableAllTabs(); TabManager.DataReaderContentTab.SetActive(true); TabManager.DataReaderContentTab.GetComponent<MultiMediaTabManager>().OpenLogTableContents(); MainTabButton.image.overrideSprite = MFDSprite; HardwareTabButton.image.overrideSprite = MFDSprite; GeneralTabButton.image.overrideSprite = MFDSprite; SoftwareTabButton.image.overrideSprite = MFDSprite; curTab = 4; break; } } } <file_sep>/Assets/Scripts/Door.cs using UnityEngine; using System.Collections; public class Door : MonoBehaviour { [Tooltip("Delay after full open before door closes")] public float delay; [Tooltip("Whether door is locked, unuseable until unlocked")] public bool locked; [Tooltip("If yes, door never closes automatically")] public bool stayOpen; [Tooltip("Should door start open (you should set stayOpen too!)")] public bool startOpen; [Tooltip("Should door start partially open")] public bool ajar = false; [Tooltip("If partially open, by what percentage")] public float ajarPercentage = 0.5f; [Tooltip("Delay after use before door can be re-used")] public float useTimeDelay = 0.15f; [Tooltip("Message to display when door is locked, e.g.'door is broken beyond repair'")] public string lockedMessage = "Door is locked"; [Tooltip("Message to display when door requires a keycard, e.g.'Standard Access card required'")] public string cardMessage = "access card required"; [Tooltip("Message to display when door is opened using a keycard, e.g.'Standard Access card used'")] public string cardUsedMessage = "STD access granted"; public string butdoorStillLockedMessage = " but door is locked."; [HideInInspector] public bool blocked = false; private float useFinished; float waitBeforeClose; private Animator anim; private AudioSource SFX = null; // assign in the editor [Tooltip("Door sound when opening or closing")] public AudioClip SFXClip = null; // assign in the editor public enum doorState {Closed, Open, Closing, Opening}; public enum accessCardType {None,Standard,Medical,Science,Admin,Group1,Group2,Group3,Group4,GroupA,GroupB,Storage,Engineering,Maintenance,Security,Per1,Per2,Per3,Per4,Per5}; public accessCardType requiredAccessCard = accessCardType.None; public doorState doorOpen; public float timeBeforeLasersOn; public float lasersFinished; public GameObject[] laserLines; public bool toggleLasers = false; public bool targettingOnlyUnlocks = false; public bool debugging = false; private int defIndex = 0; private float topTime = 1.00f; private float defaultSpeed = 1.00f; private float speedZero = 0.00f; private string idleOpenClipName = "IdleOpen"; private string idleClosedClipName = "IdleClosed"; private string openClipName = "DoorOpen"; private string closeClipName = "DoorClose"; private GameObject dynamicObjectsContainer; private int i = 0; void Start () { anim = GetComponent<Animator>(); if (startOpen) { doorOpen = doorState.Open; anim.Play(idleOpenClipName); } else { doorOpen = doorState.Closed; anim.Play(idleClosedClipName); } SFX = GetComponent<AudioSource>(); useFinished = Time.time; } public void Use (UseData ud) { ajar = false; if (useFinished < Time.time) { if (requiredAccessCard == accessCardType.None || ud.owner.GetComponent<PlayerReferenceManager>().playerInventory.GetComponent<AccessCardInventory>().HasAccessCard(requiredAccessCard)) { useFinished = Time.time + useTimeDelay; AnimatorStateInfo asi = anim.GetCurrentAnimatorStateInfo(defIndex); float playbackTime = asi.normalizedTime; //AnimatorClipInfo[] aci = anim.GetCurrentAnimatorClipInfo(defIndex); if (!locked) { if (requiredAccessCard != accessCardType.None) { Const.sprint(requiredAccessCard.ToString() + cardUsedMessage,ud.owner); // tell the owner of the Use command that we are locked } if (doorOpen == doorState.Open && playbackTime > 0.95f) { //Debug.Log("Was Open, Now Closing"); doorOpen = doorState.Closing; CloseDoor(); return; } if (doorOpen == doorState.Closed && playbackTime > 0.95f){ //Debug.Log("Was Close, Now Opening"); doorOpen = doorState.Opening; OpenDoor(); return; } if (doorOpen == doorState.Opening) { doorOpen = doorState.Closing; anim.Play(closeClipName,defIndex, topTime-playbackTime); //Debug.Log("Reversing from Opening to Closing. playbackTime = " + playbackTime.ToString() + ", topTime-playbackTime = " + (topTime-playbackTime).ToString()); SFX.PlayOneShot(SFXClip); return; } if (doorOpen == doorState.Closing) { doorOpen = doorState.Opening; waitBeforeClose = Time.time + delay; anim.Play(openClipName,defIndex, topTime-playbackTime); //Debug.Log("Reversing from Closing to Opening. playbackTime = " + playbackTime.ToString() + ", topTime-playbackTime = " + (topTime-playbackTime).ToString()); SFX.PlayOneShot(SFXClip); return; } } else { if (requiredAccessCard != accessCardType.None) { Const.sprint (requiredAccessCard.ToString() + cardUsedMessage + butdoorStillLockedMessage,ud.owner); } else { Const.sprint(lockedMessage,ud.owner); // tell the owner of the Use command that we are locked } } } else { Const.sprint(requiredAccessCard.ToString() + cardMessage,ud.owner); // tell the owner of the Use command that we are locked } } } void Targetted (UseData ud) { if (locked) locked = false; if (!targettingOnlyUnlocks) Use(ud); } void OpenDoor() { anim.speed = defaultSpeed; doorOpen = doorState.Opening; waitBeforeClose = Time.time + delay; anim.Play(openClipName); SFX.PlayOneShot(SFXClip); //lightsFinished1 = Time.time + timeBeforeLightsOut1; if (toggleLasers) { for (int i=defIndex;i<laserLines.Length;i++) { laserLines[i].SetActive(false); } lasersFinished = Mathf.Infinity; } } void CloseDoor() { anim.speed = defaultSpeed; doorOpen = doorState.Closing; anim.Play(closeClipName); SFX.PlayOneShot(SFXClip); if (toggleLasers) { lasersFinished = Time.time + timeBeforeLasersOn; } dynamicObjectsContainer = LevelManager.a.GetCurrentLevelDynamicContainer(); if (dynamicObjectsContainer == null) return; //didn't find current level, go ahead and ghost through objects // horrible hack to keep objects that have their physics sleeping ghosting through the door as it closes for (i=defIndex;i<dynamicObjectsContainer.transform.childCount;i++) { if (Vector3.Distance(transform.position,dynamicObjectsContainer.transform.GetChild(i).transform.position) < 5) { Rigidbody changeThis = dynamicObjectsContainer.transform.GetChild(i).GetComponent<Rigidbody>(); if (changeThis != null) changeThis.WakeUp(); } } } void Update () { if (ajar) { doorOpen = doorState.Closing; anim.Play(openClipName,defIndex, ajarPercentage); anim.speed = speedZero; } if (blocked || (PauseScript.a != null && PauseScript.a.paused)) { Blocked(); } else { if (PauseScript.a != null && !PauseScript.a.paused) { Unblocked(); } } if (debugging) Debug.Log("doorOpen state = " + doorOpen.ToString()); AnimatorStateInfo asi = anim.GetCurrentAnimatorStateInfo(defIndex); float playbackTime = asi.normalizedTime; //if (anim.GetCurrentAnimatorStateInfo(defIndex).IsName(idleClosedClipName)) if (doorOpen == doorState.Closing && playbackTime > 0.95f) doorOpen = doorState.Closed; // Door is closed //if (anim.GetCurrentAnimatorStateInfo(defIndex).IsName(idleOpenClipName)) if (doorOpen == doorState.Opening && playbackTime > 0.95f) doorOpen = doorState.Open; // Door is open if (Time.time > waitBeforeClose) { if ((doorOpen == doorState.Open) && (!stayOpen)) CloseDoor(); } if (lasersFinished < Time.time) { for (int i=defIndex;i<laserLines.Length;i++) { laserLines[i].SetActive(true); } } } void Blocked () { anim.speed = speedZero; } void Unblocked () { anim.speed = defaultSpeed; } } <file_sep>/Assets/Scripts/NPC_Hopper_Death.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class NPC_Hopper_Death : MonoBehaviour { public int step; public float blendAmount1; public float blendAmount2; public int blendStep1; public int blendStep2; public float blendAmountPerTick; public float redBlendAmountPerTick; public float rimPowerShiftPerTick; public float blendShapeTickSecs; public float blendRimColorTickSecs; private float redTint; private float rimPower; private float tick2Finished; private float tickFinished; private SkinnedMeshRenderer smr; void Awake() { smr = GetComponent<SkinnedMeshRenderer>(); step = 0; redTint = 0f; rimPower = 255f; tick2Finished = Time.time + blendRimColorTickSecs; tickFinished = Time.time + blendShapeTickSecs; blendStep1 = -1; blendStep2 = 0; } void Update() { if (tick2Finished < Time.time) { rimPower = smr.material.GetColor("_RimColor").r; rimPower -= rimPowerShiftPerTick; if (rimPower < 0) rimPower = 0; smr.material.SetColor("_RimColor",new Color(rimPower,0,(rimPower*0.75f),0)); tick2Finished = Time.time + blendRimColorTickSecs; } if (tickFinished < Time.time && blendStep2 < 6) { blendAmount1 -= blendAmountPerTick; blendAmount2 += blendAmountPerTick; if (blendStep2 >= 3) { redTint -= redBlendAmountPerTick; } else { redTint += redBlendAmountPerTick; } if (blendAmount1 < 0) blendAmount1 = 0; if (blendStep1 >= 0 && blendStep1 < 5) smr.SetBlendShapeWeight(blendStep1,blendAmount1); if (blendStep2 >= 0 && blendStep2 < 5) smr.SetBlendShapeWeight(blendStep2,blendAmount2); if (blendStep2 < 5) { if (smr.GetBlendShapeWeight(blendStep2) >= 100) { blendStep1++; blendStep2++; blendAmount1 = 100; blendAmount2 = 0; } } else { blendStep2 = 6; smr.SetBlendShapeWeight(0,0); smr.SetBlendShapeWeight(1,0); smr.SetBlendShapeWeight(2,0); smr.SetBlendShapeWeight(3,0); smr.SetBlendShapeWeight(4,100); redTint = 0f; } if (redTint < 0) redTint = 0; //floor if (redTint > 10) redTint = 10; // ceil smr.material.SetColor("_HSVAAdjust",new Color(redTint,0,0,0)); tickFinished = Time.time + blendShapeTickSecs; } } } <file_sep>/Assets/Scripts/Unused/DataReaderTexts.cs using UnityEngine; using System.Collections; using System.Xml; using System.Xml.Serialization; public class Log { [XmlAttribute("name")] public string name; [XmlElement("LogContent")] public string LogContent; }<file_sep>/Assets/Scripts/UIPointerMask.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class UIPointerMask : MonoBehaviour { void Awake () { EventTrigger pointerTrigger = GetComponent<EventTrigger>(); if (pointerTrigger == null) { pointerTrigger = gameObject.AddComponent<EventTrigger>(); if (pointerTrigger == null) { Const.sprint("Warning: Could not create Event Trigger for UIPointerMask",Const.a.allPlayers); return; } } EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.PointerEnter; entry.callback.AddListener((eventData) => { PtrEnter(); } ); pointerTrigger.triggers.Add(entry); EventTrigger.Entry entry2 = new EventTrigger.Entry(); entry2.eventID = EventTriggerType.PointerExit; entry2.callback.AddListener((eventData) => { PtrExit(); } ); pointerTrigger.triggers.Add(entry2); } public void PtrEnter () { GUIState.a.isBlocking = true; } public void PtrExit () { GUIState.a.isBlocking = false; } } <file_sep>/Assets/Scripts/Addons/edgedetect2edges.py #Blender 2.7 Addon to take the active face and perform loop cuts #based on differences between pixels in its diffuse texture. #Cuts are made at the line made between pixels. E.g. a 2x2 texture #will be split down the center of the face provided the pixels at #1,0 & 1,1 are different enough from 0,0 and 0,1. #Pseudo-code: #UI #3D View->Sub-Panel on tool bar #->->Button["Edge Detecct To Edges for Active Face"] #->->Dropdown Menu["Mode",Distance Based,Luminosity Based] #->->Number Input box["Threshhold",1<n<256] #Code flow #get active object #get faces from mesh data #get active face #get texture for face #get UV coords for face #set scaleVariable to ratio of pixels to texels from UV coords based on # difference from width and height of face vs width and height of UV coords # e.g. UV fills entire texture = 1:1, e.g. UV fills 10% of texture = 10:1 #set rotationVariable of texture from UV #for each pixel in texture starting with upper left pixel_X + 1 with UV coords for active face # Check if pixel is different enough() from neighboring pixel x-1 # edge loop cut across entire face at rotationVariable at position between pixels from "left" edge of UV #for each pixel in texture starting with upper left pixel_y + 1 with UV coords for active face # check if pixel is different enough() from neighboring pixel y-1 # edge loop cut across entire face at rotationVariable at position between pixels from "top" edge of UV #Check if pixel is different enough(2d texel, 2d neighbor, threshhold) #->Mode Luminosity Based # Sum r,g, and b values of texel # Sum r,g, and b values of neighbor # return true if texel sum - neighbor sum is > threshhold # #->Mode Distance Based # get distance from texel to neighbor in color space (rgb tuple to rgb tuple) # return true if distance > threshhold bl_info = { "name": "Edge Detect 2 Edges", "author": "<NAME>", "version": (1, 0, 0), "blender": (2, 78, 0), "location": "View3D > Specials > EdgeDetect2Edges", "description": "Cuts active face based on texture edge detection", "warning": "", "category": "Mesh", } import bpy import bmesh import math from bpy.props import IntProperty def edgedetect2edges_main(context, thresh): ob = bpy.context.object if ob.mode == 'EDIT': bpy.ops.object.editmode_toggle() bpy.ops.object.editmode_toggle() p = ob.data.polygons mat = ob.data.materials[p[p.active].material_index] tex = mat.active_texture #img = bpy.data.textures.get() texWidth = tex.size[0] texHeight = tex.size[1] for x in range(2,texWidth): for y in range(2,texHeight): i = x*y t = tex.pixels[i] i_neighbor = (x-1)*y n = tex.pixels[i_neighbor] if isDifferenceEnough(t,n,thresh): make_cut_x(x,y) i_neighbor = x*(y-1) n = tex.pixels[i_neighbor] if isDifferenceEnough(t,n,thresh): make_cut_y(x,y) def isDifferenceEnough(texel, neighbor, thresh): diff = math.sqrt((texel_x - neighbor_x)^2 + (texel_y - neighbor_y)^2 + (texel_z - neighbor_z)^2) return diff > thresh def make_cut_x(x,y): #Slice it x-wise relative to UV coords rotationVariable bmesh.utils.face_split(f,pointA,pointB,coords=(),False,None) def make_cut_y(x,y) #Slice it y-wise relative to UV coords rotationVariable class EdgeDetect2Edges(bpy.types.Operator): bl_idname = 'mesh.edgedetecte2edges' bl_label = 'Edge Detect 2 Edges' bl_options = {'REGISTER', 'UNDO'} threshhold = IntProperty(name="Threshhold", default=100, min=1, max=256, soft_min=1, soft_max=256) @classmethod def poll(cls, context): obj = context.active_object return (obj and obj.type == 'MESH') def execute(self, context): edgedetect2edges_main(context, threshhold) return {'FINISHED'} def menu_func(self, context): self.layout.operator(EdgeDetect2Edges.bl_idname, text="EdgeDetect 2 Edges") def register(): bpy.utils.register_module(__name__) bpy.types.VIEW3D_MT_edit_mesh_specials.append(menu_func) bpy.types.VIEW3D_MT_edit_mesh_vertices.append(menu_func) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.VIEW3D_MT_edit_mesh_specials.remove(menu_func) bpy.types.VIEW3D_MT_edit_mesh_vertices.remove(menu_func) if __name__ == "__main__": register() <file_sep>/Assets/Scripts/GeneralInvButton.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class GeneralInvButton : MonoBehaviour { public int GeneralInvButtonIndex; public int useableItemIndex; public PlayerEnergy playerEnergy; public PlayerHealth playerHealth; public GeneralInventory playerGenInv; public MFDManager mfdManager; private bool reduce = false; void GeneralInvClick() { GeneralInvCurrent.GeneralInvInstance.generalInvCurrent = GeneralInvButtonIndex; //Set current mfdManager.SendInfoToItemTab(useableItemIndex); } public void DoubleClick() { reduce = false; if (useableItemIndex == 52 || useableItemIndex == 53 || useableItemIndex == 55) { switch (useableItemIndex) { case 52: playerEnergy.GiveEnergy(83f,0); reduce = true; break; case 53: playerEnergy.GiveEnergy(255f,0); reduce = true; break; case 55: playerHealth.hm.health = playerHealth.hm.maxhealth; reduce = true; break; } } else { mfdManager.SendInfoToItemTab(useableItemIndex); mfdManager.OpenTab(1, true, MFDManager.TabMSG.None, useableItemIndex, MFDManager.handedness.LeftHand); GeneralInvCurrent.GeneralInvInstance.generalInvCurrent = GeneralInvButtonIndex; //Set current } if (reduce) playerGenInv.generalInventoryIndexRef[GeneralInvButtonIndex] = -1; } void Start() { GetComponent<Button>().onClick.AddListener(() => { GeneralInvClick(); }); } void Update() { useableItemIndex = GeneralInventory.GeneralInventoryInstance.generalInventoryIndexRef[GeneralInvButtonIndex]; } } <file_sep>/Assets/Scripts/TextWarningsManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextWarningsManager : MonoBehaviour { public GameObject[] warningTextGObjects; private Text[] warningTexts; private bool[] initialized; private float[] finishedTime; public float[] warningLifeTimes; public int[] uniqueID; public float warningDefaultLifeTime = 2f; public enum warningTextColor {white,red,green,yellow}; public Color colwhite; public Color colred; public Color colgreen; public Color colyellow; void Awake () { warningTexts = new Text[warningTextGObjects.Length]; initialized = new bool[warningTextGObjects.Length]; finishedTime = new float[warningTextGObjects.Length]; uniqueID = new int[warningTextGObjects.Length]; for (int i=0;i<warningTextGObjects.Length;i++) { warningTexts[i] = warningTextGObjects[i].GetComponent<Text>(); if (warningTexts[i] != null) warningTexts[i].text = System.String.Empty; initialized[i] = false; finishedTime[i] = Time.time; uniqueID[i] = -1; } } public void SendWarning(string message, float lifetime, int forcedReference, warningTextColor col, int id) { int setIndex = (warningTextGObjects.Length - 1); for (int i=setIndex;i>=0;i--) { if (uniqueID[i] == id) { setIndex = i; break;} if (finishedTime[i] < Time.time) { setIndex = i; break;} } if (id == 322) forcedReference = 0; if (forcedReference >= 0) setIndex = forcedReference; warningTexts[setIndex].text = message; uniqueID[setIndex] = id; if (col == warningTextColor.green) warningTexts[setIndex].color = colgreen; if (col == warningTextColor.white) warningTexts[setIndex].color = colwhite; if (col == warningTextColor.red) warningTexts[setIndex].color = colred; if (col == warningTextColor.yellow) warningTexts[setIndex].color = colyellow; if (lifetime > -1) warningLifeTimes[setIndex] += lifetime; else warningLifeTimes[setIndex] += warningDefaultLifeTime; finishedTime[setIndex] = Time.time + warningLifeTimes[setIndex]; } void Update () { for (int i=0;i<warningTextGObjects.Length;i++) { if (warningTexts[i].text != "" || warningTexts[i].text != " ") { if (finishedTime[i] < Time.time) { warningTexts[i].text = System.String.Empty; warningTextGObjects[i].SetActive(false); continue; } warningTextGObjects[i].SetActive(true); } else { warningTextGObjects[i].SetActive(false); } } } } <file_sep>/Assets/Scripts/ElevatorKeypad.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ElevatorKeypad : MonoBehaviour { public GameObject[] buttons; public GameObject[] buttonHandlers; public bool[] buttonsEnabled; public bool[] buttonsDarkened; public string[] buttonText; public Sprite buttonNormal; public Sprite buttonDarkened; public Image[] buttonSprites; public Text[] buttonTextHolders; public Image currentFloorIndicator; public int currentFloor; public GameObject[] targetDestination; public Sprite[] indicatorSprites; [HideInInspector] public GameObject activeKeypad; void Update () { for (int i=0; i<8; i++) { if (buttonsEnabled[i]) { buttons[i].SetActive(true); buttonTextHolders[i].text = buttonText[i]; if (buttonsDarkened[i]) { buttonSprites[i].overrideSprite = buttonDarkened; buttonHandlers[i].GetComponent<ElevatorButton>().floorAccessible = false; } else { buttonSprites[i].overrideSprite = buttonNormal; buttonHandlers[i].GetComponent<ElevatorButton>().floorAccessible = true; buttonHandlers[i].GetComponent<ElevatorButton>().targetDestination = targetDestination[i]; } } else { buttons[i].SetActive(false); } } switch (currentFloor) { case 0: currentFloorIndicator.overrideSprite = indicatorSprites[0]; break; case 1: currentFloorIndicator.overrideSprite = indicatorSprites[1]; break; case 2: currentFloorIndicator.overrideSprite = indicatorSprites[2]; break; case 3: currentFloorIndicator.overrideSprite = indicatorSprites[3]; break; case 4: currentFloorIndicator.overrideSprite = indicatorSprites[4]; break; case 5: currentFloorIndicator.overrideSprite = indicatorSprites[5]; break; case 6: currentFloorIndicator.overrideSprite = indicatorSprites[6]; break; case 7: currentFloorIndicator.overrideSprite = indicatorSprites[7]; break; case 8: currentFloorIndicator.overrideSprite = indicatorSprites[8]; break; case 9: currentFloorIndicator.overrideSprite = indicatorSprites[9]; break; case 10: currentFloorIndicator.overrideSprite = indicatorSprites[10]; break; } } } <file_sep>/Assets/Scripts/SkyRotate.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkyRotate : MonoBehaviour { public float rotateSpeed = 0.1f; public float timeIncrement = 0.05f; private float nextThink; void Awake() { nextThink = Time.time + timeIncrement; } void Update () { if (nextThink < Time.time) { Vector3 rot = new Vector3(0,rotateSpeed,0); transform.Rotate(rot); } } } <file_sep>/Assets/Scripts/MenuArrowKeyControls.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MenuArrowKeyControls : MonoBehaviour { public int currentIndex; public GameObject[] menuItems; public GameObject[] menuSubItems; void Awake () { currentIndex = 0; } void Update () { if (Input.GetKeyUp(KeyCode.Return)) { //menuItems[currentIndex].SendMessage("Click",SendMessageOptions.DontRequireReceiver); if (menuItems[currentIndex].GetComponent<Button>() != null) { menuItems[currentIndex].GetComponent<Button>().onClick.Invoke(); } else { menuItems[currentIndex].SendMessage("ClickViaKeyboard",SendMessageOptions.DontRequireReceiver); } return; } if (Input.GetKeyUp(KeyCode.UpArrow)) { ShiftMenuItem(false); } if (Input.GetKeyUp(KeyCode.DownArrow)) { ShiftMenuItem(true); } } void ShiftMenuItem (bool isDownKey) { if (menuItems[currentIndex] != null) { menuItems[currentIndex].SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); menuItems[currentIndex].SendMessage("InputFieldCancelFocus",SendMessageOptions.DontRequireReceiver); } if (menuSubItems[currentIndex] != null) menuSubItems[currentIndex].SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); if (isDownKey) { currentIndex++; if (currentIndex >= menuItems.Length) currentIndex = 0; // Wrap around :) } else { currentIndex--; if (currentIndex < 0) currentIndex = (menuItems.Length - 1); // Wrap around :) } if (menuItems[currentIndex] != null) menuItems[currentIndex].SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); if (menuItems[currentIndex] != null) menuItems[currentIndex].SendMessage("InputFieldFocus",SendMessageOptions.DontRequireReceiver); if (menuSubItems[currentIndex] != null) menuSubItems[currentIndex].SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); } public void SetIndex(int index) { currentIndex = index; for (int i=0;i<menuItems.Length;i++) { menuItems[i].SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); menuItems[i].SendMessage("InputFieldCancelFocus",SendMessageOptions.DontRequireReceiver); } if (menuItems[currentIndex] != null) menuItems[currentIndex].SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); if (menuItems[currentIndex] != null) menuItems[currentIndex].SendMessage("InputFieldFocus",SendMessageOptions.DontRequireReceiver); if (menuSubItems[currentIndex] != null) menuSubItems[currentIndex].SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); } } <file_sep>/Assets/Scripts/ConfigurationMenuVideoApply.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ConfigurationMenuVideoApply : MonoBehaviour { public Dropdown resolutionPicker; public void OnApplyClick () { Screen.SetResolution(Screen.resolutions[resolutionPicker.value].width,Screen.resolutions[resolutionPicker.value].height,true); Screen.fullScreen = Const.a.GraphicsFullscreen; Const.a.GraphicsResWidth = Screen.resolutions[resolutionPicker.value].width; Const.a.GraphicsResHeight = Screen.resolutions[resolutionPicker.value].height; Const.a.WriteConfig(); } } <file_sep>/Assets/Scripts/AutomapPlayerIcon.cs using UnityEngine; using System.Collections; public class AutomapPlayerIcon : MonoBehaviour { public GameObject cameraObject; [HideInInspector] public MouseLookScript mlookScript; void Start (){ mlookScript = cameraObject.GetComponent<MouseLookScript>(); // Get the mouselookscript to reference rotation } void FixedUpdate (){ transform.rotation = Quaternion.Euler(0,0,(mlookScript.yRotation*(-1) + 180)); // Rotation adjusted for player view and direction vs UI space } }<file_sep>/Assets/Scripts/RightNeuroButtonScript.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class RightNeuroButtonsScript : MonoBehaviour { [SerializeField] private Button UnknownTabButton; // assign in the editor [SerializeField] private Button CompassTabButton; // assign in the editor [SerializeField] private Button DataReaderTabButton; // assign in the editor [SerializeField] private Button Unknown2TabButton; // assign in the editor [SerializeField] private Button Unknown3TabButton; // assign in the editor [SerializeField] private Sprite EmptyNeuroTabSprite; // assign in the editor [SerializeField] private AudioSource TabSFX; // assign in the editor [SerializeField] private AudioClip TabSFXClip; // assign in the editor #region For DataReader [SerializeField] private GameObject iconman; [SerializeField] private GameObject itemtextman; [SerializeField] private LeftMFDTabs LeftTabManager; // assign in the editor [SerializeField] private CenterMFDTabs CenterTabManager; // assign in the editor [SerializeField] private TabButtons LeftTabButtonsManager; // assign in the editor #endregion //private TabButtonsScript LeftMFDTabsScript = TabManager.GetComponent <TabButtonsScript> (); public bool CompassActivated = false; public bool DataReaderActivated = false; public void TabButtonClick (int tabNum) { TabSFX.PlayOneShot(TabSFXClip); switch (tabNum) { case 2: //Data Reader Debug.Log ("Data Reader Activated"); LeftTabButtonsManager.TabButtonClick (1); iconman.GetComponent<ItemIconManager>().SetItemIcon(0); //Set Data Reader icon for MFD itemtextman.GetComponent<ItemTextManager>().SetItemText(7); //Set Data Reader text for MFD DataReaderActivated = true; break; } } }<file_sep>/Assets/Scripts/BodyState.cs using UnityEngine; using System.Collections; public class BodyState : MonoBehaviour { public float floatAbove = 0.08f; public Transform playerCapsuleTransform; //[HideInInspector] public bool collisionDetected = false; public bool collisionDebugAll = false; //[HideInInspector] public float colliderHeight; void Start (){ colliderHeight = playerCapsuleTransform.GetComponent<CapsuleCollider>().height; } public void LocalPositionSetY(Transform t, float s ) { Vector3 v = t.position; v.y = s; t.position = v; } void FixedUpdate (){ //transform.position.x = playerCapsuleTransform.position.x; //transform.position.y = playerCapsuleTransform.position.y + ((colliderHeight * playerCapsuleTransform.localScale.y)/2) + (transform.localScale.y/2) + floatAbove; LocalPositionSetY(transform, (playerCapsuleTransform.position.y + ((colliderHeight * playerCapsuleTransform.localScale.y)/2) + (transform.localScale.y/2) + floatAbove)); //transform.position.z = playerCapsuleTransform.position.z; } void OnCollisionStay ( Collision collisionInfo ){ collisionDebugAll = true; if (collisionInfo.gameObject.tag == "Geometry") { collisionDetected = true; } } void OnCollisionExit (){ collisionDetected = false; } }<file_sep>/Assets/Scripts/WeaponShotsButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class WeaponShotsButton : MonoBehaviour { [SerializeField] private GameObject iconman; [SerializeField] private GameObject ammoiconman; [SerializeField] private GameObject weptextman; [SerializeField] private int WepButtonIndex; [SerializeField] private AudioSource SFX = null; // assign in the editor [SerializeField] private AudioClip SFXClip = null; // assign in the editor private int invslot; private float ix; private float iy; private Vector3 transMouse; private Matrix4x4 m; private Matrix4x4 inv; private bool alternateAmmo = false; public void PtrEnter () { GUIState.a.isBlocking = true; } public void PtrExit () { GUIState.a.isBlocking = false; } void WeaponInvClick () { invslot = WeaponInventory.WepInventoryInstance.weaponInventoryIndices[WepButtonIndex]; if (invslot < 0) return; SFX.PlayOneShot(SFXClip); ammoiconman.GetComponent<AmmoIconManager>().SetAmmoIcon(invslot, alternateAmmo); iconman.GetComponent<WeaponIconManager>().SetWepIcon(invslot); //Set weapon icon for MFD weptextman.GetComponent<WeaponTextManager>().SetWepText(invslot); //Set weapon text for MFD WeaponCurrent.WepInstance.weaponCurrent = WepButtonIndex; //Set current weapon } [SerializeField] private Button WepButton = null; // assign in the editor void Start() { WepButton.onClick.AddListener(() => { WeaponInvClick();}); } } <file_sep>/Assets/Scripts/TabButtons.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class TabButtons : MonoBehaviour { [SerializeField] private LeftMFDTabs TabManager = null; // assign in the editor [SerializeField] private Button WeaponTabButton = null; // assign in the editor [SerializeField] private Button ItemTabButton = null; // assign in the editor [SerializeField] private Button AutomapTabButton = null; // assign in the editor [SerializeField] private Button TargetTabButton = null; // assign in the editor [SerializeField] private Button DataTabButton = null; // assign in the editor [SerializeField] private Sprite MFDSprite = null; // assign in the editor [SerializeField] private Sprite MFDSpriteSelected = null; // assign in the editor [SerializeField] private AudioSource TabSFX = null; // assign in the editor [SerializeField] private AudioClip TabSFXClip = null; // assign in the editor public int curTab = 0; public int lastTab = 0; public bool isRH; void Start() { TabManager.WeaponTab.SetActive(false); TabManager.ItemTab.SetActive(false); TabManager.AutomapTab.SetActive(false); TabManager.TargetTab.SetActive(false); TabManager.DataTab.SetActive(false); ItemTabButton.image.overrideSprite = MFDSprite; AutomapTabButton.image.overrideSprite = MFDSprite; TargetTabButton.image.overrideSprite = MFDSprite; DataTabButton.image.overrideSprite = MFDSprite; } public void SetCurrentAsLast () { lastTab = curTab; } public void ReturnToLastTab () { TabButtonClickSilent(lastTab,true); } public void TabButtonClick (int tabNum) { TabSFX.PlayOneShot(TabSFXClip); TabButtonClickSilent(tabNum,false); } public void TabButtonClickSilent (int tabNum,bool overrideToggling) { switch (tabNum) { case 0: if (curTab == 0) { if (TabManager.WeaponTab.activeSelf == true && !overrideToggling) { TabManager.WeaponTab.SetActive(false); break; } else { TabManager.WeaponTab.SetActive(true); break; } } WeaponTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.WeaponTab.SetActive(true); TabManager.ItemTab.SetActive(false); TabManager.AutomapTab.SetActive(false); TabManager.TargetTab.SetActive(false); TabManager.DataTab.SetActive(false); ItemTabButton.image.overrideSprite = MFDSprite; AutomapTabButton.image.overrideSprite = MFDSprite; TargetTabButton.image.overrideSprite = MFDSprite; DataTabButton.image.overrideSprite = MFDSprite; curTab = 0; MFDManager.a.lastWeaponSideRH = isRH; break; case 1: if (curTab == 1) { if (TabManager.ItemTab.activeSelf == true && !overrideToggling) { TabManager.ItemTab.SetActive(false); break; } else { TabManager.ItemTab.SetActive(true); break; } } ItemTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.WeaponTab.SetActive(false); TabManager.ItemTab.SetActive(true); TabManager.AutomapTab.SetActive(false); TabManager.TargetTab.SetActive(false); TabManager.DataTab.SetActive(false); WeaponTabButton.image.overrideSprite = MFDSprite; AutomapTabButton.image.overrideSprite = MFDSprite; TargetTabButton.image.overrideSprite = MFDSprite; DataTabButton.image.overrideSprite = MFDSprite; curTab = 1; MFDManager.a.lastItemSideRH = isRH; break; case 2: if (curTab == 2) { if (TabManager.AutomapTab.activeSelf == true && !overrideToggling) { TabManager.AutomapTab.SetActive(false); break; } else { TabManager.AutomapTab.SetActive(true); break; } } AutomapTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.WeaponTab.SetActive(false); TabManager.ItemTab.SetActive(false); TabManager.AutomapTab.SetActive(true); TabManager.TargetTab.SetActive(false); TabManager.DataTab.SetActive(false); WeaponTabButton.image.overrideSprite = MFDSprite; ItemTabButton.image.overrideSprite = MFDSprite; TargetTabButton.image.overrideSprite = MFDSprite; DataTabButton.image.overrideSprite = MFDSprite; curTab = 2; MFDManager.a.lastAutomapSideRH = isRH; break; case 3: if (curTab == 3) { if (TabManager.TargetTab.activeSelf == true && !overrideToggling) { TabManager.TargetTab.SetActive(false); break; } else { TabManager.TargetTab.SetActive(true); break; } } TargetTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.WeaponTab.SetActive(false); TabManager.ItemTab.SetActive(false); TabManager.AutomapTab.SetActive(false); TabManager.TargetTab.SetActive(true); TabManager.DataTab.SetActive(false); WeaponTabButton.image.overrideSprite = MFDSprite; ItemTabButton.image.overrideSprite = MFDSprite; AutomapTabButton.image.overrideSprite = MFDSprite; DataTabButton.image.overrideSprite = MFDSprite; curTab = 3; MFDManager.a.lastTargetSideRH = isRH; break; case 4: if (curTab == 4) { if (TabManager.DataTab.activeSelf == true && !overrideToggling) { TabManager.DataTab.SetActive(false); break; } else { TabManager.DataTab.SetActive(true); break; } } DataTabButton.image.overrideSprite = MFDSpriteSelected; TabManager.WeaponTab.SetActive(false); TabManager.ItemTab.SetActive(false); TabManager.AutomapTab.SetActive(false); TabManager.TargetTab.SetActive(false); TabManager.DataTab.SetActive(true); WeaponTabButton.image.overrideSprite = MFDSprite; ItemTabButton.image.overrideSprite = MFDSprite; AutomapTabButton.image.overrideSprite = MFDSprite; TargetTabButton.image.overrideSprite = MFDSprite; curTab = 4; MFDManager.a.lastDataSideRH = isRH; break; } } } <file_sep>/Assets/Scripts/TeleportFXStatic.cs using UnityEngine; using System.Collections; public class TeleportFXStatic : MonoBehaviour { public float intervalTime = 0.08f; public float activeTime = 1f; [HideInInspector] public GameObject mouseCursor; public Texture2D tempCursorTexture; [HideInInspector] public Texture2D cursorTexture; private float effectFinished; private float flipTime; private float randHolder; private bool xFlipped = false; private bool yFlipped = false; private RectTransform rect; void OnEnable () { mouseCursor = GameObject.Find("MouseCursorHandler"); if (mouseCursor == null) { print("Warning: Could Not Find object 'MouseCursorHandler' in scene\n"); return; } cursorTexture = mouseCursor.GetComponent<MouseCursor>().cursorImage; //store correct cursor mouseCursor.GetComponent<MouseCursor>().cursorImage = tempCursorTexture; //give dummy cursor to hide it effectFinished = Time.time + activeTime; rect = GetComponent<RectTransform>(); flipTime = Time.time + intervalTime; } void FlipX () { if (xFlipped) { xFlipped = false; rect.localScale = new Vector3(1f, 1f, 1f); } else { xFlipped = true; rect.localScale = new Vector3(-1f, 1f, 1f); } } void FlipY () { if (yFlipped) { yFlipped = false; rect.localScale = new Vector3(1f, 1f, 1f); } else { yFlipped = true; rect.localScale = new Vector3(1f, -1f, 1f); } } void Deactivate () { // TODO tell mouselookscript that teleportFX is active and prevent dropping or picking up items // so that the mouse cursor texture doesn't change while FX are active and also to prevent actions mouseCursor.GetComponent<MouseCursor>().cursorImage = cursorTexture; //return to previous cursor gameObject.SetActive(false); } void Update () { if (effectFinished < Time.time) { Deactivate(); } if (flipTime < Time.time) { flipTime = Time.time + intervalTime; randHolder = Random.Range(0f,1f); if (randHolder < 0.5) { FlipX(); } else { FlipY(); } } } } <file_sep>/Assets/Scripts/LogCountsText.cs using UnityEngine; using UnityEngine.UI; using System.Collections; [System.Serializable] public class LogCountsText : MonoBehaviour { Text text; int tempint; public int countsSlotnum = 0; void Start () { text = GetComponent<Text>(); } void Update () { tempint = LogInventory.a.numLogsFromLevel[countsSlotnum]; if (tempint > 0) { text.text = LogInventory.a.numLogsFromLevel[countsSlotnum].ToString(); } else { text.text = " "; // Blank out the text } } }<file_sep>/Assets/Scripts/PlayerPatch.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class PlayerPatch : MonoBehaviour { public GameObject playerCamera; [HideInInspector] public float berserkFinishedTime; [HideInInspector] public float berserkIncrementFinishedTime; [HideInInspector] public float detoxFinishedTime; [HideInInspector] public float geniusFinishedTime; [HideInInspector] public float mediFinishedTime; [HideInInspector] public float reflexFinishedTime; [HideInInspector] public float sightFinishedTime; [HideInInspector] public float sightSideEffectFinishedTime; [HideInInspector] public float staminupFinishedTime; public int berserkIncrement; private int PATCH_BERSERK = 1; private int PATCH_DETOX = 2; private int PATCH_GENIUS = 4; private int PATCH_MEDI = 8; private int PATCH_REFLEX = 16; private int PATCH_SIGHT = 32; private int PATCH_STAMINUP = 64; private AudioSource SFX; private MouseLookScript playerMouseLookScript; private PlayerHealth playerHealthScript; private PlayerMovement playerMovementScript; public WeaponFire playerWeapon; public Texture2D b1; public Texture2D b2; public Texture2D b3; public Texture2D b4; public Texture2D b5; public Texture2D b6; public Texture2D b7; public AudioClip patchUseSFX; public Light sightLight; public Image sightDimming; public PatchInventory playerPI; private UnityStandardAssets.ImageEffects.BerserkEffect berserk; public int patchActive; // bitflag carrier for active patches public PuzzleWire wirePuzzle; // Patches stack so multiple can be used at once // For instance, berserk + staminup + medi = 1 + 64 + 8 = 73 // This is turning on bits in the int patchActive so above would be: 01001001, // meaning 3 patches are enabled out of the 7 types (short integer has 8 bits // but the 7th bit can be used for sign +/-) void Awake () { playerHealthScript = gameObject.GetComponent<PlayerHealth>(); playerMouseLookScript = playerCamera.GetComponent<MouseLookScript>(); playerMovementScript = gameObject.GetComponent<PlayerMovement>(); SFX = GetComponent<AudioSource>(); mediFinishedTime = -1f; reflexFinishedTime = -1f; sightFinishedTime = -1f; berserk = playerCamera.GetComponent<UnityStandardAssets.ImageEffects.BerserkEffect>(); } public void ActivatePatch(int index) { switch (index) { case 14: // Berserk Patch playerPI.patchCounts[2]--; playerWeapon.berserkActive = true; if (!(Const.a.CheckFlags(patchActive, PATCH_BERSERK))) patchActive += PATCH_BERSERK; berserkFinishedTime = Time.time + Const.a.berserkTime; float berserkIncrementTime = Const.a.berserkTime/5f; berserkIncrementFinishedTime = Time.time + berserkIncrementTime; break; case 15: // Detox Patch playerPI.patchCounts[6]--; patchActive = PATCH_DETOX; // overwrite all other active patches playerHealthScript.detoxPatchActive = true; detoxFinishedTime = Time.time + Const.a.detoxTime; break; case 16: // Genius Patch playerPI.patchCounts[5]--; if (!(Const.a.CheckFlags(patchActive, PATCH_GENIUS))) patchActive += PATCH_GENIUS; geniusFinishedTime = Time.time + Const.a.geniusTime; break; case 17: // Medi Patch playerPI.patchCounts[3]--; if (!(Const.a.CheckFlags(patchActive, PATCH_MEDI))) patchActive += PATCH_MEDI; playerHealthScript.mediPatchPulseCount = 0; mediFinishedTime = Time.time + Const.a.mediTime; break; case 18: // Reflex Patch playerPI.patchCounts[4]--; Time.timeScale = Const.a.reflexTimeScale; if (!(Const.a.CheckFlags(patchActive, PATCH_REFLEX))) patchActive += PATCH_REFLEX; reflexFinishedTime = Time.realtimeSinceStartup + Const.a.reflexTime; break; case 19: // Sight Patch playerPI.patchCounts[1]--; sightLight.enabled = true; // enable vision enhancement sightSideEffectFinishedTime = -1f; // reset side effect timer from previous patch sightDimming.enabled = false; // deactivate side effect from previous patch if (!(Const.a.CheckFlags(patchActive, PATCH_SIGHT))) patchActive += PATCH_SIGHT; sightFinishedTime = Time.time + Const.a.sightTime; break; case 20: // Staminup Patch playerPI.patchCounts[0]--; playerMovementScript.staminupActive = true; if (!(Const.a.CheckFlags(patchActive, PATCH_STAMINUP))) patchActive += PATCH_STAMINUP; staminupFinishedTime = Time.time + Const.a.staminupTime; break; } SFX.PlayOneShot(patchUseSFX); GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } void Update () { // ================================== DETOX PATCH ========================= if (Const.a.CheckFlags(patchActive, PATCH_DETOX)) { // ---Disable Patch--- if (detoxFinishedTime < Time.time) { playerHealthScript.detoxPatchActive = false; // back to full force radiation effects patchActive -= PATCH_DETOX; } else { // ***Patch Effect*** patchActive = 2; // remove all other effects, even medipatch playerHealthScript.detoxPatchActive = true; // let health script know to ameliorate the effects of radiation } } // ================================== MEDI PATCH ========================= if (Const.a.CheckFlags(patchActive, PATCH_MEDI)) { // ---Disable Patch--- if (mediFinishedTime < Time.time && mediFinishedTime != -1) { patchActive -= PATCH_MEDI; playerHealthScript.mediPatchActive = false; mediFinishedTime = -1; } else { // ***Patch Effect*** playerHealthScript.mediPatchActive = true; } } // ================================== REFLEX PATCH ======================= if (Const.a.CheckFlags(patchActive, PATCH_REFLEX)) { // ---Disable Patch--- if (reflexFinishedTime < Time.realtimeSinceStartup && reflexFinishedTime != -1) { patchActive -= PATCH_REFLEX; Time.timeScale = Const.a.defaultTimeScale; reflexFinishedTime = -1; } else { // ***Patch Effect*** if (Time.timeScale != Const.a.reflexTimeScale) { Time.timeScale = Const.a.reflexTimeScale; } } } // ================================== BERSERK PATCH ======================= if (Const.a.CheckFlags(patchActive, PATCH_BERSERK)) { // ---Disable Patch--- if (berserkFinishedTime < Time.time) { berserkIncrement = 0; patchActive -= PATCH_BERSERK; playerWeapon.berserkActive = false; berserk.Reset(); berserk.enabled = false; } else { // ***Patch Effect*** playerWeapon.berserkActive = true; berserk.enabled = true; if (berserkIncrementFinishedTime < Time.time) { berserkIncrement++; switch (berserkIncrement) { case 0: berserk.swapTexture = b1; break; case 1: berserk.swapTexture = b2; berserk.effectStrength += 1f; break; case 2: berserk.swapTexture = b3; break; case 3: berserk.swapTexture = b4; berserk.effectStrength += 1f; berserk.hithreshold += 0.25f; break; case 4: berserk.swapTexture = b5; break; case 5: berserk.swapTexture = b6; berserk.effectStrength += 1f; berserk.hithreshold += 0.25f; break; case 6: berserk.swapTexture = b7; berserk.effectStrength += 1f; berserk.hithreshold += 0.25f; break; } float berserkIncrementTime = Const.a.berserkTime/5f; berserkIncrementFinishedTime = Time.time + berserkIncrementTime; } } } // ================================== GENIUS PATCH ======================== if (Const.a.CheckFlags(patchActive, PATCH_GENIUS)) { // ---Disable Patch--- if (geniusFinishedTime < Time.time) { playerMouseLookScript.geniusActive = false; patchActive -= PATCH_GENIUS; wirePuzzle.geniusActive = false; } else { // ***Patch Effect*** playerMouseLookScript.geniusActive = true; // so that LH/RH are swapped for mouse look wirePuzzle.geniusActive = true; } } // ================================== SIGHT PATCH ========================= if (Const.a.CheckFlags(patchActive, PATCH_SIGHT)) { // [[[Enable Side Effect]]] if (sightFinishedTime < Time.time && sightFinishedTime != -1f) { sightFinishedTime = -1f; sightSideEffectFinishedTime = Time.time + Const.a.sightSideEffectTime; sightLight.enabled = false; sightDimming.enabled = true; } // ---Disable Patch--- if (sightSideEffectFinishedTime < Time.time && sightSideEffectFinishedTime != -1f) { sightSideEffectFinishedTime = -1f; sightFinishedTime = -1f; sightDimming.enabled = false; sightLight.enabled = false; patchActive -= PATCH_SIGHT; } } // ================================== STAMINUP PATCH ====================== if (Const.a.CheckFlags(patchActive, PATCH_STAMINUP)) { // ---Disable Patch--- if (staminupFinishedTime < Time.time) { playerMovementScript.staminupActive = false; playerMovementScript.fatigue = 100f; // side effect patchActive -= PATCH_STAMINUP; } else { // ***Patch Effect*** playerMovementScript.fatigue = 0f; playerMovementScript.staminupActive = true; } } } } <file_sep>/Assets/Scripts/PlayerMovement.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using System.Collections; public class PlayerMovement : MonoBehaviour { private float walkAcceleration = 2000f; private float walkDeacceleration = 0.15f; private float walkDeaccelerationBooster = 2f; private float deceleration; private float walkAccelAirRatio = 0.15f; public GameObject cameraObject; public MouseLookScript mlookScript; public float playerSpeed; private float maxWalkSpeed = 3f; private float maxCyberSpeed = 4f; private float maxCrouchSpeed = 1.75f; private float maxProneSpeed = 1f; private float maxSprintSpeed = 9f; private float maxSprintSpeedFatigued = 5.5f; private float maxVerticalSpeed = 5f; private float boosterSpeedBoost = 0.5f; // ammount to boost by when booster is active public bool isSprinting = false; public bool isSkating = false; private float jumpImpulseTime = 2.0f; public float jumpVelocityBoots = 0.5f; private float jumpVelocity = 1.1f; private float jumpVelocityFatigued = 0.6f; public bool grounded = false; private float maxSlope = 90f; private float crouchRatio = 0.6f; private float proneRatio = 0.2f; private float transitionToCrouchSec = 0.2f; private float transitionToProneAdd = 0.1f; public float currentCrouchRatio = 1f; public float crouchLocalScaleY; public float capsuleHeight; public float capsuleRadius; public int bodyState = 0; public bool ladderState = false; private float ladderSpeed = 0.25f; private float fallDamage = 75f; public bool gravliftState = false; public bool inCyberSpace = false; public GameObject automapContainer; public Texture2D automapMaskTex; public float automapFactor = 0.000285f; private Sprite automapMaskSprite; //[HideInInspector] public bool CheatWallSticky; //[HideInInspector] public bool CheatNoclip; public bool staminupActive = false; private Vector2 horizontalMovement; private float verticalMovement; private float jumpTime; private float crouchingVelocity = 1f; private float originalLocalScaleY; private float lastCrouchRatio; private int layerGeometry = 9; private int layerMask; private Rigidbody rbody; private float fallDamageSpeed = 11.72f; private Vector3 oldVelocity; public GameObject mainMenu; public HardwareInvCurrent hwc; public float fatigue; private float jumpFatigue = 8f; private float fatigueWanePerTick = 1f; private float fatigueWanePerTickCrouched = 2f; private float fatigueWanePerTickProne = 3.5f; private float fatigueWaneTickSecs = 0.3f; private float fatiguePerWalkTick = 2.5f; private float fatiguePerSprintTick = 3.5f; public string cantStandText = "Can't stand here."; public string cantCrouchText = "Can't crouch here."; private bool justJumped = false; private float fatigueFinished; private float fatigueFinished2; private int defIndex = 0; private int def1 = 1; private int onehundred = 100; public bool running = false; public bool cyberSetup = false; public bool cyberDesetup = false; private SphereCollider cyberCollider; private CapsuleCollider capsuleCollider; private int oldBodyState; private float bonus; private float walkDeaccelerationVolx; private float walkDeaccelerationVoly; private float walkDeaccelerationVolz; public Image consolebg; public InputField consoleinpFd; public Text consoleplaceholderText; public Text consoleentryText; public bool consoleActivated; public Transform leanTransform; private float leanLeftDoubleFinished; private float keyboardButtonDoubleTapTime = 0.25f; // max time before a double tap of a keyboard button is registered private float leanTarget = 0f; void Awake (){ currentCrouchRatio = def1; bodyState = defIndex; cyberDesetup = false; oldBodyState = bodyState; fatigueFinished = Time.time; fatigueFinished2 = Time.time; originalLocalScaleY = transform.localScale.y; crouchLocalScaleY = transform.localScale.y * crouchRatio; rbody = GetComponent<Rigidbody>(); oldVelocity = rbody.velocity; capsuleHeight = GetComponent<CapsuleCollider>().height; capsuleRadius = GetComponent<CapsuleCollider>().radius; layerMask = def1 << layerGeometry; staminupActive = false; cyberCollider = GetComponent<SphereCollider>(); capsuleCollider = GetComponent<CapsuleCollider>(); consoleActivated = false; leanLeftDoubleFinished = Time.time; } bool CantStand (){ return Physics.CheckCapsule(cameraObject.transform.position, cameraObject.transform.position + new Vector3(0f,(1.6f-0.84f),0f), capsuleRadius, layerMask); } bool CantCrouch (){ return Physics.CheckCapsule(cameraObject.transform.position, cameraObject.transform.position + new Vector3(0f,0.4f,0f), capsuleRadius, layerMask); } void Update (){ // Crouch input state machine // Body states: // 0 = Standing // 1 = Crouch // 2 = Crouching down in process // 3 = Standing up in process // 4 = Prone // 5 = Proning down in process // 6 = Proning up to crouch in process // Always allow console, even when paused if (GetInput.a.Console()) { ToggleConsole(); } if (Input.GetKeyDown(KeyCode.Return)) { ConsoleEntry(); } if (mainMenu.activeSelf == true) return; // ignore movement when main menu is still up if (!PauseScript.a.paused) { rbody.WakeUp(); if (inCyberSpace && !cyberSetup) { cyberCollider.enabled = true; capsuleCollider.enabled = false; rbody.useGravity = false; mlookScript.inCyberSpace = true; // enable full camera rotation up/down by disabling clamp oldBodyState = bodyState; bodyState = defIndex; // reset to "standing" to prevent speed anomolies // TODO enable dummy player for coop games cyberSetup = true; cyberDesetup = true; } if (!inCyberSpace && cyberDesetup || CheatNoclip) { if (CheatNoclip) { // Flying cheat...also map editing mode! cyberCollider.enabled = false; // can't touch dis capsuleCollider.enabled = false; //na nana na rbody.useGravity = false; // look ma! no legs Mathf.Clamp(mlookScript.xRotation, -90f, 90f); // pre-clamp camera rotation - still useful mlookScript.inCyberSpace = false; // disable full camera rotation up/down by enabling auto clamp bodyState = oldBodyState; // return to what we were doing in the "real world" (real lol) // TODO disable dummy player for coop games dummyPlayerModel.SetActive(false); dummyPlayerCapsule.enabled = false; cyberSetup = false; cyberDesetup = false; } else { cyberCollider.enabled = false; capsuleCollider.enabled = true; rbody.useGravity = true; Mathf.Clamp(mlookScript.xRotation, -90f, 90f); // pre-clamp camera rotation mlookScript.inCyberSpace = false; // disable full camera rotation up/down by enabling auto clamp bodyState = oldBodyState; // return to what we were doing in the "real world" (real lol) // TODO disable dummy player for coop games cyberSetup = false; cyberDesetup = false; } } if (GetInput.a.Sprint() && !consoleActivated) { if (grounded) { if (GetInput.a.CapsLockOn()) { isSprinting = false; } else { isSprinting = true; } } } else { if (grounded) { if (GetInput.a.CapsLockOn()) { isSprinting = true; } else { isSprinting = false; } } } if (GetInput.a.Crouch() && !CheatNoclip && !consoleActivated) { if ((bodyState == 1) || (bodyState == 2)) { if (!(CantStand())) { bodyState = 3; // Start standing up //Debug.Log ("Standing up from crouch..."); } else { Const.sprint(cantStandText,Const.a.player1); } } else { if ((bodyState == 0) || (bodyState == 3)) { //Debug.Log ("Crouching down..."); bodyState = 2; // Start crouching down } else { if ((bodyState == 4) || (bodyState == 5)) { if (!(CantCrouch())) { //Debug.Log ("Getting up from prone to crouch..."); bodyState = 6; // Start getting up to crouch } else { Const.sprint(cantCrouchText,Const.a.player1); } } } } } if (GetInput.a.Prone() && !CheatNoclip && !consoleActivated) { if (bodyState == 0 || bodyState == 1 || bodyState == 2 || bodyState == 3 || bodyState == 6) { //Debug.Log ("Proning down..."); bodyState = 5; // Start proning down } else { if (bodyState == 4 || bodyState == 5) { if (!CantStand()) { //Debug.Log ("Getting up from prone to standing..."); bodyState = 3; // Start standing up } else { Const.sprint(cantStandText,Const.a.player1); } } } } if (currentCrouchRatio > 1) { if (bodyState == 0 || bodyState == 3) { currentCrouchRatio = 1; //Clamp it bodyState = 0; } } else { if (currentCrouchRatio < crouchRatio) { if (bodyState == 1 || bodyState == 2) { currentCrouchRatio = crouchRatio; //Clamp it bodyState = 1; } else { if (bodyState == 4 || bodyState == 5) { if (currentCrouchRatio < proneRatio) { currentCrouchRatio = proneRatio; //Clamp it bodyState = 4; } } } } else { if (bodyState == 6) { if (currentCrouchRatio > crouchRatio) { currentCrouchRatio = crouchRatio; //Clamp it bodyState = 1; } } } } // here fatigue me out, except in cyberspace if (fatigueFinished < Time.time && !inCyberSpace && !CheatNoclip) { fatigueFinished = Time.time + fatigueWaneTickSecs; switch (bodyState) { case 0: fatigue -= fatigueWanePerTick; break; case 1: fatigue -= fatigueWanePerTickCrouched; break; case 4: fatigue -= fatigueWanePerTickProne; break; default: fatigue -= fatigueWanePerTick; break; } if (fatigue < defIndex) fatigue = defIndex; // clamp at 0 } if (fatigue > onehundred) fatigue = onehundred; // clamp at 100 using dummy variables to hang onto the value and not get collected by garbage collector } } public void LocalScaleSetX(Transform t, float s ) { Vector3 v = t.localScale; v.x = s; t.localScale = v; } public void LocalScaleSetY(Transform t, float s ) { Vector3 v = t.localScale; v.y = s; t.localScale = v; } public void LocalScaleSetZ(Transform t, float s ) { Vector3 v = t.localScale; v.z = s; t.localScale = v; } public void LocalPositionSetX(Transform t, float s ) { Vector3 v = t.position; v.x = s; t.position = v; } public void LocalPositionSetY(Transform t, float s ) { Vector3 v = t.position; v.y = s; t.position = v; } public void LocalPositionSetZ(Transform t, float s ) { Vector3 v = t.position; v.z = s; t.position = v; } public void RigidbodySetVelocity(Rigidbody t, float s ) { Vector3 v = t.velocity; v = v.normalized * s; t.velocity = v; } public void RigidbodySetVelocityX(Rigidbody t, float s ) { Vector3 v = t.velocity; v.x = s; t.velocity = v; } public void RigidbodySetVelocityY(Rigidbody t, float s ) { Vector3 v = t.velocity; v.y = s; t.velocity = v; } public void RigidbodySetVelocityZ(Rigidbody t, float s ) { Vector3 v = t.velocity; v.z = s; t.velocity = v; } void FixedUpdate (){ if (mainMenu.activeSelf == true) return; // ignore movement when main menu is still up if (PauseScript.a == null) { Const.sprint("ERROR->PlayerMovement: PauseScript is null",transform.parent.gameObject); return; } if (!PauseScript.a.paused) { if (CheatNoclip) grounded = true; // Crouch LocalScaleSetY(transform,(originalLocalScaleY * currentCrouchRatio)); // Handle body state speeds and body position lerping for smooth transitions if (!inCyberSpace && !CheatNoclip) { bonus = 0f; if (hwc.hardwareIsActive [9]) bonus = boosterSpeedBoost; switch (bodyState) { case 0: playerSpeed = maxWalkSpeed + bonus; //TODO:: lerp from other speeds break; case 1: //Debug.Log("Crouched"); playerSpeed = maxCrouchSpeed + bonus; //TODO:: lerp from other speeds break; case 2: //Debug.Log("Crouching down lerp from standing..."); currentCrouchRatio = Mathf.SmoothDamp (currentCrouchRatio, -0.01f, ref crouchingVelocity, transitionToCrouchSec); break; case 3: //Debug.Log("Standing up lerp from crouch or prone..."); lastCrouchRatio = currentCrouchRatio; currentCrouchRatio = Mathf.SmoothDamp (currentCrouchRatio, 1.01f, ref crouchingVelocity, transitionToCrouchSec); LocalPositionSetY (transform, (((currentCrouchRatio - lastCrouchRatio) * capsuleHeight) / 2) + transform.position.y); break; case 4: playerSpeed = maxProneSpeed + bonus; //TODO:: lerp from other speeds break; case 5: currentCrouchRatio = Mathf.SmoothDamp (currentCrouchRatio, -0.01f, ref crouchingVelocity, transitionToCrouchSec); break; case 6: lastCrouchRatio = currentCrouchRatio; currentCrouchRatio = Mathf.SmoothDamp (currentCrouchRatio, 1.01f, ref crouchingVelocity, (transitionToCrouchSec + transitionToProneAdd)); LocalPositionSetY (transform, (((currentCrouchRatio - lastCrouchRatio) * capsuleHeight) / 2) + transform.position.y); break; } } else { if (!CheatNoclip) { //Cyber space state playerSpeed = maxCyberSpeed; } } if (inCyberSpace && !CheatNoclip) { // Limit movement speed in all axes x,y,z in cyberspace if (rbody.velocity.magnitude > playerSpeed) { RigidbodySetVelocity(rbody, playerSpeed); } } else { // Limit movement speed horizontally for normal movement horizontalMovement = new Vector2(rbody.velocity.x, rbody.velocity.z); if (horizontalMovement.magnitude > playerSpeed) { horizontalMovement = horizontalMovement.normalized; if (isSprinting && running && !inCyberSpace && !CheatNoclip) { if (fatigue > 80f) { playerSpeed = maxSprintSpeedFatigued + bonus; } else { playerSpeed = maxSprintSpeed + bonus; } } horizontalMovement *= playerSpeed; // cap velocity to max speed } // Set horizontal velocity RigidbodySetVelocityX(rbody, horizontalMovement.x); RigidbodySetVelocityZ(rbody, horizontalMovement.y); // NOT A BUG - already passed rbody.velocity.z into the .y of this Vector2 UpdateAutomap(); if (horizontalMovement.x != 0 || horizontalMovement.y != 0) { //automapContainer.GetComponent<ScrollRect>().verticalNormalizedPosition += horizontalMovement.y * automapFactor * (-1); //automapContainer.GetComponent<ScrollRect>().horizontalNormalizedPosition += horizontalMovement.x * automapFactor * (-1); //UpdateAutomap(); } // Set vertical velocity verticalMovement = rbody.velocity.y; if (verticalMovement > maxVerticalSpeed) { verticalMovement = maxVerticalSpeed; } if (!CheatNoclip) RigidbodySetVelocityY(rbody, verticalMovement); // Ground friction (TODO: disable grounded for Cyberspace) if (grounded || CheatNoclip) { if (hwc.hardwareIsActive [9]) { deceleration = walkDeaccelerationBooster; } else { deceleration = walkDeacceleration; } if (CheatNoclip) deceleration = 0.05f; RigidbodySetVelocityX(rbody, (Mathf.SmoothDamp(rbody.velocity.x, 0, ref walkDeaccelerationVolx, deceleration))); if (CheatNoclip) RigidbodySetVelocityY(rbody, (Mathf.SmoothDamp(rbody.velocity.y, 0, ref walkDeaccelerationVoly, deceleration))); RigidbodySetVelocityZ(rbody, (Mathf.SmoothDamp(rbody.velocity.z, 0, ref walkDeaccelerationVolz, deceleration))); } } // Set rotation of playercapsule from mouselook script TODO: Is this needed? //transform.rotation = Quaternion.Euler(0,mlookScript.yRotation,0); //Change 0 values for x and z for use in Cyberspace float relForward = 0f; float relSideways = 0f; running = false; if (GetInput.a.Forward() && !consoleActivated) relForward = 1f; if (GetInput.a.Backpedal() && !consoleActivated) relForward = -1f; if (GetInput.a.StrafeLeft() && !consoleActivated) relSideways = -1f; if (GetInput.a.StrafeRight() && !consoleActivated) relSideways = 1f; if (relForward != 0 || relSideways != 0) running = true; // we are mashing a run button down // Handle movement if (!inCyberSpace) { if (grounded == true || CheatNoclip) { if (ladderState && !CheatNoclip) { // CLimbing when touching the ground //rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime, 0); rbody.AddRelativeForce (relSideways * walkAcceleration * Time.deltaTime, relForward * walkAcceleration * Time.deltaTime, 0); } else { //Walking on the ground //rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime); if (CheatNoclip) { rbody.AddRelativeForce(relSideways * 2f * walkAcceleration * Time.deltaTime, 0, relForward * 2f * walkAcceleration * Time.deltaTime); } else { rbody.AddRelativeForce(relSideways * walkAcceleration * Time.deltaTime, 0, relForward * walkAcceleration * Time.deltaTime); } // Noclip up and down if (GetInput.a.SwimUp() && !consoleActivated) { if (CheatNoclip) { //Debug.Log("Floating Up!"); rbody.AddRelativeForce(0, 4 * walkAcceleration * Time.deltaTime, 0); } } if (GetInput.a.SwimDn() && !consoleActivated) { if (CheatNoclip) { //Debug.Log("Floating Dn!"); rbody.AddRelativeForce(0, 4 * walkAcceleration * Time.deltaTime * -1, 0); } } if (fatigueFinished2 < Time.time && relForward != defIndex && !CheatNoclip) { fatigueFinished2 = Time.time + fatigueWaneTickSecs; if (isSprinting) { fatigue += fatiguePerSprintTick; if (staminupActive) fatigue = 0; } else { fatigue += fatiguePerWalkTick; if (staminupActive) fatigue = 0; } } } } else { if (ladderState) { // Climbing off the ground //rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, ladderSpeed * Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime, 0); rbody.AddRelativeForce (relSideways * walkAcceleration * walkAccelAirRatio * Time.deltaTime, ladderSpeed * relForward * walkAcceleration * Time.deltaTime, 0); } else { // Sprinting in the air if (isSprinting && running && !inCyberSpace && !CheatNoclip) { //rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime); rbody.AddRelativeForce (relSideways * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime, 0, relForward * walkAcceleration * walkAccelAirRatio * 0.01f * Time.deltaTime); } else { // Walking in the air, we're floating in the moonlit sky, the people far below are sleeping as we fly //rbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio * Time.deltaTime); if (CheatNoclip) { //rbody.AddRelativeForce(relSideways * walkAcceleration * 1.5f * Time.deltaTime, 0, relForward * walkAcceleration * 1.5f * Time.deltaTime); } else { rbody.AddRelativeForce(relSideways * walkAcceleration * walkAccelAirRatio * Time.deltaTime, 0, relForward * walkAcceleration * walkAccelAirRatio * Time.deltaTime); } } } } // private float leanLeftDoubleFinished; //private float keyboardButtonDoubleTapTime = 0.25f; // max time before a double tap of a keyboard button is registered // Handle leaning if (GetInput.a.LeanLeft()) { // Check for double tap of lean and reset lean target //if (leanLeftDoubleFinished < Time.time) { // leanTarget = 0; // leanLeftDoubleFinished = Mathf.Infinity; /// return; //} leanTarget -= (1f * Time.deltaTime); if (leanTarget < 22.5f) leanTarget = -22.5f; leanLeftDoubleFinished = Time.time + keyboardButtonDoubleTapTime; } if (GetInput.a.LeanRight()) { } //move lean transform.localRotation.z to leanTarget; float leanz = Mathf.Lerp(leanTransform.localRotation.z,leanTarget,0.1f); leanTransform.localRotation = Quaternion.Euler(0, 0, leanz); // Handle gravity and ladders if (ladderState) { rbody.useGravity = false; // Set vertical velocity towards 0 when climbing if (hwc.hardwareIsActive [9]) { deceleration = walkDeaccelerationBooster; } else { deceleration = walkDeacceleration; } RigidbodySetVelocityY(rbody, (Mathf.SmoothDamp(rbody.velocity.y, 0, ref walkDeaccelerationVoly, deceleration))); } else { // Check if using a gravity lift if (gravliftState == true || CheatNoclip) { rbody.useGravity = false; } else { // Disables gravity when touching the ground to prevent player sliding down ramps...hacky? if (grounded == true) { rbody.useGravity = false; } else { if (!inCyberSpace) rbody.useGravity = true; } } // Apply gravity - OBSOLETE: Now handled by gravity of the RigidBody physics system //rbody.AddForce(0, (-1 * playerGravity * Time.deltaTime), 0); //Apply gravity force } // Get input for Jump and set impulse time if (!inCyberSpace && (GetInput.a.Jump() && !consoleActivated) && (ladderState == false) && !CheatNoclip) { if (grounded || gravliftState || (hwc.hardwareIsActive[10])) { jumpTime = jumpImpulseTime; } } // Perform Jump while (jumpTime > 0) { jumpTime -= Time.smoothDeltaTime; if (fatigue > 80 && !(hwc.hardwareIsActive[10])) { rbody.AddForce (new Vector3 (0, jumpVelocityFatigued * rbody.mass, 0), ForceMode.Force); // huhnh! } else { if (hwc.hardwareIsActive [10]) { rbody.AddForce (new Vector3 (0, jumpVelocityBoots * rbody.mass, 0), ForceMode.Force); // huhnh! } else { rbody.AddForce (new Vector3 (0, jumpVelocity * rbody.mass, 0), ForceMode.Force); // huhnh! } } //if ( justJumped = true; } if (justJumped && !(hwc.hardwareIsActive[10])) { justJumped = false; fatigue += jumpFatigue; if (staminupActive) fatigue = 0; } // Handle fall damage (no impact damage in cyber space 5/5/18, JJ) if (Mathf.Abs ((oldVelocity.y - rbody.velocity.y)) > fallDamageSpeed && !inCyberSpace && !CheatNoclip) { DamageData dd = new DamageData (); dd.damage = fallDamage; dd.attackType = Const.AttackType.None; dd.offense = 0f; dd.isOtherNPC = false; GetComponent<PlayerHealth> ().TakeDamage (dd); } oldVelocity = rbody.velocity; // Automatically set grounded to false to prevent ability to climb any wall if (CheatWallSticky == false || gravliftState) grounded = false; } else { // Handle cyberspace movement if (GetInput.a.Forward() && !consoleActivated) { //Vector3 tempvec = mlookScript.cyberLookDir; rbody.AddForce (cameraObject.transform.forward * walkAcceleration * Time.deltaTime); //rbody.AddRelativeForce (relSideways * walkAcceleration * Time.deltaTime, 0, relForward * walkAcceleration * Time.deltaTime); } } } } // Update automap location public void UpdateAutomap () { //Texture2D tex = new Texture2D(512,512); // 722,658 //tex.SetPixels(automapMaskTex.GetPixels(0,0,512,512), 0); //tex.Apply(); //automapMaskSprite = Sprite.Create(tex, new Rect(0, 0, 512, 512), new Vector2(50,50)); //automapContainer.GetComponent<Image>().sprite = automapMaskSprite; } // Sets grounded based on normal angle of the impact point (NOTE: This is not the surface normal!) void OnCollisionStay (Collision collision ){ if (!PauseScript.a.paused && !inCyberSpace) { foreach(ContactPoint contact in collision.contacts) { if (Vector3.Angle(contact.normal,Vector3.up) < maxSlope) { grounded = true; } } } } // Reset grounded to false when player is mid-air void OnCollisionExit (){ if (!PauseScript.a.paused) { // Automatically set grounded to false to prevent ability to climb any wall (Cheat!) if (CheatWallSticky == true) { grounded = false; } } } private void ToggleConsole() { if (consoleActivated) { consoleActivated = false; consoleplaceholderText.enabled = false; consoleinpFd.DeactivateInputField(); consoleinpFd.enabled = false; consolebg.enabled = false; consoleentryText.enabled = false; } else { consoleActivated = true; consoleplaceholderText.enabled = true; consoleinpFd.enabled = true; consoleinpFd.ActivateInputField(); consolebg.enabled = true; consoleentryText.enabled = true; } } public void ConsoleEntry() { if (consoleinpFd.text == "noclip") { if (CheatNoclip) { CheatNoclip = false; Const.sprint("Noclip disabled", Const.a.allPlayers); } else { CheatNoclip = true; Const.sprint("Noclip activated!", Const.a.allPlayers); } } else if (consoleinpFd.text == "wallsticky") { if (CheatNoclip) { CheatWallSticky = false; Const.sprint("Wallsticky disabled", Const.a.allPlayers); } else { CheatWallSticky = true; Const.sprint("Wallsticky activated!", Const.a.allPlayers); } } else if (consoleinpFd.text == "god") { Const.sprint("God mode activated!", Const.a.allPlayers); } else { Const.sprint("Uknown command or function: " + consoleinpFd.text, Const.a.allPlayers); } // Reset console and hide it, command was entered consoleinpFd.text = ""; ToggleConsole(); } }<file_sep>/Assets/Scripts/WeaponMagazineCounter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WeaponMagazineCounter : MonoBehaviour { public Sprite[] indicatorSprites; public Image onesIndicator; public Image tensIndicator; public Image hunsIndicator; private int tempi; private int checkcount; private int[] tempis = new int[] {0,0,0}; public void UpdateDigits (int newamount) { tempi = newamount; tempis[0] = 10; tempis[1] = 10; tempis[2] = 10; //if (tempi > 99) { tempis[2] = tempi % 10; // ones if (newamount > 9) { tempi /= 10; tempis[1] = tempi % 10; // tens } if (newamount> 99) { tempi /= 10; tempis[0] = tempi % 10; // huns } onesIndicator.overrideSprite = indicatorSprites[tempis[2]]; tensIndicator.overrideSprite = indicatorSprites[tempis[1]]; hunsIndicator.overrideSprite = indicatorSprites[tempis[0]]; } } <file_sep>/Assets/Scripts/ElevatorButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ElevatorButton : MonoBehaviour { public bool floorAccessible = false; public bool tooFarAway = false; public bool doorOpen = false; private GameObject levelManager; [HideInInspector] public GameObject targetDestination; private Text childText; private int levelIndex; public GameObject currentPlayer; private string levR = "R"; private string lev1 = "1"; private string lev2 = "2"; private string lev3 = "3"; private string lev4 = "4"; private string lev5 = "5"; private string lev6 = "6"; private string lev7 = "7"; private string lev8 = "8"; private string lev9 = "9"; private string levG1 = "G1"; private string levG2 = "G2"; private string levG4 = "G4"; private string levC = "C"; private int zero = 0; private int one = 1; private int two = 2; private int three = 3; private int four = 4; private int five = 5; private int six = 6; private int seven = 7; private int eight = 8; private int nine = 9; private int ten = 10; private int eleven = 11; private int twelve = 12; private int thirteen = 13; public string tooFarAwayText = "You are too far away from that"; public string doorStillOpenText = "Elevator door is still open"; public string shaftDamageText = "Shaft Damage -- Unable to go there."; void Awake() { levelManager = GameObject.Find("LevelManager"); if (levelManager == null) Const.sprint("Warning: Could Not Find object 'LevelManager' in scene\n",Const.a.allPlayers); childText = GetComponentInChildren<Text>(); doorOpen = false; } void Start() { GetComponent<Button>().onClick.AddListener(() => { ElevButtonClick(); }); } void ElevButtonClick () { if (tooFarAway) { Const.sprint(tooFarAwayText,currentPlayer); } else { if (doorOpen) { Const.sprint(doorStillOpenText,currentPlayer); } else { if (floorAccessible && levelManager != null) { levelManager.GetComponent<LevelManager>().LoadLevel(levelIndex,targetDestination,currentPlayer); } else { Const.sprint(shaftDamageText,currentPlayer); } } } } public void SetTooFarTrue() { tooFarAway = true; } public void SetTooFarFalse() { tooFarAway = false; } void Update() { if (childText.text == levR) { levelIndex = zero; } if (childText.text == lev1) { levelIndex = one; } if (childText.text == lev2) { levelIndex = two; } if (childText.text == lev3) { levelIndex = three; } if (childText.text == lev4) { levelIndex = four; } if (childText.text == lev5) { levelIndex = five; } if (childText.text == lev6) { levelIndex = six; } if (childText.text == lev7) { levelIndex = seven; } if (childText.text == lev8) { levelIndex = eight; } if (childText.text == lev9) { levelIndex = nine; } if (childText.text == levG1) { levelIndex = ten; } if (childText.text == levG2) { levelIndex = eleven; } if (childText.text == levG4) { levelIndex = twelve; } if (childText.text == levC) { levelIndex = thirteen; } } } <file_sep>/Assets/Scripts/FuncWall.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FuncWall : MonoBehaviour { public float speed = 0.64f; public GameObject targetPosition; public enum FuncStates {Start, Target, MovingStart, MovingTarget,AjarMovingStart,AjarMovingTarget}; public FuncStates startState; public float percentAjar = 0; public AudioClip SFXMoving; public AudioClip SFXStop; public GameObject trigger; public bool useTrigger; public bool useOnlyActivatesTrigger; private Vector3 startPosition; private Vector3 goalPosition; private Vector3 tempVec; private AudioSource SFXSource; private FuncStates currentState; private Rigidbody rbody; private bool stopSoundPlayed; private bool movedToLocation; private float dist; void Awake () { currentState = startState; // set door position to picked state startPosition = transform.position; if (currentState == FuncStates.AjarMovingStart || currentState == FuncStates.AjarMovingTarget) { tempVec = ((transform.position - targetPosition.transform.position).normalized * (Vector3.Distance(transform.position,targetPosition.transform.position) * percentAjar * -1)) + transform.position; transform.position = tempVec; if (useTrigger) trigger.SetActive (false); } rbody = GetComponent<Rigidbody>(); rbody.isKinematic = true; SFXSource = GetComponent<AudioSource>(); stopSoundPlayed = false; movedToLocation = false; dist = 0; if (useOnlyActivatesTrigger) trigger.SetActive (false); } public void Targetted (UseData ud) { if (useOnlyActivatesTrigger) { trigger.SetActive (true); useOnlyActivatesTrigger = false; return; } switch (currentState) { case FuncStates.Start: MoveTarget(); break; case FuncStates.Target: MoveStart(); break; case FuncStates.MovingStart: MoveTarget (); break; case FuncStates.MovingTarget: MoveStart (); break; case FuncStates.AjarMovingStart: MoveStart(); break; case FuncStates.AjarMovingTarget: MoveTarget(); break; } SFXSource.clip = SFXMoving; SFXSource.loop = true; SFXSource.Play(); stopSoundPlayed = false; movedToLocation = false; } void MoveStart() { currentState = FuncStates.MovingStart; if (useTrigger) { trigger.SetActive (false); } } void MoveTarget() { currentState = FuncStates.MovingTarget; if (useTrigger) { trigger.SetActive (false); } } void FixedUpdate () { switch (currentState) { case FuncStates.Start: if (!movedToLocation) { transform.position = startPosition; rbody.velocity = Vector3.zero; movedToLocation = true; } break; case FuncStates.Target: if (!movedToLocation) { transform.position = targetPosition.transform.position; rbody.velocity = Vector3.zero; movedToLocation = true; } break; case FuncStates.MovingStart: goalPosition = startPosition; //transform.position = Vector3.MoveTowards (transform.position, goalPosition, (speed * Time.deltaTime)); rbody.WakeUp(); //rbody.velocity = ((goalPosition - transform.position) * speed); dist = speed * Time.deltaTime; tempVec = ((transform.position - goalPosition).normalized * dist * -1) + transform.position; rbody.MovePosition(tempVec); if ((Vector3.Distance(transform.position,goalPosition)) <= 0.02f) { if (currentState == FuncStates.MovingStart) { currentState = FuncStates.Start; } else { currentState = FuncStates.Target; } if (!stopSoundPlayed) { SFXSource.Stop (); SFXSource.loop = false; SFXSource.PlayOneShot (SFXStop); stopSoundPlayed = true; } if (useTrigger) trigger.SetActive (true); } break; case FuncStates.MovingTarget: goalPosition = targetPosition.transform.position; //transform.position = Vector3.MoveTowards (transform.position, goalPosition, (speed * Time.deltaTime)); rbody.WakeUp(); //rbody.velocity = ((goalPosition - transform.position) * speed); //rbody.velocity = new Vector3(0,-1f,0); //rbody.velocity = (goalPosition - transform.position) * speed; //rbody.MovePosition(goalPosition); dist = speed * Time.deltaTime; tempVec = ((transform.position - goalPosition).normalized * dist * -1) + transform.position; rbody.MovePosition(tempVec); if ((Vector3.Distance(transform.position,goalPosition)) <= 0.01f) { if (currentState == FuncStates.MovingStart) { currentState = FuncStates.Start; } else { currentState = FuncStates.Target; } if (!stopSoundPlayed) { SFXSource.Stop (); SFXSource.loop = false; SFXSource.PlayOneShot (SFXStop); stopSoundPlayed = true; } if (useTrigger) { trigger.SetActive (true); } } break; } } } <file_sep>/Assets/Scripts/PatchInventory.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class PatchInventory : MonoBehaviour { public int[] patchCounts; public static PatchInventory PatchInvInstance; public Text[] patchCountTextObjects; void Awake () { PatchInvInstance = this; for (int i= 0; i<7; i++) { PatchInvInstance.patchCounts[i] = 0; } } public void AddPatchToInventory (int index) { patchCounts[index]++; // Update UI text for (int i = 0; i < 7; i++) { patchCountTextObjects[i].text = patchCounts [i].ToString (); if (i == index) patchCountTextObjects[i].color = Const.a.ssYellowText; // Yellow else patchCountTextObjects[i].color = Const.a.ssGreenText; // Green } } } <file_sep>/Assets/Scripts/GrenadeInventoryText.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class GrenadeInventoryText : MonoBehaviour { Text text; [SerializeField] public int slotnum = 0; void Start () { text = GetComponent<Text>(); } void Update () { //text.text = WeaponText.Instance.weaponInventoryText[slotnum]; if (slotnum == GrenadeCurrent.GrenadeInstance.grenadeCurrent) { text.color = Const.a.ssYellowText; // Yellow } else { text.color = Const.a.ssGreenText; // Green } } } <file_sep>/Assets/Scripts/ListenerHardwareEreader.cs using UnityEngine; using System.Collections; public class ListenerHardwareEreader : MonoBehaviour { //[SerializeField] private AudioSource SFX = null; // assign in the editor //[SerializeField] private AudioClip SFXClip = null; // assign in the editor //[SerializeField] public GameObject centerTabContainer; //public CenterTabButtons ctb; /* void Update (){ if (HardwareInventory.a.hasHardware[2] && GetInput.a.Email()) { SFX.PlayOneShot(SFXClip); //centerTabContainer.GetComponent<CenterMFDTabs>().DisableAllTabs(); //centerTabContainer.GetComponent<CenterMFDTabs>().DataReaderContentTab.SetActive(true); ctb.TabButtonClickSilent(4); MFDManager.a.OpenEReaderInItemsTab(); } }*/ }<file_sep>/Assets/Scripts/MouseCursor.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class MouseCursor : MonoBehaviour { public GameObject playerCamera; public GameObject uiCamera; public bool liveGrenade = false; public string toolTip = ""; public Camera mainCamera; public MouseLookScript playerCameraScript; public RectTransform centerMFDPanel; public GameObject inventoryAddHelper; public float cursorSize = 24f; public bool offsetCentering = true; public Texture2D cursorImage; private float offsetX; private float offsetY; public bool justDroppedItemInHelper = false; public static Rect drawTexture; public Rect drawTextureInspector; public static float cursorXmin; public static float cursorYmin; public static float cursorX; public static float cursorY; public float x; public float y; public static float cursorXmax; public static float cursorYmax; public GUIStyle liveGrenadeStyle; public GUIStyle toolTipStyle; public GUIStyle toolTipStyleLH; public GUIStyle toolTipStyleRH; public Handedness toolTipType; public Texture2D cursorLHTexture; public Texture2D cursorRHTexture; public Texture2D cursorDNTexture; public Texture2D cursorOverButtonTexture; private Texture2D tempTexture; public WeaponCurrent wepCurrent; void OnGUI () { if (offsetCentering) { offsetX = cursorSize / 2; offsetY = offsetX; } //Debug.Log("MouseCursor:: Input.mousePosition.x: " + Input.mousePosition.x.ToString() + ", Input.mousePosition.y: " + Input.mousePosition.y.ToString()); if (playerCameraScript.inventoryMode || PauseScript.a.paused) { // Inventory Mode Cursor drawTexture = new Rect(Input.mousePosition.x - offsetX, Screen.height - Input.mousePosition.y - offsetY, cursorSize, cursorSize); } else { // Shoot Mode Cursor drawTexture = new Rect((Screen.width/2) - offsetX, (Screen.height/2) - cursorSize, cursorSize, cursorSize); } drawTextureInspector = drawTexture; cursorXmin = drawTexture.xMin; cursorYmin = drawTexture.yMin; cursorX = drawTexture.center.x; cursorY = drawTexture.center.y; x = cursorX; y = cursorY; cursorXmax = drawTexture.xMax; cursorYmax = drawTexture.yMax; if (toolTip != null && toolTip != "" && toolTip != "-1" && !PauseScript.a.paused) { switch(toolTipType) { case Handedness.LH: GUI.Label(drawTexture,toolTip,toolTipStyleLH); tempTexture = cursorLHTexture; break; case Handedness.RH: GUI.Label(drawTexture,toolTip,toolTipStyleRH); tempTexture = cursorRHTexture; break; default: GUI.Label(drawTexture,toolTip,toolTipStyle); tempTexture = cursorDNTexture; break; // Handedness.Center } if (!playerCameraScript.holdingObject) { cursorImage = tempTexture; } } else { if (playerCameraScript.holdingObject) { cursorImage = Const.a.useableItemsFrobIcons[playerCameraScript.heldObjectIndex]; } else { //cursorImage = Const.a.useableItemsFrobIcons[115]; switch(wepCurrent.weaponIndex) { case 36: cursorImage = Const.a.useableItemsFrobIcons[116]; // red break; case 37: cursorImage = Const.a.useableItemsFrobIcons[125]; // blue break; case 38: cursorImage = Const.a.useableItemsFrobIcons[116]; // red break; case 39: cursorImage = Const.a.useableItemsFrobIcons[115]; // green break; case 40: cursorImage = Const.a.useableItemsFrobIcons[125]; // blue break; case 41: cursorImage = Const.a.useableItemsFrobIcons[126]; // orange break; case 42: cursorImage = Const.a.useableItemsFrobIcons[126]; // orange break; case 43: cursorImage = Const.a.useableItemsFrobIcons[116]; // red break; case 44: cursorImage = Const.a.useableItemsFrobIcons[123]; // yellow break; case 45: cursorImage = Const.a.useableItemsFrobIcons[116]; // red break; case 46: cursorImage = Const.a.useableItemsFrobIcons[127]; // teal break; case 47: cursorImage = Const.a.useableItemsFrobIcons[123]; // yellow break; case 48: cursorImage = Const.a.useableItemsFrobIcons[116]; // red break; case 49: cursorImage = Const.a.useableItemsFrobIcons[115]; // green break; case 50: cursorImage = Const.a.useableItemsFrobIcons[125]; // blue break; case 51: cursorImage = Const.a.useableItemsFrobIcons[127]; // teal break; default: cursorImage = Const.a.useableItemsFrobIcons[115]; // green break; } } } GUI.DrawTexture(drawTexture, cursorImage); if (liveGrenade && !PauseScript.a.paused) { GUI.Label(drawTexture,"live",liveGrenadeStyle); } } void Update () { cursorSize = (24f * (Screen.width/640f)); if (playerCameraScript.inventoryMode && playerCameraScript.holdingObject && !PauseScript.a.paused) { // Be sure to pass the camera to the 3rd parameter if using "Screen Space - Camer" on the Canvas, otherwise use "null" if (RectTransformUtility.RectangleContainsScreenPoint(centerMFDPanel,Input.mousePosition,uiCamera.GetComponent<Camera>())) { if (!inventoryAddHelper.activeInHierarchy) inventoryAddHelper.SetActive(true); } else { if (inventoryAddHelper.activeInHierarchy) inventoryAddHelper.SetActive(false); if (justDroppedItemInHelper) { GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); justDroppedItemInHelper = false; // only disable blocking state once, not constantly } } } else { if (justDroppedItemInHelper) { justDroppedItemInHelper = false; // only disable blocking state once, not constantly inventoryAddHelper.SetActive(false); GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } } } } <file_sep>/Assets/Scripts/PreviewCulling.cs using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections; [ExecuteInEditMode] public class PreviewCulling : MonoBehaviour { #if UNITY_EDITOR static Camera sceneReferenceCamera; Vector3 pos; Quaternion rot; float near; float far; new Camera camera; bool IsSceneViewCamera(Camera cam) { Camera[] sceneCameras = SceneView.GetAllSceneCameras(); for (int i = 0; i < sceneCameras.Length; i++){ if (cam == sceneCameras[i]) { return true; } } return false; } void OnEnable() { camera = GetComponent<Camera>(); if (camera && !IsSceneViewCamera(camera)) { sceneReferenceCamera = camera; UpdateSceneCameras(); } } void OnDisable() { if (camera && sceneReferenceCamera == camera) { CleanSceneCameras(); sceneReferenceCamera = null; } } private void UpdateSceneCameras() { //add a PreviewCulling script to the scene camera if not done already Camera[] sceneCameras = SceneView.GetAllSceneCameras(); for (int i = 0; i < sceneCameras.Length; i++) { if (!sceneCameras[i].GetComponent<PreviewCulling>()) { sceneCameras[i].gameObject.AddComponent<PreviewCulling>(); } } } void CleanSceneCameras() { Camera[] sceneCameras = SceneView.GetAllSceneCameras(); for (int i = 0; i < sceneCameras.Length; i++) { PreviewCulling pc = sceneCameras[i].GetComponent<PreviewCulling>(); if (pc) { DestroyImmediate(pc); } } } void OnPreCull() { //if the scene camera is about to cull, save current transform values and copy from the reference camera if (camera && sceneReferenceCamera && IsSceneViewCamera(camera)) { pos = transform.position; rot = transform.rotation; near = camera.nearClipPlane; far = camera.farClipPlane; camera.projectionMatrix = sceneReferenceCamera.projectionMatrix; camera.transform.position = sceneReferenceCamera.transform.position; camera.transform.rotation = sceneReferenceCamera.transform.rotation; camera.nearClipPlane = sceneReferenceCamera.nearClipPlane; camera.farClipPlane = sceneReferenceCamera.farClipPlane; } } void OnPreRender() { //if the scene camera is about to render reset its transform to saved values if (camera && IsSceneViewCamera(camera)) { transform.position = pos; transform.rotation = rot; camera.nearClipPlane = near; camera.farClipPlane = far; camera.ResetProjectionMatrix(); } } #endif }<file_sep>/Assets/Scripts/ClassDamageData.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageData { // Attacker (self [a]) data public GameObject owner; public GameObject ownersCamera; public WeaponFire ownersWeaponFireScript; public Const.AttackType attackType; public bool isOtherNPC; public bool isFullAuto; public float damage; public float delayBetweenShots; public float penetration; public float offense; public float damageOverload; public float energyDrainLow; public float energyDrainHi; public float energyDrainOver; public float range; public bool berserkActive; // Attacked (other [o]) data public float armorvalue; public float defense; public GameObject other; public int indexNPC; public RaycastHit hit; public Vector3 attacknormal; public float impactVelocity; public void ResetDamageData (DamageData damageData) { damageData.owner = null; damageData.ownersCamera = null; damageData.ownersWeaponFireScript = null; damageData.other = null; damageData.attackType = Const.AttackType.None; damageData.isOtherNPC = false; damageData.isFullAuto = false; damageData.damage = 0f; damageData.delayBetweenShots = 0.8f; damageData.penetration = 0f; damageData.offense = 0f; damageData.damageOverload = 0f; damageData.energyDrainLow = 0f; damageData.energyDrainHi = 0f; damageData.energyDrainOver = 0f; damageData.range = 200f; damageData.berserkActive = false; damageData.armorvalue = 0f; damageData.defense = 0f; damageData.other = null; damageData.indexNPC = -1; damageData.hit = new RaycastHit(); damageData.attacknormal = Vector3.zero; damageData.impactVelocity = 0f; } } <file_sep>/Assets/Scripts/ExplosionForce.cs using UnityEngine; using System.Collections; public class ExplosionForce : MonoBehaviour { public float radius = 10f; public float power = 1000f; // Unity builtin // pos: center of sphere public void ExplodeInner(Vector3 pos, float oldforce, float oldradius, DamageData dd) { Collider[] colliders = Physics.OverlapSphere(pos, oldradius); foreach (Collider c in colliders) { if (c != null && c.GetComponent<Rigidbody>() != null) { c.GetComponent<Rigidbody>().AddExplosionForce(oldforce, pos, oldradius, 1.0f); if (dd != null) { HealthManager hm = c.gameObject.GetComponent<HealthManager>(); if (hm != null) hm.TakeDamage(dd); } } } } // Occlusion support // pos: center of sphere public void ExplodeOuter(Vector3 pos) { Collider[] colliders = Physics.OverlapSphere(pos, radius); foreach (Collider c in colliders) { if (c.GetComponent<Rigidbody>() == null) { continue; } Vector3 direction = c.transform.position - pos; Ray ray = new Ray(pos, direction); RaycastHit hit; // Raycast from explosion center to possible objective "c". if (!Physics.Raycast(ray, out hit, radius)) { continue; } // Raycast got direct hit with "c"? // - Yes: apply force // - No: ignore explosion force // TODO(by YOU): IMPORTANT Change this to match your problem!! if (!hit.collider.Equals(c) || !hit.transform.tag.Equals(c.tag)) { continue; } float distPenalty = Mathf.Pow((radius - hit.distance) / radius, 2); var force = direction * power * distPenalty; hit.rigidbody.AddForce(force); } } }<file_sep>/Assets/Scripts/Billboard.cs using UnityEngine; using System.Collections; public class Billboard : MonoBehaviour { public Camera mainCamera; private Vector3 tempDir; void Awake () { mainCamera = GetComponent<Camera> (); if (mainCamera == null) transform.gameObject.SetActive (false); } void Update (){ if (mainCamera.enabled == true) { tempDir = mainCamera.transform.forward; transform.rotation = Quaternion.LookRotation(-tempDir); } } public void DestroySprite() { Destroy(gameObject); } }<file_sep>/Assets/Scripts/WeaponShotsInventory.cs using UnityEngine; using UnityEngine.UI; using System.Collections; [System.Serializable] public class WeaponShotsInventory : MonoBehaviour { Text text; public int shotSlotnum = 0; void Start () { text = GetComponent<Text>(); } void Update () { text.text = WeaponShotsText.weaponShotsInventoryText[shotSlotnum]; if (shotSlotnum == WeaponCurrent.WepInstance.weaponCurrent) { text.color = Const.a.ssYellowText; // Yellow } else { text.color = Const.a.ssGreenText; // Green } } }<file_sep>/Assets/Scripts/PlayerHealth.cs using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections; public class PlayerHealth : MonoBehaviour { //public float health = 211f; //max is 255 public float radiated = 0f; public float resetAfterDeathTime = 0.5f; public float timer; public static bool playerDead = false; public bool mediPatchActive = false; public float mediPatchPulseTime = 1f; public float mediPatchHealAmount = 10f; public bool detoxPatchActive = false; public AudioSource PlayerNoise; public AudioClip PainSFXClip; public AudioClip RadiationClip; public GameObject cameraObject; public GameObject hardwareShield; public GameObject radiationEffect; private bool shieldOn = false; public bool radiationArea = false; private float radiationBleedOffFinished = 0f; public float radiationBleedOffTime = 1f; public float radiationReductionAmount = 1f; public float radiationHealthDamageRatio = 0.2f; public GameObject mainPlayerParent; public int radiationAmountWarningID = 323; public int radiationAreaWarningID = 322; public float mediPatchPulseFinished = 0f; public int mediPatchPulseCount = 0; public bool makingNoise = false; [HideInInspector] public HealthManager hm; public GameObject healingFXFlash; private float lastHealth; private float painSoundFinished; private float radSoundFinished; private float radFXFinished; private TextWarningsManager twm; void Awake () { twm = mainPlayerParent.GetComponent<PlayerReferenceManager>().playerTextWarningManager.GetComponent<TextWarningsManager>(); hm = GetComponent<HealthManager>(); if (hm == null) Debug.Log("BUG: No HealthManager script found on player!!"); painSoundFinished = Time.time; radSoundFinished = Time.time; radFXFinished = Time.time; lastHealth = hm.health; } void Update (){ if (PlayerNoise.isPlaying) makingNoise = true; else makingNoise = false; if (hm.health <= 0f) { if (!playerDead) { PlayerDying(); } else { PlayerDead(); } } if (mediPatchActive) { if (mediPatchPulseFinished == 0) mediPatchPulseCount = 0; if (mediPatchPulseFinished < Time.time) { float timePulse = mediPatchPulseTime; hm.health += mediPatchHealAmount; // give health //if (hm.health > hm.maxhealth) hm.health = hm.maxhealth; // handled by HealthManager.cs timePulse += (mediPatchPulseCount*0.5f); mediPatchPulseFinished = Time.time + timePulse; mediPatchPulseCount++; } } else { mediPatchPulseFinished = 0; mediPatchPulseCount = 0; } if (detoxPatchActive) { radiated = 0f; } if (radiated > 0) { if (radiationArea) twm.SendWarning(("Radiation Area"),0.1f,-2,TextWarningsManager.warningTextColor.white,radiationAreaWarningID); twm.SendWarning(("Radiation poisoning "+radiated.ToString()+" LBP"),0.1f,-2,TextWarningsManager.warningTextColor.red,radiationAmountWarningID); if (radFXFinished < Time.time) { radiationEffect.SetActive(true); radFXFinished = Time.time + Random.Range(0.4f,1f); } } if (radiated < 1) { radiationArea = false; } if (radiationBleedOffFinished < Time.time) { if (radiated > 0) { hm.health -= radiated*radiationHealthDamageRatio*radiationBleedOffTime; // apply health at rate of bleedoff time if (!radiationArea) { radiated -= radiationReductionAmount; // bleed off the radiation over time } else { if (radSoundFinished < Time.time) { radSoundFinished = Time.time + Random.Range(0.5f,1.5f); PlayerNoise.PlayOneShot(RadiationClip); } } radiationBleedOffFinished = Time.time + radiationBleedOffTime; } } // Did we lose health? if (lastHealth > hm.health) { if (painSoundFinished < Time.time && !(radSoundFinished < Time.time)) { painSoundFinished = Time.time + Random.Range(0.5f,1.5f); // Don't spam pain sounds PlayerNoise.PlayOneShot(PainSFXClip); } } lastHealth = hm.health; } void PlayerDying (){ timer += Time.deltaTime; if (timer >= resetAfterDeathTime) { hm.health = 0f; playerDead = true; } } void PlayerDead (){ //gameObject.GetComponent<PlayerMovement>().enabled = false; //cameraObject.SetActive(false); Cursor.lockState = CursorLockMode.None; #if UNITY_EDITOR if (Application.isEditor) { EditorApplication.isPlaying = false; return; } #endif cameraObject.GetComponent<Camera>().enabled = false; } public void TakeDamage (DamageData dd){ float shieldBlock = 0f; if (shieldOn) { //shieldBlock = hardwareShield.GetComponent<Shield>().GetShieldBlock(); } dd.armorvalue = shieldBlock; dd.defense = 0f; float take = Const.a.GetDamageTakeAmount(dd); hm.health -= take; PlayerNoise.PlayOneShot(PainSFXClip); //Debug.Log("Player Health: " + health.ToString()); } public void GiveRadiation (float rad) { if (radiated < rad) radiated = rad; //radiated -= suitReduction; } public void HealingBed(float amount) { hm.HealingBed(amount); if (healingFXFlash != null) { healingFXFlash.SetActive(true); } } }<file_sep>/Assets/Scripts/StartMenuDifficultyButton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class StartMenuDifficultyButton : MonoBehaviour { public GameObject[] otherControllers; public GameObject controller; public int difficultyValue; public void OnDiffButtonClick () { controller.GetComponent<StartMenuDifficultyController>().SetDifficulty(difficultyValue); controller.SendMessage("Highlight",SendMessageOptions.DontRequireReceiver); if (otherControllers.Length <= 0) return; for (int i=0; i<(otherControllers.Length-1);i++) { otherControllers[i].SendMessage("DeHighlight",SendMessageOptions.DontRequireReceiver); } } } <file_sep>/Assets/Scripts/WeaponInventory.cs using UnityEngine; using System.Collections; public class WeaponInventory : MonoBehaviour { public string[] weaponInventoryText; public int[] weaponInventoryIndices; public int[] weaponInventoryAmmoIndices; [SerializeField] public string[] weaponInvTextSource; public static WeaponInventory WepInventoryInstance; public bool[] weaponFound; public bool[] hasWeapon; void Awake() { WepInventoryInstance = this; WepInventoryInstance.weaponInventoryText = new string[]{"","","","","","",""};; WepInventoryInstance.weaponInventoryIndices = new int[]{-1,-1,-1,-1,-1,-1,-1}; WepInventoryInstance.weaponInventoryAmmoIndices = new int[]{-1,-1,-1,-1,-1,-1,-1}; } void Update() { for (int i=0;i<WeaponShotsText.weaponShotsInventoryText.Length;i++) { WeaponShotsText.weaponShotsInventoryText[i] = GetTextForWeaponAmmo(i); } } string GetTextForWeaponAmmo(int index) { int globalLookupIndex = weaponInventoryIndices[index]; string retval = "0"; switch (globalLookupIndex) { case 36: //Mark3 Assault Rifle retval = WeaponAmmo.a.wepAmmo[0].ToString() + "mg, " + WeaponAmmo.a.wepAmmoSecondary[0].ToString() + "pn"; break; case 37: //ER-90 Blaster if (WeaponAmmo.a.currentEnergyWeaponState [1] == WeaponAmmo.energyWeaponStates.Overheated) { retval = "OVERHEATED"; } else { retval = "READY"; } break; case 38: //SV-23 Dartgun retval = WeaponAmmo.a.wepAmmo[2].ToString() + "nd, " + WeaponAmmo.a.wepAmmoSecondary[2].ToString() + "tq"; break; case 39: //AM-27 Flechette retval = WeaponAmmo.a.wepAmmo[3].ToString() + "hn, " + WeaponAmmo.a.wepAmmoSecondary[3].ToString() + "sp"; break; case 40: //RW-45 Ion Beam if (WeaponAmmo.a.currentEnergyWeaponState [4] == WeaponAmmo.energyWeaponStates.Overheated) { retval = "OVERHEATED"; } else { retval = "READY"; } break; case 41: //TS-04 Laser Rapier retval = ""; break; case 42: //Lead Pipe retval = ""; break; case 43: //Magnum 2100 retval = WeaponAmmo.a.wepAmmo[7].ToString() + "hw, " + WeaponAmmo.a.wepAmmoSecondary[7].ToString() + "slg"; break; case 44: //SB-20 Magpulse retval = WeaponAmmo.a.wepAmmo[8].ToString() + "car, " + WeaponAmmo.a.wepAmmoSecondary[8].ToString() + "sup"; break; case 45: //ML-41 Pistol retval = WeaponAmmo.a.wepAmmo[9].ToString() + "st, " + WeaponAmmo.a.wepAmmoSecondary[9].ToString() + "tef"; break; case 46: //LG-XX Plasma Rifle if (WeaponAmmo.a.currentEnergyWeaponState [10] == WeaponAmmo.energyWeaponStates.Overheated) { retval = "OVERHEATED"; } else { retval = "READY"; } break; case 47: //MM-76 Railgun retval = WeaponAmmo.a.wepAmmo[11].ToString() + "rail"; break; case 48: //DC-05 Riotgun retval = WeaponAmmo.a.wepAmmo[12].ToString() + "rub"; break; case 49: //RF-07 Skorpion retval = WeaponAmmo.a.wepAmmo[13].ToString() + "sm, " + WeaponAmmo.a.wepAmmoSecondary[13].ToString() + "lg"; break; case 50: //Sparq Beam if (WeaponAmmo.a.currentEnergyWeaponState [14] == WeaponAmmo.energyWeaponStates.Overheated) { retval = "OVERHEATED"; } else { retval = "READY"; } break; case 51: //DH-07 Stungun if (WeaponAmmo.a.currentEnergyWeaponState [15] == WeaponAmmo.energyWeaponStates.Overheated) { retval = "OVERHEATED"; } else { retval = "READY"; } break; } return retval; } } <file_sep>/Assets/Scripts/SearchableItem.cs using UnityEngine; using System.Collections; public class SearchableItem : MonoBehaviour { [Tooltip("Use lookUp table instead of randomItem#'s for default random item generation, for example for NPCs")] public int lookUpIndex = 0; // For randomly generating items [Tooltip("The indices referring to the prefab in Const table to have inside this searchable")] public int[] contents = {-1,-1,-1,-1}; [Tooltip("Custom item indices of contents, for referring to specific attributes of content such as log type")] public int[] customIndex = {-1,-1,-1,-1}; [Tooltip("Whether to randomly generate search items based on randomItem# indices")] public bool generateContents = false; [Tooltip("Pick index from Const list of potential random item.")] public int[] randomItem; // possible item this container could contain if generateContents is true [Tooltip("Pick index from Const list of potential random item.")] public int[] randomItemCustomIndex; // possible item this container could contain if generateContents is true [Tooltip("Name of the searchable item.")] public string objectName; [Tooltip("Number of slots.")] public int numSlots = 4; [HideInInspector] public bool searchableInUse; [HideInInspector] public GameObject currentPlayerCapsule; private float disconnectDist; void Start () { disconnectDist = Const.a.frobDistance; } void Update () { if (searchableInUse) { if (Vector3.Distance(currentPlayerCapsule.transform.position, gameObject.transform.position) > disconnectDist) { searchableInUse = false; MFDManager.a.ClearDataTab(); } } } }<file_sep>/Assets/Scripts/Radiation.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Radiation : MonoBehaviour { public float intervalTime = 1f; public float radiationAmount = 11f; public float radFinished = 0f; public int numPlayers = 0; void OnTriggerEnter (Collider col) { if ((col.gameObject.tag == "Player") && (col.gameObject.GetComponent<PlayerHealth>().hm.health > 0f)) { numPlayers++; col.gameObject.GetComponent<PlayerHealth>().radiationArea = true; col.gameObject.SendMessage("GiveRadiation",radiationAmount,SendMessageOptions.DontRequireReceiver); radFinished = Time.time + (intervalTime); } } void OnTriggerStay (Collider col) { if ((col.gameObject.tag == "Player") && (col.gameObject.GetComponent<PlayerHealth>().hm.health > 0f) && (radFinished < Time.time)) { col.gameObject.GetComponent<PlayerHealth>().radiationArea = true; col.gameObject.SendMessage("GiveRadiation",radiationAmount,SendMessageOptions.DontRequireReceiver); radFinished = Time.time + (intervalTime); } } void OnTriggerExit (Collider col) { if ((col.gameObject.tag == "Player") && (col.gameObject.GetComponent<PlayerHealth>().hm.health > 0f)) { col.gameObject.GetComponent<PlayerHealth>().radiationArea = false; numPlayers--; if (numPlayers == 0) radFinished = Time.time; // reset so re-triggering is instant } } } <file_sep>/Assets/Scripts/LoadPageGetSaveNames.cs using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UI; public class LoadPageGetSaveNames : MonoBehaviour { public Text[] loadButtonText; void Awake () { string readline; // variable to hold each string read in from the file for (int i=0;i<8;i++) { StreamReader sf = new StreamReader(Application.streamingAssetsPath + "/sav"+i.ToString()+".txt"); if (sf != null) { using (sf) { readline = sf.ReadLine(); if (readline == null) break; // just in case loadButtonText[i].text = readline; sf.Close(); } } } } } <file_sep>/Assets/Scripts/LevelManager.cs using UnityEngine; using System.Collections; public class LevelManager : MonoBehaviour { public int currentLevel; public static LevelManager a; public GameObject[] levels; public int[] levelSecurity; //public GameObject currentPlayer; //public GameObject elevatorControl; public GameObject sky; void Awake () { a = this; //print("LevelManager Awake(): Current level: " + currentLevel); SetAllPlayersLevelsToCurrent(); DisableAllNonOccupiedLevels(); if (sky != null) sky.SetActive(true); Time.timeScale = Const.a.defaultTimeScale; } public void LoadLevel (int levnum, GameObject targetDestination, GameObject currentPlayer) { // NOTE: Check this first since the button for the current level has a null destination if (currentLevel == levnum) { Const.sprint("Already there",currentPlayer); // Do nothing return; } if (currentPlayer == null) { Const.sprint("BUG: LevelManager cannot find current player.",Const.a.allPlayers); return; // prevent possible error if keypad does not have player to move } if (targetDestination == null) { Const.sprint("BUG: LevelManager cannot find destination.",Const.a.allPlayers); return; // prevent possible error if keypad does not have destination set } MFDManager.a.TurnOffElevatorPad(); GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); currentPlayer.GetComponent<PlayerReferenceManager>().playerCapsule.transform.position = targetDestination.transform.position; // Put player in the new level levels[levnum].SetActive(true); // enable new level currentPlayer.GetComponent<PlayerReferenceManager>().playerCurrentLevel = levnum; if (levnum == 13) currentPlayer.GetComponent<PlayerReferenceManager> ().playerCapsule.GetComponent<PlayerMovement> ().inCyberSpace = true; currentLevel = levnum; // Set current level to be the new level DisableAllNonOccupiedLevels(); } public void LoadLevelFromSave (int levnum) { // NOTE: Check this first since the button for the current level has a null destination if (currentLevel == levnum) { return; } levels[levnum].SetActive(true); // Load new level levels[currentLevel].SetActive(false); // Unload current level currentLevel = levnum; // Set current level to be the new level } void SetAllPlayersLevelsToCurrent () { if (Const.a.player1 != null) { Const.a.player1.GetComponent<PlayerReferenceManager>().playerCurrentLevel = currentLevel; } if (Const.a.player2 != null) { Const.a.player2.GetComponent<PlayerReferenceManager>().playerCurrentLevel = currentLevel; } if (Const.a.player3 != null) { Const.a.player3.GetComponent<PlayerReferenceManager>().playerCurrentLevel = currentLevel; } if (Const.a.player4 != null) { Const.a.player4.GetComponent<PlayerReferenceManager>().playerCurrentLevel = currentLevel; } } void DisableAllNonOccupiedLevels() { int p1level = -1; int p2level = -1; int p3level = -1; int p4level = -1;; if (Const.a.player1 != null) p1level = Const.a.player1.GetComponent<PlayerReferenceManager>().playerCurrentLevel; if (Const.a.player2 != null) p2level = Const.a.player2.GetComponent<PlayerReferenceManager>().playerCurrentLevel; if (Const.a.player3 != null) p3level = Const.a.player3.GetComponent<PlayerReferenceManager>().playerCurrentLevel; if (Const.a.player4 != null) p4level = Const.a.player4.GetComponent<PlayerReferenceManager>().playerCurrentLevel; for (int i=0;i<levels.Length;i++) { if (p1level != i && p2level != i && p3level != i && p4level != i) levels[i].SetActive(false); else levels[i].SetActive(true); } } public GameObject GetCurrentLevelDynamicContainer() { GameObject retval = null; if (currentLevel < levels.Length) retval = levels[currentLevel].GetComponent<Level>().dynamicObjectsContainer; return retval; } public int GetCurrentLevelSecurity() { return levelSecurity [currentLevel]; } public void ReduceCurrentLevelSecurity(int secDrop) { levelSecurity [currentLevel] -= secDrop; if (levelSecurity [currentLevel] < 0) levelSecurity [currentLevel] = 0; // limit reduction in case of setup errors. Calculate your sec levels carefully!! } } <file_sep>/Assets/Scripts/Ladder.cs using UnityEngine; using System.Collections; public class Ladder : MonoBehaviour { GameObject other; void OnTriggerEnter (Collider other){ if (other.tag == "Player") { other.GetComponent<PlayerMovement>().ladderState = true; } } void OnTriggerExit (Collider other){ if (other.tag == "Player") { other.GetComponent<PlayerMovement>().ladderState = false; } } }<file_sep>/Assets/Scripts/WeaponFire.cs using UnityEngine; using System.Collections; public class WeaponFire : MonoBehaviour { [HideInInspector] public float waitTilNextFire = 0f; public float muzzleDistance = 0.10f; public float hitOffset = 0.2f; public float normalHitOffset = 0.2f; public float verticalOffset = -0.2f; // For laser beams public float fireDistance = 200f; public float hitscanDistance = 200f; public float meleescanDistance = 2.5f; public float overheatedPercent = 80f; public bool isAlternateAmmo = false; public bool berserkActive = false; public float magpulseShotForce = 2.20f; public float stungunShotForce = 1.92f; public float railgunShotForce = 2.60f; public float plasmaShotForce = 1.50f; [HideInInspector] public float[] args; public GameObject bullet; public GameObject impactEffect; public WeaponMagazineCounter wepmagCounter; public Camera playerCamera; // assign in the editor public PlayerMovement playerMovement; // assign in editor public Camera gunCamera; // assign in the editor public PlayerEnergy curEnergy; public GameObject playerCapsule; public WeaponCurrent currentWeapon; // assign in the editor public EnergyOverloadButton energoverButton; public EnergyHeatTickManager energheatMgr; public GameObject bulletHoleTiny; public GameObject bulletHoleSmall; public GameObject bulletHoleSpread; public GameObject bulletHoleLarge; public GameObject bulletHoleScorchSmall; public GameObject bulletHoleScorchLarge; [SerializeField] private AudioSource SFX = null; // assign in the editor [SerializeField] private AudioClip SFXMark3Fire; // assign in the editor [SerializeField] private AudioClip SFXBlasterFire; // assign in the editor //[SerializeField] private AudioClip SFXBlasterOverFire; // assign in the editor [SerializeField] private AudioClip SFXDartFire; // assign in the editor [SerializeField] private AudioClip SFXFlechetteFire; // assign in the editor [SerializeField] private AudioClip SFXIonFire; // assign in the editor //[SerializeField] private AudioClip SFXIonOverFire; // assign in the editor [SerializeField] private AudioClip SFXRapierMiss; // assign in the editor [SerializeField] private AudioClip SFXRapierHit; // assign in the editor [SerializeField] private AudioClip SFXPipeMiss; // assign in the editor [SerializeField] private AudioClip SFXPipeHit; // assign in the editor [SerializeField] private AudioClip SFXPipeHitFlesh; // assign in the editor [SerializeField] private AudioClip SFXMagnumFire; // assign in the editor [SerializeField] private AudioClip SFXMagpulseFire; // assign in the editor [SerializeField] private AudioClip SFXPistolFire; // assign in the editor [SerializeField] private AudioClip SFXPlasmaFire; // assign in the editor [SerializeField] private AudioClip SFXRailgunFire; // assign in the editor [SerializeField] private AudioClip SFXRiotgunFire; // assign in the editor [SerializeField] private AudioClip SFXSkorpionFire; // assign in the editor [SerializeField] private AudioClip SFXSparqBeamFire; // assign in the editor //[SerializeField] private AudioClip SFXSparqBeamOverFire; // assign in the editor [SerializeField] private AudioClip SFXStungunFire; // assign in the editor [SerializeField] private AudioClip SFXEmpty; // assign in the editor [SerializeField] private AudioClip SFXRicochet; // assign in the editor public bool overloadEnabled; public float sparqHeat; public float ionHeat; public float blasterHeat; public float stungunHeat; public float plasmaHeat; public float sparqSetting; public float ionSetting; public float blasterSetting; public float plasmaSetting; public float stungunSetting; private float clipEnd; public Animator anim; // assign in the editor public DamageData damageData; private RaycastHit tempHit; private Vector3 tempVec; private bool useBlood; private HealthManager tempHM; private float retval; private float heatTickFinished; private float heatTickTime = 0.50f; public GameObject muzFlashMK3; public GameObject muzFlashBlaster; public GameObject muzFlashDartgun; public GameObject muzFlashFlechette; public GameObject muzFlashIonBeam; public GameObject muzFlashMagnum; public GameObject muzFlashPistol; public GameObject muzFlashMagpulse; public GameObject muzFlashPlasma; public GameObject muzFlashRailgun; public GameObject muzFlashRiotgun; public GameObject muzFlashSkorpion; public GameObject muzFlashSparq; public GameObject muzFlashStungun; // Recoil the weapon view models public GameObject wepView; private Vector3 wepViewDefaultLocalPos; [SerializeField] private bool recoiling; void Awake() { damageData = new DamageData(); tempHit = new RaycastHit(); tempVec = new Vector3(0f, 0f, 0f); heatTickFinished = Time.time + heatTickTime; wepViewDefaultLocalPos = wepView.transform.localPosition; } void GetWeaponData(int index) { if (index == -1) return; damageData.isFullAuto = Const.a.isFullAutoForWeapon[index]; if (currentWeapon.weaponIsAlternateAmmo) { damageData.damage = Const.a.damagePerHitForWeapon2[index]; damageData.delayBetweenShots = Const.a.delayBetweenShotsForWeapon2[index]; damageData.penetration = Const.a.penetrationForWeapon2[index]; damageData.offense = Const.a.offenseForWeapon2[index]; } else { damageData.damage = Const.a.damagePerHitForWeapon[index]; damageData.delayBetweenShots = Const.a.delayBetweenShotsForWeapon[index]; damageData.penetration = Const.a.penetrationForWeapon[index]; damageData.offense = Const.a.offenseForWeapon[index]; } damageData.damageOverload = Const.a.damageOverloadForWeapon[index]; damageData.energyDrainLow = Const.a.energyDrainLowForWeapon[index]; damageData.energyDrainHi = Const.a.energyDrainHiForWeapon[index]; damageData.energyDrainOver = Const.a.energyDrainOverloadForWeapon[index]; damageData.range = Const.a.rangeForWeapon[index]; damageData.attackType = Const.a.attackTypeForWeapon[index]; damageData.berserkActive = berserkActive; } public static int Get16WeaponIndexFromConstIndex(int index) { int i = -1; switch (index) { case 36: //Mark3 Assault Rifle i = 0; break; case 37: //ER-90 Blaster i = 1; break; case 38: //SV-23 Dartgun i = 2; break; case 39: //AM-27 Flechette i = 3; break; case 40: //RW-45 Ion Beam i = 4; break; case 41: //TS-04 Laser Rapier i = 5; break; case 42: //Lead Pipe i = 6; break; case 43: //Magnum 2100 i = 7; break; case 44: //SB-20 Magpulse i = 8; break; case 45: //ML-41 Pistol i = 9; break; case 46: //LG-XX Plasma Rifle i = 10; break; case 47: //MM-76 Railgun i = 11; break; case 48: //DC-05 Riotgun i = 12; break; case 49: //RF-07 Skorpion i = 13; break; case 50: //Sparq Beam i = 14; break; case 51: //DH-07 Stungun i = 15; break; } return i; } bool CurrentWeaponUsesEnergy () { if (currentWeapon.weaponIndex == 37 || currentWeapon.weaponIndex == 40 || currentWeapon.weaponIndex == 46 || currentWeapon.weaponIndex == 50 || currentWeapon.weaponIndex == 51) return true; return false; } bool WeaponsHaveAnyHeat() { if (ionHeat > 0) return true; if (plasmaHeat > 0) return true; if (sparqHeat > 0) return true; if (stungunHeat > 0) return true; if (blasterHeat > 0) return true; return false; } void HeatBleedOff() { if (heatTickFinished < Time.time) { ionHeat -= 10f; if (ionHeat < 0) ionHeat = 0; blasterHeat -= 10f; if (blasterHeat < 0) blasterHeat = 0; sparqHeat -= 10f; if (sparqHeat < 0) sparqHeat = 0; stungunHeat -= 10f; if (stungunHeat < 0) stungunHeat = 0; plasmaHeat -= 10f; if (plasmaHeat < 0) plasmaHeat = 0; if (CurrentWeaponUsesEnergy()) energheatMgr.HeatBleed(GetHeatForCurrentWeapon()); // update hud heat ticks if current weapon uses energy heatTickFinished = Time.time + heatTickTime; } } public void Recoil (int i) { float strength = Const.a.recoilForWeapon[i]; //Debug.Log("Recoil from gun index: "+i.ToString()+" with strength of " +strength.ToString()); if (strength <= 0f) return; if (playerMovement.fatigue > 80) strength = strength * 2f; strength = strength * 0.25f; Vector3 wepJoltPosition = new Vector3(wepView.transform.localPosition.x, wepView.transform.localPosition.y, (wepViewDefaultLocalPos.z - strength)); wepView.transform.localPosition = wepJoltPosition; recoiling = true; } void Update() { if (!PauseScript.a.paused) { if (WeaponsHaveAnyHeat()) HeatBleedOff(); // Slowly cool off any weapons that have been heated from firing if (recoiling) { float x = wepView.transform.localPosition.x; // side to side float y = wepView.transform.localPosition.y; // up and down float z = wepView.transform.localPosition.z; // forward and back z = Mathf.Lerp(z,wepViewDefaultLocalPos.z,Time.deltaTime); wepView.transform.localPosition = new Vector3(x,y,z); } if (!GUIState.a.isBlocking && !playerCamera.GetComponent<MouseLookScript>().holdingObject) { int i = Get16WeaponIndexFromConstIndex(currentWeapon.weaponIndex); if (i == -1) return; GetWeaponData(i); if (GetInput.a.Attack(Const.a.isFullAutoForWeapon[i]) && waitTilNextFire < Time.time) { // Check weapon type and check ammo before firing if (i == 5 || i == 6) { // Pipe or Laser Rapier, attack without prejudice FireWeapon(i, false); // weapon index, isSilent == false so play normal SFX } else { // Energy weapons so check energy level if (i == 1 || i == 4 || i == 10 || i == 14 || i == 15) { // Even if we have only 1 energy, we still fire with all we've got up to the energy level setting of course if (curEnergy.energy > 0) { if (GetHeatForCurrentWeapon() > overheatedPercent) { SFX.PlayOneShot(SFXEmpty); waitTilNextFire = Time.time + 0.8f; Const.sprint("Weapon is too hot to fire",Const.a.allPlayers); } else { FireWeapon(i, false); // weapon index, isSilent == false so play normal SFX } } } else { // Uses normal ammo, check versus alternate or normal to see if we have ammo then fire if (currentWeapon.weaponIsAlternateAmmo) { if (WeaponCurrent.WepInstance.currentMagazineAmount2[i] > 0) { FireWeapon(i, false); // weapon index, isSilent == false so play normal SFX } else { SFX.PlayOneShot(SFXEmpty); waitTilNextFire = Time.time + 0.8f; } } else { if (WeaponCurrent.WepInstance.currentMagazineAmount[i] > 0) { FireWeapon(i, false); // weapon index, isSilent == false so play normal SFX } else { SFX.PlayOneShot(SFXEmpty); waitTilNextFire = Time.time + 0.8f; } } } } } if (GetInput.a.Reload()) { WeaponCurrent.WepInstance.Reload(); } } } } // index is used to get recoil down at the bottom and pass along ref for damageData, // otherwise the cases use currentWeapon.weaponIndex void FireWeapon(int index, bool isSilent) { damageData.ResetDamageData(damageData); switch (currentWeapon.weaponIndex) { case 36: //Mark3 Assault Rifle if (!isSilent) { SFX.clip = SFXMark3Fire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashMK3.SetActive(true); break; case 37: //ER-90 Blaster if (!isSilent) { SFX.clip = SFXBlasterFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashBlaster.SetActive(true); if (overloadEnabled) { blasterHeat = 100f; } else { blasterHeat += blasterSetting; } if (blasterHeat > 100f) blasterHeat = 100f; break; case 38: //SV-23 Dartgun if (!isSilent) { SFX.clip = SFXDartFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashDartgun.SetActive(true); break; case 39: //AM-27 Flechette if (!isSilent) { SFX.clip = SFXFlechetteFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashFlechette.SetActive(true); break; case 40: //RW-45 Ion Beam if (!isSilent) { SFX.clip = SFXIonFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashIonBeam.SetActive(true); if (overloadEnabled) { ionHeat = 100f; } else { ionHeat += ionSetting; } if (ionHeat > 100f) ionHeat = 100f; break; case 41: //TS-04 Laser Rapier FireRapier(index, isSilent); break; case 42: //Lead Pipe FirePipe(index, isSilent); break; case 43: //Magnum 2100 if (!isSilent) { SFX.clip = SFXMagnumFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashMagnum.SetActive(true); break; case 44: //SB-20 Magpulse if (!isSilent) { SFX.clip = SFXMagpulseFire; SFX.Play(); } FireMagpulse(index); muzFlashMagpulse.SetActive(true); break; case 45: //ML-41 Pistol if (!isSilent) { SFX.clip = SFXPistolFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashPistol.SetActive(true); break; case 46: //LG-XX Plasma Rifle if (!isSilent) { SFX.clip = SFXPlasmaFire; SFX.Play(); } FirePlasma(index); muzFlashPlasma.SetActive(true); plasmaHeat += plasmaSetting; if (plasmaHeat > 100f) plasmaHeat = 100f; break; case 47: //MM-76 Railgun if (!isSilent) { SFX.clip = SFXRailgunFire; SFX.Play(); } FireRailgun(index); muzFlashRailgun.SetActive(true); break; case 48: //DC-05 Riotgun if (!isSilent) { SFX.clip = SFXRiotgunFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashRiotgun.SetActive(true); break; case 49: //RF-07 Skorpion if (!isSilent) { SFX.clip = SFXSkorpionFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashSkorpion.SetActive(true); break; case 50: //Sparq Beam if (!isSilent) { SFX.clip = SFXSparqBeamFire; SFX.Play(); } if (DidRayHit()) HitScanFire(index); muzFlashSparq.SetActive(true); if (overloadEnabled) { sparqHeat = 100f; } else { sparqHeat += sparqSetting; } if (sparqHeat > 100f) sparqHeat = 100f; break; case 51: //DH-07 Stungun if (!isSilent) { SFX.clip = SFXStungunFire; SFX.Play(); } FireStungun(index); muzFlashStungun.SetActive(true); stungunHeat += stungunSetting; if (stungunHeat > 100f) stungunHeat = 100f; break; } // TAKE AMMO // no weapons subtract more than 1 at a time in a shot, subtracting 1 // Check weapon type before subtracting ammo or energy if (index == 5 || index == 6) { // Pipe or Laser Rapier // ammo is already 0, do nothing. This is here to prevent subtracting ammo on the first slot of .wepAmmo[index] on the last else clause below } else { // Energy weapons so check energy level if (index == 1 || index == 4 || index == 10 || index == 14 || index == 15) { if (overloadEnabled) { energoverButton.OverloadFired(); curEnergy.TakeEnergy(Const.a.energyDrainOverloadForWeapon[index]); //take large amount } else { float takeEnerg = (currentWeapon.weaponEnergySetting[index] / 100f) * (Const.a.energyDrainHiForWeapon[index] - Const.a.energyDrainLowForWeapon[index]); curEnergy.TakeEnergy(takeEnerg); } } else { if (currentWeapon.weaponIsAlternateAmmo) { WeaponCurrent.WepInstance.currentMagazineAmount2[index]--; // Update the counter MFDManager.a.UpdateHUDAmmoCounts(WeaponCurrent.WepInstance.currentMagazineAmount2[index]); } else { WeaponCurrent.WepInstance.currentMagazineAmount[index]--; // Update the counter MFDManager.a.UpdateHUDAmmoCounts(WeaponCurrent.WepInstance.currentMagazineAmount[index]); } } } playerCamera.GetComponent<MouseLookScript>().Recoil(index); Recoil(index); if (currentWeapon.weaponIsAlternateAmmo || overloadEnabled) { overloadEnabled = false; waitTilNextFire = Time.time + Const.a.delayBetweenShotsForWeapon2[index]; } else { waitTilNextFire = Time.time + Const.a.delayBetweenShotsForWeapon[index]; } } bool DidRayHit() { tempHit = new RaycastHit(); tempVec = new Vector3(MouseCursor.drawTexture.x + (MouseCursor.drawTexture.width / 2), MouseCursor.drawTexture.y + (MouseCursor.drawTexture.height / 2) + verticalOffset, 0); tempVec.y = Screen.height - tempVec.y; // Flip it. Rect uses y=0 UL corner, ScreenPointToRay uses y=0 LL corner int layMask = LayerMask.GetMask("Default","Water","Geometry","NPC","Corpse"); //TODO: Can't shoot players, but we can't shoot the back of our eyeballs now if (Physics.Raycast(playerCamera.ScreenPointToRay(tempVec), out tempHit, fireDistance,layMask)) { tempHM = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (tempHit.transform.gameObject.GetComponent<HealthManager>() != null) { useBlood = true; } return true; } return false; } GameObject GetImpactType(HealthManager hm) { if (hm == null) return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); switch (hm.bloodType) { case HealthManager.BloodType.None: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); case HealthManager.BloodType.Red: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmall); case HealthManager.BloodType.Yellow: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallYellow); case HealthManager.BloodType.Green: return Const.a.GetObjectFromPool(Const.PoolType.BloodSpurtSmallGreen); case HealthManager.BloodType.Robot: return Const.a.GetObjectFromPool(Const.PoolType.SparksSmallBlue); } return Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); } void CreateStandardImpactMarks(int wep16index) { // Add bullethole tempVec = tempHit.normal * 0.16f; GameObject holetype = bulletHoleSmall; switch(wep16index) { case 0: holetype = bulletHoleLarge; break; case 1: holetype = bulletHoleScorchSmall; break; case 2: holetype = bulletHoleTiny; break; case 3: holetype = bulletHoleSmall; break; case 4: holetype = bulletHoleScorchLarge; break; case 5: holetype = bulletHoleScorchSmall; break; case 6: return; // no impact marks for lead pipe...actually doesn't even call this function case 7: holetype = bulletHoleLarge; break; case 8: holetype = bulletHoleScorchLarge; break; case 9: holetype = bulletHoleSmall; break; case 10: holetype = bulletHoleScorchLarge; break; case 11: holetype = bulletHoleScorchLarge; break; case 12: holetype = bulletHoleSpread; break; case 13: holetype = bulletHoleLarge; break; case 14: holetype = bulletHoleScorchSmall; break; case 15: holetype = bulletHoleScorchSmall; break; } GameObject impactMark = (GameObject) Instantiate(holetype, (tempHit.point + tempVec), Quaternion.LookRotation(tempHit.normal*-1,Vector3.up), tempHit.transform.gameObject.transform); int rint = Random.Range(0,3); Quaternion roll = impactMark.transform.localRotation; roll *= Quaternion.Euler(0f,0f,rint * 90f); impactMark.transform.localRotation = roll; } void CreateStandardImpactEffects(bool onlyBloodIfHitHasHM) { // Determine blood type of hit target and spawn corresponding blood particle effect from the Const.Pool if (useBlood) { GameObject impact = GetImpactType(tempHM); if (impact != null) { tempVec = tempHit.normal * hitOffset; impact.transform.position = tempHit.point + tempVec; impact.transform.rotation = Quaternion.FromToRotation(Vector3.up, tempHit.normal); impact.SetActive(true); } } else { // Allow for skipping adding sparks after special override impact effects per attack functions below if (!onlyBloodIfHitHasHM) { GameObject impact = Const.a.GetObjectFromPool(Const.PoolType.SparksSmall); //Didn't hit an object with a HealthManager script, use sparks if (impact != null) { tempVec = tempHit.normal * hitOffset; impact.transform.position = tempHit.point + tempVec; impact.transform.rotation = Quaternion.FromToRotation(Vector3.up, tempHit.normal); impact.SetActive(true); } } } } void CreateBeamImpactEffects(int wep16index) { GameObject impact = Const.a.GetObjectFromPool(Const.PoolType.SparqImpacts); if (wep16index == 1) { impact = Const.a.GetObjectFromPool(Const.PoolType.BlasterImpacts); //Red laser for blaster } else { if (wep16index == 4) { impact = Const.a.GetObjectFromPool(Const.PoolType.IonImpacts); // Yellow laser for ion } } if (impact != null) { impact.transform.position = tempHit.point; impact.transform.rotation = Quaternion.FromToRotation(Vector3.up, tempHit.normal); impact.SetActive(true); } } void CreateBeamEffects(int wep16index) { GameObject lasertracer = Const.a.GetObjectFromPool(Const.PoolType.LaserLines); // Turquoise/Pale-Teal for sparq if (wep16index == 1) { lasertracer = Const.a.GetObjectFromPool(Const.PoolType.LaserLinesBlaster); //Red laser for blaster } else { if (wep16index == 4) { lasertracer = Const.a.GetObjectFromPool(Const.PoolType.LaserLinesIon); // Yellow laser for ion } } if (lasertracer != null) { tempVec = transform.position; tempVec.y += verticalOffset; lasertracer.GetComponent<LaserDrawing>().startPoint = tempVec; lasertracer.GetComponent<LaserDrawing>().endPoint = tempHit.point; lasertracer.SetActive(true); } } // dmg_min is Const.a.damagePerHitForWeapon[wep16Index], dmg_max is Const.a.damagePerHitForWeapon2[wep16Index] float DamageForPower(int wep16Index) { float retval, dmg_min, dmg_max, ener_min, ener_max; // overload overrides current setting and uses overload damage if (overloadEnabled) { retval = Const.a.damageOverloadForWeapon[wep16Index]; return retval; } dmg_min = Const.a.damagePerHitForWeapon[wep16Index]; dmg_max = Const.a.damagePerHitForWeapon2[wep16Index]; ener_min = Const.a.energyDrainLowForWeapon[wep16Index]; ener_max = Const.a.energyDrainHiForWeapon[wep16Index]; // Calculates damage based on min and max values and applies a curve of the slopes based on the linear plotting of the slope from min at min to max at max // Right then, the beautifully ugly formula: retval = ((currentWeapon.weaponEnergySetting[wep16Index]/100f)*((dmg_max/ener_max)-(dmg_min/ener_min)) + 3f) * (((currentWeapon.weaponEnergySetting[wep16Index])/100f)*(ener_max-ener_min) + ener_min); return retval; // You gotta love maths! There is a spreadsheet for this (.ods LibreOffice file format, found with src code) that shows the calculations to make this dmg curve. } // WEAPON FIRING CODE: // ============================================================================================================================== // Hitscan Weapons //---------------------------------------------------------------------------------------------------------- // Guns and laser beams, used by most weapons void HitScanFire(int wep16Index) { if (wep16Index == 1 || wep16Index == 4 || wep16Index == 14) { CreateBeamImpactEffects(wep16Index); // laser burst effect overrides standard blood spurts/robot sparks CreateStandardImpactMarks(wep16Index); damageData.attackType = Const.AttackType.EnergyBeam; } else { CreateStandardImpactEffects(false); // standard blood spurts/robot sparks CreateStandardImpactMarks(wep16Index); damageData.attackType = Const.AttackType.Projectile; } // Fill the damageData container damageData.other = tempHit.transform.gameObject; if (tempHit.transform.gameObject.tag == "NPC") { damageData.isOtherNPC = true; } else { damageData.isOtherNPC = false; } damageData.hit = tempHit; damageData.attacknormal = playerCamera.ScreenPointToRay(MouseCursor.drawTexture.center).direction; if (currentWeapon.weaponIsAlternateAmmo) { damageData.damage = Const.a.damagePerHitForWeapon2[wep16Index]; } else { if (CurrentWeaponUsesEnergy()) { damageData.damage = DamageForPower(wep16Index); } else { damageData.damage = Const.a.damagePerHitForWeapon[wep16Index]; } } damageData.damage = Const.a.GetDamageTakeAmount(damageData); damageData.owner = playerCapsule; HealthManager hm = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (hm != null) hm.TakeDamage(damageData); // send the damageData container to HealthManager of hit object and apply damage // Draw a laser beam for beam weapons if (wep16Index == 1 || wep16Index == 4 || wep16Index == 14) { CreateBeamEffects(wep16Index); } } // Melee weapons //---------------------------------------------------------------------------------------------------------- // Rapier and pipe. Need extra code to handle anims for view model and sound for swing-and-a-miss! vs. hit void FireRapier(int index16, bool silent) { fireDistance = meleescanDistance; if (DidRayHit()) { anim.Play("Attack2"); if (!silent) { SFX.clip = SFXPipeHit; SFX.Play(); } CreateStandardImpactEffects(true); CreateStandardImpactMarks(index16); damageData.other = tempHit.transform.gameObject; if (tempHit.transform.gameObject.tag == "NPC") { damageData.isOtherNPC = true; } else { damageData.isOtherNPC = false; } damageData.hit = tempHit; damageData.attacknormal = playerCamera.ScreenPointToRay(MouseCursor.drawTexture.center).direction; damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.damage = Const.a.GetDamageTakeAmount(damageData); damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Melee; HealthManager hm = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (hm == null) return; hm.TakeDamage(damageData); return; } fireDistance = hitscanDistance; if (!silent) { SFX.clip = SFXRapierMiss; SFX.Play(); } anim.Play("Attack1"); } void FirePipe(int index16, bool silent) { fireDistance = meleescanDistance; if (DidRayHit()) { anim.Play("Attack2"); if (!silent) { SFX.clip = SFXPipeHit; SFX.Play(); } CreateStandardImpactEffects(true); damageData.other = tempHit.transform.gameObject; if (tempHit.transform.gameObject.tag == "NPC") { damageData.isOtherNPC = true; } else { damageData.isOtherNPC = false; } damageData.hit = tempHit; damageData.attacknormal = playerCamera.ScreenPointToRay(MouseCursor.drawTexture.center).direction; damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.damage = Const.a.GetDamageTakeAmount(damageData); damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Melee; HealthManager hm = tempHit.transform.gameObject.GetComponent<HealthManager>(); if (hm == null) return; hm.TakeDamage(damageData); return; } fireDistance = hitscanDistance; if (!silent) { SFX.clip = SFXPipeMiss; SFX.Play(); } anim.Play("Attack1"); } // Projectile weapons //---------------------------------------------------------------------------------------------------------- void FirePlasma(int index16) { // Create and hurl a beachball-like object. On the developer commentary they said that the projectiles act GameObject beachball = Const.a.GetObjectFromPool(Const.PoolType.PlasmaShots); //TODO: Create correct projectils if (beachball != null) { damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Projectile; beachball.GetComponent<ProjectileEffectImpact>().dd = damageData; beachball.GetComponent<ProjectileEffectImpact>().host = playerCapsule; beachball.transform.position = playerCamera.transform.position; tempVec = playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint - playerCamera.transform.position; beachball.transform.forward = tempVec.normalized; //drawMyLine(beachball.transform.position, playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint, Color.green, 2f); beachball.SetActive(true); Vector3 shove = beachball.transform.forward * plasmaShotForce; beachball.GetComponent<Rigidbody>().velocity = Vector3.zero; // prevent random variation from the last shot's velocity beachball.GetComponent<Rigidbody>().AddForce(shove, ForceMode.Impulse); } } void FireRailgun(int index16) { // Create and hurl a beachball-like object. On the developer commentary they said that the projectiles act GameObject beachball = Const.a.GetObjectFromPool(Const.PoolType.RailgunShots); //TODO: Create correct projectils if (beachball != null) { damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Projectile; beachball.GetComponent<ProjectileEffectImpact>().dd = damageData; beachball.GetComponent<ProjectileEffectImpact>().host = playerCapsule; beachball.transform.position = playerCamera.transform.position; tempVec = playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint - playerCamera.transform.position; beachball.transform.forward = tempVec.normalized; //drawMyLine(beachball.transform.position, playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint, Color.green, 2f); beachball.SetActive(true); Vector3 shove = beachball.transform.forward * railgunShotForce; beachball.GetComponent<Rigidbody>().velocity = Vector3.zero; // prevent random variation from the last shot's velocity beachball.GetComponent<Rigidbody>().AddForce(shove, ForceMode.Impulse); } } void FireStungun(int index16) { // Create and hurl a beachball-like object. On the developer commentary they said that the projectiles act GameObject beachball = Const.a.GetObjectFromPool(Const.PoolType.StungunShots); //TODO: Create correct projectils if (beachball != null) { damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Projectile; beachball.GetComponent<ProjectileEffectImpact>().dd = damageData; beachball.GetComponent<ProjectileEffectImpact>().host = playerCapsule; beachball.transform.position = playerCamera.transform.position; tempVec = playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint - playerCamera.transform.position; beachball.transform.forward = tempVec.normalized; //drawMyLine(beachball.transform.position, playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint, Color.green, 2f); beachball.SetActive(true); Vector3 shove = beachball.transform.forward * stungunShotForce; beachball.GetComponent<Rigidbody>().velocity = Vector3.zero; // prevent random variation from the last shot's velocity beachball.GetComponent<Rigidbody>().AddForce(shove, ForceMode.Impulse); } } public Vector3 ScreenPointToDirectionVector() { Vector3 retval = Vector3.zero; retval = playerCamera.transform.forward; return retval; } void FireMagpulse(int index16) { // Create and hurl a beachball-like object. On the developer commentary they said that the projectiles act // like a beachball for collisions with enemies, but act like a baseball for walls/floor to prevent hitting corners GameObject beachball = Const.a.GetObjectFromPool(Const.PoolType.MagpulseShots); //TODO: Create correct projectils if (beachball != null) { damageData.damage = Const.a.damagePerHitForWeapon[index16]; damageData.owner = playerCapsule; damageData.attackType = Const.AttackType.Magnetic; beachball.GetComponent<ProjectileEffectImpact>().dd = damageData; beachball.GetComponent<ProjectileEffectImpact>().host = playerCapsule; beachball.transform.position = playerCamera.transform.position; tempVec = playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint - playerCamera.transform.position; beachball.transform.forward = tempVec.normalized; //drawMyLine(beachball.transform.position, playerCamera.GetComponent<MouseLookScript>().cameraFocusPoint, Color.green, 2f); beachball.SetActive(true); Vector3 shove = beachball.transform.forward * magpulseShotForce; beachball.GetComponent<Rigidbody>().velocity = Vector3.zero; // prevent random variation from the last shot's velocity beachball.GetComponent<Rigidbody>().AddForce(shove, ForceMode.Impulse); } } public float GetHeatForCurrentWeapon() { retval = 0f; switch (currentWeapon.weaponIndex) { case 37: retval = blasterHeat; break; case 40: retval = ionHeat; break; case 46: retval = plasmaHeat; break; case 50: retval = sparqHeat; break; case 51: retval = stungunHeat; break; default: retval = 0f; break; } if (retval > 100f) Const.sprint("BUG: Weapon heat greater than 100", Const.a.allPlayers); if (retval < 0) Const.sprint("BUG: Weapon heat less than 0", Const.a.allPlayers); return retval; } void drawMyLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f) { StartCoroutine(drawLine(start, end, color, duration)); } IEnumerator drawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f) { GameObject myLine = new GameObject(); myLine.transform.position = start; myLine.AddComponent<LineRenderer>(); LineRenderer lr = myLine.GetComponent<LineRenderer>(); lr.material = new Material(Shader.Find("Particles/Additive")); lr.startColor = color; lr.endColor = color; lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.SetPosition(0, start); lr.SetPosition(1, end); yield return new WaitForSeconds(duration); GameObject.Destroy(myLine); } }<file_sep>/Assets/Scripts/ButtonSwitch.cs using UnityEngine; using System.Collections; public class ButtonSwitch : MonoBehaviour { public int securityThreshhold = 100; // if security level is not below this level, this is unusable public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; public string message; public float delay = 0f; public Material mainSwitchMaterial; public Material alternateSwitchMaterial; public AudioClip SFX; public float tickTime = 1.5f; public bool active; public bool blinkWhenActive; public bool changeMatOnActive = true; private float delayFinished; private float tickFinished; private GameObject player; private AudioSource SFXSource; private bool alternateOn; private MeshRenderer mRenderer; void Awake () { SFXSource = GetComponent<AudioSource>(); mRenderer = GetComponent<MeshRenderer>(); delayFinished = 0; // prevent using targets on awake } public void Use (UseData ud) { if (LevelManager.a.levelSecurity[LevelManager.a.currentLevel] > securityThreshhold) { MFDManager.a.BlockedBySecurity(); return; } player = ud.owner; // set playerCamera to owner of the input (always should be the player camera) SFXSource.PlayOneShot(SFX); if (message != null && message != "") Const.sprint(message,ud.owner); if (delay > 0) { delayFinished = Time.time + delay; } else { UseTargets(); } } public void UseTargets () { UseData ud = new UseData(); ud.owner = player; if (target != null) { target.SendMessageUpwards("Targetted", ud); } if (target1 != null) { target1.SendMessageUpwards("Targetted", ud); } if (target2 != null) { target2.SendMessageUpwards("Targetted", ud); } if (target3 != null) { target3.SendMessageUpwards("Targetted", ud); } active = !active; alternateOn = active; if (changeMatOnActive) { if (blinkWhenActive) { ToggleMaterial (); if (active) tickFinished = Time.time + tickTime; } else { ToggleMaterial (); } } } void ToggleMaterial() { if (alternateOn) mRenderer.material = alternateSwitchMaterial; else mRenderer.material = mainSwitchMaterial; } void Update () { if ((delayFinished < Time.time) && delayFinished != 0) { delayFinished = 0; UseTargets(); } // blink the switch when active if (blinkWhenActive) { if (active) { if (tickFinished < Time.time) { if (alternateOn) { mRenderer.material = mainSwitchMaterial; } else { mRenderer.material = alternateSwitchMaterial; } alternateOn = !alternateOn; tickFinished = Time.time + tickTime; } } } } } <file_sep>/Assets/Scripts/PainStaticFX.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PainStaticFX : MonoBehaviour { public float lifetime = 0.1f; private float effectFinished; void OnEnable () { effectFinished = Time.time + lifetime; } // Update is called once per frame void Update () { if (effectFinished < Time.time) Deactivate(); } void Deactivate () { gameObject.SetActive(false); } } <file_sep>/Assets/Scripts/AmmoControl.cs using UnityEngine; using System.Collections; public class AmmoControl : MonoBehaviour { public GameObject noAmmoIcon; public GameObject curcntDigitOnes; public GameObject curcntDigitTens; public GameObject curcntDigitHuns; public float currentAmmo; } <file_sep>/Assets/Scripts/SecurityCameraRotate.cs using UnityEngine; using System.Collections; // For security cameras public class SecurityCameraRotate : MonoBehaviour { public float startYAngle = 0f; public float endYAngle = 180f; public float degreesYPerSecond = 5f; public float waitTime = 0.8f; private float waitingTime = 0f; private bool rotatePositive; private float tickTime = 0.1f; void Awake () { waitingTime = Time.time; rotatePositive = true; } void Update () { if (waitingTime < Time.time) { if (rotatePositive) { RotatePositive(); } else { RotateNegative(); } } } void RotatePositive () { if (((transform.rotation.eulerAngles.y + 1f) >= endYAngle) && ((transform.rotation.eulerAngles.y - 1f) <= endYAngle)) { rotatePositive = false; waitingTime = Time.time + waitTime; return; } transform.Rotate(new Vector3(0,degreesYPerSecond * tickTime,0),Space.World); } void RotateNegative () { if (((transform.rotation.eulerAngles.y + 1f) >= startYAngle) && ((transform.rotation.eulerAngles.y - 1f) <= startYAngle)) { rotatePositive = true; waitingTime = Time.time + waitTime; return; } transform.Rotate(new Vector3(0,degreesYPerSecond * tickTime * -1,0),Space.World); } } <file_sep>/Assets/Scripts/PuzzleGridPuzzle.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PuzzleGridPuzzle : MonoBehaviour { public int securityThreshhold = 100; // if security level is not below this level, this is unusable public bool dead = false; public bool[] grid; public PuzzleGrid.CellType[] cellType; public PuzzleGrid.GridType gridType; public int sourceIndex; public int outputIndex; public int width; public int height; public PuzzleGrid.GridColorTheme theme; public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; public void Use (UseData ud) { if (dead) { Const.sprint("Can't use broken panel",ud.owner); return; } if (LevelManager.a.levelSecurity[LevelManager.a.currentLevel] > securityThreshhold) { MFDManager.a.BlockedBySecurity(); return; } Const.sprint("Puzzle interface accessed",ud.owner); //(bool[] states, CellType[] types, GridType gtype, int start, int end, GridColorTheme colors, UseData ud) MFDManager.a.SendGridPuzzleToDataTab(grid,cellType,gridType,sourceIndex,outputIndex,width,height,theme,target,target1,target2,target3,ud); } } <file_sep>/Assets/Scripts/WeaponAmmo.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class WeaponAmmo : MonoBehaviour { public int[] wepAmmo; public int[] wepAmmoSecondary; public enum energyWeaponStates {Ready,Overheated}; public energyWeaponStates[] currentEnergyWeaponState; public static WeaponAmmo a; void Awake () { int i; a = this; for (i= 0; i<16; i++) { a.wepAmmo[i] = 0; a.wepAmmoSecondary[i] = 0; a.currentEnergyWeaponState[i] = energyWeaponStates.Ready; } } } <file_sep>/Assets/Scripts/PlayerEnergy.cs using UnityEngine; using System.Collections; public class PlayerEnergy : MonoBehaviour { public float energy = 54f; //max is 255 public float resetAfterDeathTime = 0.5f; public float timer; private AudioSource SFX; public AudioClip SFXBatteryUse; public AudioClip SFXChargeStationUse; public void Awake() { SFX = GetComponent<AudioSource>(); } public void TakeEnergy ( float take ){ energy -= take; if (energy <= 0f) energy = 0f; //print("Player Energy: " + energy.ToString()); } public void GiveEnergy (float give, int type) { energy += give; if (energy > 255f) { energy = 255f; } if (type == 0) { if (SFX != null) SFX.PlayOneShot(SFXBatteryUse); // battery sound } if (type == 1) { if (SFX != null) SFX.PlayOneShot(SFXChargeStationUse); // charging station sound } } }<file_sep>/Assets/Scripts/TriggerCounter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerCounter : MonoBehaviour { public int countToTrigger; public int counter; public GameObject[] target; public float[] delay; public bool dontReset; private float[] delayFinished; private bool[] delayStarted; void Awake() { // Check and set delays array to equal the target array if (delay.Length < target.Length) { float[] tempDelays = delay; // temporarily store the delays delay = new float[target.Length]; // wipe out array with new larger array same size as the targets for (int j = 0; j < target.Length; j++) { if (j >= tempDelays.Length) { delay [j] = 0; continue; } delay [j] = tempDelays [j]; // put values back } } // Set delayFinished and delayStarted array to equal the target array length before zeroing out delayFinished = new float[target.Length]; delayStarted = new bool[target.Length]; // zero out the private arrays for the delay time keepers for (int i = 0; i < target.Length; i++) { delayStarted [i] = false; delayFinished [i] = Time.time; } } public void Targetted (UseData ud) { counter++; if (counter == countToTrigger) { Target (); } } void Target() { if (!dontReset) counter = 0; UseData ud = new UseData(); ud.owner = Const.a.allPlayers; // TODO: should we have a different Const.a.nullPlayer? for (int i = 0; i < target.Length; i++) { if (delay [i] > 0) { delayStarted [i] = true; // tell Update() to check the timekeeper to see if we are past the delay delayFinished[i] = Time.time + delay [i]; // set delay timekeeper } else { if (target [i] != null) { target [i].SendMessageUpwards ("Targetted", ud); } } } } void Update () { for (int i = 0; i < target.Length; i++) { if (delayStarted [i]) { if (delayFinished[i] < Time.time) { UseData ud = new UseData(); ud.owner = Const.a.allPlayers; // TODO: should we have a different Const.a.nullPlayer? delayStarted [i] = false; // reset bit so we don't keep triggering every frame if (target[i] != null) { target[i].SendMessageUpwards ("Targetted", ud); // fire in the hole } } } } } } <file_sep>/Assets/Scripts/HealthTickManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class HealthTickManager : MonoBehaviour { public GameObject playerObject; public PlayerHealth playerHealth; public GameObject[] healthTicks; public Sprite[] tickImages; private Image tickImage; private int tempSpriteIndex; private float lasthealth; void Awake () { tickImage = GetComponent<Image>(); } void Update (){ if (lasthealth != playerHealth.hm.health) DrawTicks(); lasthealth = playerHealth.hm.health; // reason why this script can't be combined with energy ticks script } void DrawTicks() { tempSpriteIndex = -1; int step = 0; while (step < 256) { if (playerHealth.hm.health < (256 - step)) { tempSpriteIndex++; } step += 11; } //Debug.Log(tempSpriteIndex.ToString()); if (tempSpriteIndex >= 0 && tempSpriteIndex < 24) { tickImage.overrideSprite = tickImages[tempSpriteIndex]; } /* int h = 0; int tickcnt = 0; // Clear health ticks for (int i=0;i<24;i++) { healthTicks[i].SetActive(false); } // Keep drawing ticks out until playerHealth is met while (h < playerHealth.hm.health) { healthTicks[tickcnt].SetActive(true); tickcnt++; h = h + 11; } */ } }<file_sep>/Assets/Scripts/StartMenuButtonHighlight.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class StartMenuButtonHighlight : MonoBehaviour { public MenuArrowKeyControls pageController; public int menuItemIndex; public Text text; public Shadow textshadow; public Color lit; public Color dark; public Color darkshadow; public Color litshadow; void DeHighlight () { if (textshadow != null) textshadow.effectColor = darkshadow; if (text != null) text.color = dark; } void Highlight () { if (textshadow != null) textshadow.effectColor = litshadow; if (text != null) text.color = lit; } public void CursorHighlight () { Highlight(); pageController.SetIndex(menuItemIndex); } public void CursorDeHighlight () { DeHighlight(); pageController.currentIndex = 0; } } <file_sep>/Assets/Scripts/GrenadeButton.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class GrenadeButton : MonoBehaviour { public int GrenButtonIndex; public GameObject playerCamera; public int useableItemIndex; public MFDManager mfdManager; private int itemLookup; private Texture2D cursorTexture; private Vector2 cursorHotspot; public GrenadeInventory playerGrenInv; public GrenadeCurrent playerGrenCurrent; public void PtrEnter () { GUIState.a.PtrHandler(true,true,GUIState.ButtonType.Grenade,gameObject); playerCamera.GetComponent<MouseLookScript>().currentButton = gameObject; } public void PtrExit () { GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } void DoubleClick() { // Subtract one from grenade inventory switch(useableItemIndex) { case 7: playerGrenInv.grenAmmo[0]--; break; // Frag case 8: playerGrenInv.grenAmmo[3]--; break; // Concussion case 9: playerGrenInv.grenAmmo[1]--; break; // EMP case 10: playerGrenInv.grenAmmo[6]--; break; // Earth Shaker case 11: playerGrenInv.grenAmmo[4]--; break; // Land Mine case 12: playerGrenInv.grenAmmo[5]--; break; // Nitropak case 13: playerGrenInv.grenAmmo[2]--; break; // Gas } // Put grenade in the player's hand (cursor) playerCamera.GetComponent<MouseLookScript>().UseGrenade(useableItemIndex); } void GrenadeInvClick () { mfdManager.SendInfoToItemTab(useableItemIndex); GrenadeCurrent.GrenadeInstance.grenadeCurrent = GrenButtonIndex; //Set current } void Start() { GetComponent<Button>().onClick.AddListener(() => { GrenadeInvClick();}); } }<file_sep>/Assets/Scripts/KeypadKeycode.cs using UnityEngine; using System.Collections; public class KeypadKeycode : MonoBehaviour { public int securityThreshhold = 100; // if security level is not below this level, this is unusable public DataTab dataTabResetter; public GameObject keypadControl; public int keycode; // the access code public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; public AudioClip SFX; private float disconnectDist; private AudioSource SFXSource; private bool padInUse = false; private GameObject playerCamera; private GameObject playerCapsule; void Start () { padInUse = false; disconnectDist = Const.a.frobDistance; SFXSource = GetComponent<AudioSource>(); } public void Use (UseData ud) { if (LevelManager.a.levelSecurity[LevelManager.a.currentLevel] > securityThreshhold) { Const.sprint("Blocked by SHODAN level Security.",ud.owner); MFDManager.a.BlockedBySecurity(); return; } padInUse = true; SFXSource.PlayOneShot(SFX); dataTabResetter.Reset(); keypadControl.SetActive(true); keypadControl.GetComponent<KeypadKeycodeButtons>().keycode = keycode; keypadControl.GetComponent<KeypadKeycodeButtons>().keypad = this; playerCamera = ud.owner.GetComponent<PlayerReferenceManager>().playerCapsuleMainCamera; playerCapsule = ud.owner.GetComponent<PlayerReferenceManager>().playerCapsule; // Get player capsule of player using this pad playerCamera.GetComponent<MouseLookScript>().ForceInventoryMode(); MFDManager.a.OpenTab(4,true,MFDManager.TabMSG.Keypad,0,MFDManager.handedness.LeftHand); } public void UseTargets () { UseData ud = new UseData(); ud.owner = playerCamera; if (target != null) { target.SendMessageUpwards("Targetted", ud); } if (target1 != null) { target1.SendMessageUpwards("Targetted", ud); } if (target2 != null) { target2.SendMessageUpwards("Targetted", ud); } if (target3 != null) { target3.SendMessageUpwards("Targetted", ud); } } void Update () { if (padInUse) { if (Vector3.Distance(playerCapsule.transform.position, gameObject.transform.position) > disconnectDist) { padInUse = false; MFDManager.a.TurnOffKeypad(); //keypadControl.SetActive(false); } } } } <file_sep>/Assets/Scripts/SearchButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class SearchButton : MonoBehaviour { public DataTab dataTabController; public TabButtons tabButtonController; public MouseLookScript playerCamera; public int[] contents; public int[] customIndex; public int j; void Awake () { for (int i=0;i<=3;i++) { contents[i] = -1; customIndex[i] = -1; } } public void CheckForEmpty () { j = 0; for (int i=0;i<=3;i++) { if (contents[i] == -1) j++; } if (j == 4) { tabButtonController.ReturnToLastTab(); } } public void SearchButtonClick (int buttonIndex) { switch (buttonIndex) { case 0: playerCamera.mouseCursor.GetComponent<MouseCursor>().cursorImage = Const.a.useableItemsFrobIcons[contents[0]]; playerCamera.heldObjectIndex = contents[0]; playerCamera.currentSearchItem.GetComponent<SearchableItem>().contents[0] = -1; playerCamera.currentSearchItem.GetComponent<SearchableItem>().customIndex[0] = -1; playerCamera.holdingObject = true; contents[0] = -1; customIndex[0] = -1; dataTabController.searchItemImages[0].SetActive(false); CheckForEmpty(); break; case 1: playerCamera.mouseCursor.GetComponent<MouseCursor>().cursorImage = Const.a.useableItemsFrobIcons[contents[1]]; playerCamera.heldObjectIndex = contents[1]; playerCamera.currentSearchItem.GetComponent<SearchableItem>().contents[1] = -1; playerCamera.currentSearchItem.GetComponent<SearchableItem>().customIndex[1] = -1; playerCamera.holdingObject = true; contents[1] = -1; customIndex[1] = -1; dataTabController.searchItemImages[1].SetActive(false); CheckForEmpty(); break; case 2: playerCamera.mouseCursor.GetComponent<MouseCursor>().cursorImage = Const.a.useableItemsFrobIcons[contents[2]]; playerCamera.heldObjectIndex = contents[2]; playerCamera.currentSearchItem.GetComponent<SearchableItem>().contents[2] = -1; playerCamera.currentSearchItem.GetComponent<SearchableItem>().customIndex[2] = -1; playerCamera.holdingObject = true; contents[2] = -1; customIndex[2] = -1; dataTabController.searchItemImages[2].SetActive(false); CheckForEmpty(); break; case 3: playerCamera.mouseCursor.GetComponent<MouseCursor>().cursorImage = Const.a.useableItemsFrobIcons[contents[3]]; playerCamera.heldObjectIndex = contents[3]; playerCamera.currentSearchItem.GetComponent<SearchableItem>().contents[3] = -1; playerCamera.currentSearchItem.GetComponent<SearchableItem>().customIndex[3] = -1; playerCamera.holdingObject = true; contents[3] = -1; customIndex[3] = -1; dataTabController.searchItemImages[3].SetActive(false); CheckForEmpty(); break; } GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); } } <file_sep>/Assets/Scripts/GrenadeProximity.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GrenadeProximity : MonoBehaviour { public GrenadeActivate ga; void OnTriggerEnter(Collider col) { if (col.transform.gameObject.tag == "NPC" || col.transform.gameObject.tag == "Player") { ga.proxSensed = true; } } void OnTriggerExit(Collider col) { ga.proxSensed = false; } } <file_sep>/Assets/Scripts/PlayerReferenceManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerReferenceManager : MonoBehaviour { public GameObject playerCapsule; public GameObject playerCapsuleHardwareLantern; public GameObject playerCapsuleHardwareEReader; public GameObject playerCapsuleMainCamera; public GameObject playerCapsuleMainCameraWeaponController; public GameObject playerCapsuleMainCameraGunCamera; public GameObject playerInventory; public GameObject playerCanvas; public GameObject playerCursor; public GameObject playerStatusBar; public GameObject playerTextWarningManager; public CenterTabButtons playerCenterTabButtonsControl; public int playerCurrentLevel; } <file_sep>/Assets/Scripts/MFDManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class MFDManager : MonoBehaviour { public TabButtons leftTC; public TabButtons rightTC; public ItemTabManager itemTabLH; public ItemTabManager itemTabRH; public enum handedness {LeftHand,RightHand}; public DataTab dataTabLH; public DataTab dataTabRH; public bool lastWeaponSideRH; public bool lastItemSideRH; public bool lastAutomapSideRH; public bool lastTargetSideRH; public bool lastDataSideRH; public bool lastSearchSideRH; public bool lastLogSideRH; public bool lastLogSecondarySideRH; public bool lastMinigameSideRH; public GameObject SearchFXRH; public GameObject SearchFXLH; public enum TabMSG {None,Search,AudioLog,Keypad,Elevator,GridPuzzle,WirePuzzle,EReader}; public static MFDManager a; public MouseLookScript playerMLook; private bool isRH; // External to gameObject, assigned in Inspector public WeaponMagazineCounter wepmagCounterLH; public WeaponMagazineCounter wepmagCounterRH; public GameObject logReaderContainer; public GameObject multiMediaTab; public void Awake () { a = this; } public void OpenTab(int index, bool overrideToggling,TabMSG type,int intdata1, handedness side) { if (side == handedness.LeftHand) { isRH = false; } else { isRH = true; } switch (index) { case 0: isRH = lastWeaponSideRH; break; case 1: isRH = lastItemSideRH; break; case 2: isRH = lastAutomapSideRH; break; case 3: isRH = lastTargetSideRH; break; case 4: isRH = lastDataSideRH; break; } if(!isRH) { // RH MFD leftTC.TabButtonClickSilent(index,overrideToggling); leftTC.SetCurrentAsLast(); if (type == TabMSG.AudioLog) { dataTabLH.Reset(); dataTabLH.audioLogContainer.SetActive(true); dataTabLH.audioLogContainer.GetComponent<LogDataTabContainerManager>().SendLogData(intdata1); } if (type == TabMSG.Keypad) { dataTabLH.Reset(); dataTabLH.keycodeUIControl.SetActive(true); playerMLook.ForceInventoryMode(); } if (type == TabMSG.Elevator) { dataTabLH.Reset(); dataTabLH.elevatorUIControl.SetActive(true); playerMLook.ForceInventoryMode(); } if (type == TabMSG.GridPuzzle) { dataTabLH.Reset(); dataTabLH.puzzleGrid.SetActive(true); playerMLook.ForceInventoryMode(); } if (type == TabMSG.EReader) { //itemTabLH.Reset(); itemTabLH.EReaderSectionSContainerOpen(); playerMLook.ForceInventoryMode(); } } else { // LH MFD rightTC.TabButtonClickSilent(index,overrideToggling); rightTC.SetCurrentAsLast(); if (type == TabMSG.AudioLog) { dataTabRH.Reset(); dataTabRH.audioLogContainer.SetActive(true); dataTabRH.audioLogContainer.GetComponent<LogDataTabContainerManager>().SendLogData(intdata1); } if (type == TabMSG.Keypad) { dataTabRH.Reset(); dataTabRH.keycodeUIControl.SetActive(true); } if (type == TabMSG.Elevator) { dataTabRH.Reset(); dataTabRH.elevatorUIControl.SetActive(true); } if (type == TabMSG.GridPuzzle) { dataTabLH.Reset(); dataTabLH.puzzleGrid.SetActive(true); } if (type == TabMSG.EReader) { //itemTabRH.Reset(); itemTabRH.EReaderSectionSContainerOpen(); } } } public void SendInfoToItemTab(int index) { if (itemTabRH != null) itemTabRH.SendItemDataToItemTab(index); if (itemTabLH != null) itemTabLH.SendItemDataToItemTab(index); } public void SendSearchToDataTab (string name, int contentCount, int[] resultContents, int[] resultsIndices) { // Enable search box scaling effect if (lastSearchSideRH) { dataTabRH.Reset(); dataTabRH.Search(name,contentCount,resultContents,resultsIndices); OpenTab(4,true,TabMSG.Search,0,handedness.RightHand); SearchFXRH.SetActive(true); } else { dataTabLH.Reset(); dataTabLH.Search(name,contentCount,resultContents,resultsIndices); OpenTab(4,true,TabMSG.Search,0,handedness.LeftHand); SearchFXLH.SetActive(true); } } public void SendGridPuzzleToDataTab (bool[] states, PuzzleGrid.CellType[] types, PuzzleGrid.GridType gtype, int start, int end, int width, int height, PuzzleGrid.GridColorTheme colors, GameObject t1, GameObject t2, GameObject t3, GameObject t4, UseData ud) { if (lastDataSideRH) { // Send to RH tab dataTabRH.Reset(); dataTabRH.GridPuzzle(states,types,gtype,start,end, width, height,colors,t1,t2,t3,t4,ud); OpenTab(4,true,TabMSG.GridPuzzle,0,handedness.RightHand); SearchFXRH.SetActive(true); } else { // Send to LH tab dataTabLH.Reset(); dataTabLH.GridPuzzle(states,types,gtype,start,end, width, height,colors,t1,t2,t3,t4,ud); OpenTab(4,true,TabMSG.GridPuzzle,0,handedness.LeftHand); SearchFXLH.SetActive(true); } } public void SendPaperLogToDataTab(int index) { if (lastDataSideRH) { // Send to RH tab dataTabRH.Reset(); OpenTab(4,true,TabMSG.AudioLog,index,handedness.RightHand); SearchFXRH.SetActive(true); } else { // Send to LH tab dataTabLH.Reset(); OpenTab(4,true,TabMSG.AudioLog,index,handedness.LeftHand); SearchFXLH.SetActive(true); } multiMediaTab.GetComponent<MultiMediaTabManager>().OpenLogTextReader(); logReaderContainer.GetComponent<LogTextReaderManager>().SendTextToReader(index); } public void SendAudioLogToDataTab(int index) { if (lastDataSideRH) { // Send to RH tab dataTabRH.Reset(); OpenTab(4,true,TabMSG.AudioLog,index,handedness.RightHand); } else { // Send to LH tab dataTabLH.Reset(); OpenTab(4,true,TabMSG.AudioLog,index,handedness.LeftHand); } multiMediaTab.GetComponent<MultiMediaTabManager>().OpenLogTextReader(); logReaderContainer.GetComponent<LogTextReaderManager>().SendTextToReader(index); } public void OpenEReaderInItemsTab() { if (lastItemSideRH) { itemTabRH.Reset(); OpenTab(1,true,TabMSG.EReader,-1,handedness.RightHand); } else { itemTabLH.Reset(); OpenTab(1,true,TabMSG.EReader,-1,handedness.LeftHand); } } public void ClearDataTab() { if (lastDataSideRH) { dataTabRH.Reset(); } else { dataTabLH.Reset(); } } public void TurnOffKeypad() { if (lastDataSideRH) { dataTabRH.keycodeUIControl.SetActive(false); } else { dataTabLH.keycodeUIControl.SetActive(false); } } public void TurnOffElevatorPad() { if (lastDataSideRH) { dataTabRH.elevatorUIControl.SetActive(false); } else { dataTabLH.elevatorUIControl.SetActive(false); } } public bool GetElevatorControlActiveState() { if (lastDataSideRH) { return dataTabRH.elevatorUIControl.activeInHierarchy; } else { return dataTabLH.elevatorUIControl.activeInHierarchy; } } public void BlockedBySecurity() { if (lastDataSideRH) { dataTabRH.blockedBySecurity.SetActive(true); } else { dataTabLH.blockedBySecurity.SetActive(true); } } public void UpdateHUDAmmoCounts(int amount) { if (wepmagCounterLH != null) wepmagCounterLH.UpdateDigits(amount); if (wepmagCounterRH != null) wepmagCounterRH.UpdateDigits(amount); } }<file_sep>/Assets/Scripts/RigidBodyKeepAwakeScript.cs using UnityEngine; using System.Collections; public class RigidBodyKeepAwakeScript : MonoBehaviour { private Rigidbody rbody; void Awake () { rbody = GetComponent<Rigidbody>(); } void FixedUpdate () { if (rbody != null && PauseScript.a != null && !PauseScript.a.paused) rbody.WakeUp(); } } <file_sep>/Assets/Scripts/WeaponCurrent.cs using UnityEngine; using System.Collections; public class WeaponCurrent : MonoBehaviour { [SerializeField] public int weaponCurrent = new int(); [SerializeField] public int weaponIndex = new int(); [SerializeField] public bool weaponIsAlternateAmmo = new bool(); public float[] weaponEnergySetting; public int[] currentMagazineAmount; public int[] currentMagazineAmount2; public static WeaponCurrent WepInstance; public WeaponMagazineCounter wepmagCounter; public GameObject ammoIndicatorHuns; public GameObject ammoIndicatorTens; public GameObject ammoIndicatorOnes; public GameObject ViewModelAssault; public GameObject ViewModelBlaster; public GameObject ViewModelDartgun; public GameObject ViewModelFlechette; public GameObject ViewModelIon; public GameObject ViewModelRapier; public GameObject ViewModelPipe; public GameObject ViewModelMagnum; public GameObject ViewModelMagpulse; public GameObject ViewModelPistol; public GameObject ViewModelPlasma; public GameObject ViewModelRailgun; public GameObject ViewModelRiotgun; public GameObject ViewModelSkorpion; public GameObject ViewModelSparq; public GameObject ViewModelStungun; public GameObject owner; private bool justChangedWeap = true; private int lastIndex = 0; private AudioSource SFX; public AudioClip ReloadSFX; public AudioClip ReloadInStyleSFX; void Awake() { WepInstance = this; WepInstance.weaponCurrent = 0; // Current slot in the weapon inventory (7 slots) WepInstance.weaponIndex = 0; // Current index to the weapon look-up tables WepInstance.weaponIsAlternateAmmo = false; WepInstance.SFX = GetComponent<AudioSource> (); // Put energy settings to lowest energy level as default for (int i=0;i<16;i++) { WepInstance.weaponEnergySetting [i] = 0f; // zero out ones we don't use WepInstance.currentMagazineAmount[i] = 0; WepInstance.currentMagazineAmount2[i] = 0; } //Default power settings WepInstance.weaponEnergySetting [1] = 3f; // Blaster WepInstance.weaponEnergySetting [4] = 5f; // Ion Beam WepInstance.weaponEnergySetting [10] = 13f; // Plasma rifle WepInstance.weaponEnergySetting [14] = 2f; // Sparq Beam WepInstance.weaponEnergySetting [15] = 3f; // Stungun } void Update() { if (justChangedWeap) { justChangedWeap = false; if (ViewModelAssault != null) ViewModelAssault.SetActive(false); if (ViewModelBlaster != null) ViewModelBlaster.SetActive(false); if (ViewModelDartgun != null) ViewModelDartgun.SetActive(false); if (ViewModelFlechette != null) ViewModelFlechette.SetActive(false); if (ViewModelIon != null) ViewModelIon.SetActive(false); if (ViewModelRapier != null) ViewModelRapier.SetActive(false); if (ViewModelPipe != null) ViewModelPipe.SetActive(false); if (ViewModelMagnum != null) ViewModelMagnum.SetActive(false); if (ViewModelMagpulse != null) ViewModelMagpulse.SetActive(false); if (ViewModelPistol != null) ViewModelPistol.SetActive(false); if (ViewModelPlasma != null) ViewModelPlasma.SetActive(false); if (ViewModelRailgun != null) ViewModelRailgun.SetActive(false); if (ViewModelRiotgun != null) ViewModelRiotgun.SetActive(false); if (ViewModelSkorpion != null) ViewModelSkorpion.SetActive(false); if (ViewModelSparq != null) ViewModelSparq.SetActive(false); if (ViewModelStungun != null) ViewModelStungun.SetActive(false); } if (lastIndex != weaponIndex) { justChangedWeap = true; lastIndex = weaponIndex; } ammoIndicatorHuns.SetActive(true); ammoIndicatorTens.SetActive(true); ammoIndicatorOnes.SetActive(true); switch (weaponIndex) { case 36: ViewModelAssault.SetActive(true); break; case 37: ViewModelBlaster.SetActive(true); break; case 38: ViewModelDartgun.SetActive(true); break; case 39: ViewModelFlechette.SetActive(true); break; case 40: ViewModelIon.SetActive(true); break; case 41: ViewModelRapier.SetActive(true); ammoIndicatorHuns.SetActive(false); ammoIndicatorTens.SetActive(false); ammoIndicatorOnes.SetActive(false); break; case 42: ViewModelPipe.SetActive(true); ammoIndicatorHuns.SetActive(false); ammoIndicatorTens.SetActive(false); ammoIndicatorOnes.SetActive(false); break; case 43: ViewModelMagnum.SetActive(true); break; case 44: ViewModelMagpulse.SetActive(true); break; case 45: ViewModelPistol.SetActive(true); break; case 46: ViewModelPlasma.SetActive(true); break; case 47: ViewModelRailgun.SetActive(true); break; case 48: ViewModelRiotgun.SetActive(true); break; case 49: ViewModelSkorpion.SetActive(true); break; case 50: ViewModelSparq.SetActive(true); break; case 51: ViewModelStungun.SetActive(true); break; } } public void ChangeAmmoType() { if (weaponIsAlternateAmmo) { weaponIsAlternateAmmo = false; Unload(true); LoadPrimaryAmmoType(false); } else { weaponIsAlternateAmmo = true; Unload(true); LoadSecondaryAmmoType(false); } } public void LoadPrimaryAmmoType(bool isSilent) { int wep16index = WeaponFire.Get16WeaponIndexFromConstIndex (weaponIndex); // Put bullets into the magazine if (WeaponAmmo.a.wepAmmo[wep16index] >= Const.a.magazinePitchCountForWeapon[wep16index]) { currentMagazineAmount[wep16index] = Const.a.magazinePitchCountForWeapon[wep16index]; } else { currentMagazineAmount[wep16index] = WeaponAmmo.a.wepAmmo[wep16index]; } // Take bullets out of the ammo stockpile WeaponAmmo.a.wepAmmo[wep16index] -= currentMagazineAmount[wep16index]; if (!isSilent) { if (wep16index == 0 || wep16index == 3) { SFX.PlayOneShot (ReloadInStyleSFX); } else { SFX.PlayOneShot (ReloadSFX); } } // Update the counter on the HUD MFDManager.a.UpdateHUDAmmoCounts(currentMagazineAmount[wep16index]); } public void LoadSecondaryAmmoType(bool isSilent) { int wep16index = WeaponFire.Get16WeaponIndexFromConstIndex (weaponIndex); // Put bullets into the magazine if (WeaponAmmo.a.wepAmmoSecondary[wep16index] >= Const.a.magazinePitchCountForWeapon2[wep16index]) { currentMagazineAmount2[wep16index] = Const.a.magazinePitchCountForWeapon2[wep16index]; } else { currentMagazineAmount2[wep16index] = WeaponAmmo.a.wepAmmoSecondary[wep16index]; } // Take bullets out of the ammo stockpile WeaponAmmo.a.wepAmmoSecondary[wep16index] -= currentMagazineAmount2[wep16index]; if (!isSilent) { if (wep16index == 0 || wep16index == 3) { SFX.PlayOneShot (ReloadInStyleSFX); } else { SFX.PlayOneShot (ReloadSFX); } } // Update the counter on the HUD MFDManager.a.UpdateHUDAmmoCounts(currentMagazineAmount[wep16index]); } public void Unload(bool isSilent) { int wep16index = WeaponFire.Get16WeaponIndexFromConstIndex (weaponIndex); // Take bullets out of the clip, put them back into the ammo stockpile, then zero out the clip amount, did I say clip? I mean magazine but whatever if (weaponIsAlternateAmmo) { WeaponAmmo.a.wepAmmoSecondary[wep16index] += currentMagazineAmount2[wep16index]; currentMagazineAmount2[wep16index] = 0; } else { WeaponAmmo.a.wepAmmo[wep16index] += currentMagazineAmount[wep16index]; currentMagazineAmount[wep16index] = 0; } if (!isSilent) SFX.PlayOneShot (ReloadSFX); // Update the counter on the HUD MFDManager.a.UpdateHUDAmmoCounts(currentMagazineAmount[wep16index]); } public void Reload() { int wep16index = WeaponFire.Get16WeaponIndexFromConstIndex (weaponIndex); if (weaponIsAlternateAmmo) { if (currentMagazineAmount2[wep16index] == Const.a.magazinePitchCountForWeapon2[wep16index]) { Const.sprint("Current weapon magazine already full.",owner); return; } if (WeaponAmmo.a.wepAmmoSecondary[wep16index] <= 0) { Const.sprint("No more of current ammo type to load.",owner); return; } Unload(true); LoadSecondaryAmmoType(false); } else { if (currentMagazineAmount[wep16index] == Const.a.magazinePitchCountForWeapon[wep16index]) { Const.sprint("Current weapon magazine already full.",owner); return; } if (WeaponAmmo.a.wepAmmo[wep16index] <= 0) { Const.sprint("No more of current ammo type to load.",owner); return; } Unload(true); LoadPrimaryAmmoType(false); } } }<file_sep>/Assets/Scripts/WeaponButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class WeaponButton : MonoBehaviour { public GameObject playerCamera; public int useableItemIndex; public int WepButtonIndex; [SerializeField] private GameObject iconman; [SerializeField] private MFDManager mfdManager; [SerializeField] private GameObject ammoiconman; [SerializeField] private GameObject weptextman; [SerializeField] private AudioSource SFX = null; // assign in the editor [SerializeField] private AudioClip SFXClip = null; // assign in the editor private int invslot; private bool alternateAmmo = false; public void WeaponInvClick () { invslot = WeaponInventory.WepInventoryInstance.weaponInventoryIndices[WepButtonIndex]; if (invslot >= 0) ammoiconman.GetComponent<AmmoIconManager>().SetAmmoIcon(invslot, alternateAmmo); SFX.PlayOneShot(SFXClip); iconman.GetComponent<WeaponIconManager>().SetWepIcon(useableItemIndex); //Set weapon icon for MFD weptextman.GetComponent<WeaponTextManager>().SetWepText(useableItemIndex); //Set weapon text for MFD mfdManager.SendInfoToItemTab(useableItemIndex); WeaponCurrent.WepInstance.weaponCurrent = WepButtonIndex; //Set current weapon WeaponCurrent.WepInstance.weaponIndex = useableItemIndex; //Set current weapon } void Start() { GetComponent<Button>().onClick.AddListener(() => { WeaponInvClick();}); } } <file_sep>/Assets/Scripts/Unused/DataReaderTextLoader.cs using UnityEngine; using System.Collections; public class DataReaderTextLoader : MonoBehaviour { public const string path = "AudioLogs"; // Use this for initialization void Start () { Debug.Log ("Script started"); DataReaderTextContainer drtc = DataReaderTextContainer.Load (path); foreach (Log audioLog in drtc.audioLogs) { print(audioLog.name); print (audioLog.LogContent); Debug.Log ("Okay..."); } } // Update is called once per frame void Update () { } }<file_sep>/Assets/Scripts/PooledItemDestroy.cs using UnityEngine; using System.Collections; public class PooledItemDestroy : MonoBehaviour { public float itemLifeTime = 3.00f; void OnEnable () { StartCoroutine(DestroyBackToPool()); } IEnumerator DestroyBackToPool () { yield return new WaitForSeconds(itemLifeTime); gameObject.SetActive(false); } } <file_sep>/Assets/Scripts/PatchCurrent.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class PatchCurrent : MonoBehaviour { [SerializeField] public int patchCurrent = new int(); [SerializeField] public int patchIndex = new int(); public Text[] patchCountsTextObjects; public int[] patchInventoryIndices = new int[]{0,1,2,3,4,5,6}; public static PatchCurrent PatchInstance; void Awake() { PatchInstance = this; PatchInstance.patchCurrent = 0; // Current slot in the grenade inventory (7 slots) PatchInstance.patchIndex = 0; // Current index to the grenade look-up tables } } <file_sep>/Assets/Scripts/CameraView.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraView : MonoBehaviour { private Camera cam; private float tick; private float tickFinished; private bool frameOn; void Awake () { cam = GetComponent<Camera>(); tick = 0.5f; tickFinished = Time.time + tick; frameOn = false; } // Update is called once per frame void Update () { if (tickFinished < Time.time) { cam.enabled = true; frameOn = true; tickFinished = Time.time + tick; } } void LateUpdate() { if (frameOn) cam.enabled = false; // Render to texture for 1 frame only! } } <file_sep>/Assets/LightsManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class LightsManager : MonoBehaviour { private GameObject[] lightChildrenGOs; private Light[] lightChildren; private int childCount; public float distanceToDisableLightsFromPlayer = 10f; void Start () { childCount = transform.childCount; lightChildren = new Light[childCount]; lightChildrenGOs = new GameObject[childCount]; for (int i=0;i<childCount;i++) { lightChildrenGOs[i] = transform.GetChild(i).gameObject; lightChildren[i] = lightChildrenGOs[i].GetComponent<Light>(); } } void Update () { for (int i=0;i<lightChildren.Length;i++) { if (lightChildrenGOs[i] != null) { if ((Vector3.Distance(Const.a.player1.transform.position,lightChildrenGOs[i].transform.position)) > distanceToDisableLightsFromPlayer) { lightChildrenGOs[i].SetActive(false); } else { lightChildrenGOs[i].SetActive(true); } } } } } <file_sep>/Assets/Scripts/EmailCurrent.cs using UnityEngine; using System.Collections; public class EmailCurrent : MonoBehaviour { [SerializeField] public int emailCurrent = new int(); [SerializeField] public int emailIndex = new int(); public static EmailCurrent Instance; void Awake() { Instance = this; Instance.emailCurrent = 0; // Current slot in the email inventory (7 slots) Instance.emailIndex = 0; // Current index to the email look-up tables } }<file_sep>/Assets/Scripts/EmailInventory.cs using UnityEngine; using UnityEngine.UI; using System.Collections; [System.Serializable] public class EmailInventory : MonoBehaviour { Text title; public int slotnum = 0; void Start () { title = GetComponent<Text>(); } void Update () { title.text = EmailTitle.Instance.emailInventoryTitle[slotnum]; if (slotnum == EmailCurrent.Instance.emailCurrent) { title.color = Const.a.ssYellowText; // Yellow } else { title.color = Const.a.ssGreenText; // Green } } } <file_sep>/Assets/Scripts/UIButtonMask.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class UIButtonMask : MonoBehaviour { public GameObject playerCamera; public GUIState.ButtonType overButtonType = GUIState.ButtonType.Generic; // default to generic button private float doubleClickTime; private float dbclickFinished; public int doubleClickTicks; // takes 2 to activate double click function public bool doubleClickEnabled = false; public string toolTipText; public Handedness toolTipType; public Texture2D cursorOnHover; void Start () { if (playerCamera == null) { Const.sprint("Warning: UIButtonMask script could not find playerCamera",Const.a.allPlayers); } EventTrigger pointerTrigger = GetComponent<EventTrigger>(); if (pointerTrigger == null) { pointerTrigger = gameObject.AddComponent<EventTrigger>(); if (pointerTrigger == null) { Const.sprint("Warning: Could not create Event Trigger for UIButtonMask",Const.a.allPlayers); return; } } EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.PointerEnter; entry.callback.AddListener((eventData) => { PtrEnter(); } ); pointerTrigger.triggers.Add(entry); EventTrigger.Entry entry2 = new EventTrigger.Entry(); entry2.eventID = EventTriggerType.PointerExit; entry2.callback.AddListener((eventData) => { PtrExit(); } ); pointerTrigger.triggers.Add(entry2); if (doubleClickEnabled) { doubleClickTime = Const.a.doubleClickTime; dbclickFinished = Time.time; doubleClickTicks = 0; GetComponent<Button>().onClick.AddListener(() => { UiButtonMaskClick(); }); } } void Update () { if (doubleClickEnabled) { if (dbclickFinished < Time.time) { doubleClickTicks--; if (doubleClickTicks < 0) doubleClickTicks = 0; } } } public void PtrEnter () { GUIState.a.PtrHandler(true,true,overButtonType,gameObject); playerCamera.GetComponent<MouseLookScript>().currentButton = gameObject; doubleClickTicks = 0; if (toolTipText != null && toolTipText != string.Empty) { playerCamera.GetComponent<MouseLookScript>().mouseCursor.GetComponent<MouseCursor>().toolTip = toolTipText; playerCamera.GetComponent<MouseLookScript>().mouseCursor.GetComponent<MouseCursor>().toolTipType = toolTipType; } } public void PtrExit () { GUIState.a.PtrHandler(false,false,GUIState.ButtonType.None,null); doubleClickTicks = 0; if (toolTipText != null && toolTipText != string.Empty) { playerCamera.GetComponent<MouseLookScript>().mouseCursor.GetComponent<MouseCursor>().toolTip = string.Empty; } } void UiButtonMaskClick () { doubleClickTicks++; if (doubleClickTicks == 2) { gameObject.SendMessage("DoubleClick"); doubleClickTicks = 0; dbclickFinished = Time.time + doubleClickTime; return; } dbclickFinished = Time.time + doubleClickTime; } } <file_sep>/Assets/Scripts/AmmoIconManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class AmmoIconManager : MonoBehaviour { [SerializeField] public Sprite[] ammIcons; [SerializeField] public GameObject clipBox; [SerializeField] public GameObject energySlider; [SerializeField] public GameObject energyHeatTicks; [SerializeField] public GameObject energyOverloadButton; private Image border; private Image icon; public void Awake() { icon = GetComponent<Image>(); border = clipBox.GetComponent<Image>(); } public void SetAmmoIcon (int index, bool alternateAmmo) { if (index >= 0) { icon.enabled = true; border.enabled = true; energySlider.SetActive(false); energyHeatTicks.SetActive(false); energyOverloadButton.SetActive(false); switch (index) { case 36: if (alternateAmmo) { icon.overrideSprite = ammIcons[8]; // penetrator, MK3 } else { icon.overrideSprite = ammIcons[7]; // magnesium, MK3 } break; case 37: icon.enabled = false; // Uses energy, blaster border.enabled = false; energySlider.SetActive(true); energyHeatTicks.SetActive(true); energyOverloadButton.SetActive(true); break; case 38: if (alternateAmmo) { icon.overrideSprite = ammIcons[1]; // tranq darts, dartgun } else { icon.overrideSprite = ammIcons[0]; // needle darts, dartgun } break; case 39: if (alternateAmmo) { icon.overrideSprite = ammIcons[10]; // splinter, flechette } else { icon.overrideSprite = ammIcons[9]; // hornet, flechette } break; case 40: icon.enabled = false; // Uses energy, ion beam border.enabled = false; energySlider.SetActive(true); energyHeatTicks.SetActive(true); energyOverloadButton.SetActive(true); break; case 41: icon.enabled = false; // Rapier, no ammo used border.enabled = false; break; case 42: icon.enabled = false; // Pipe, no ammo used border.enabled = false; break; case 43: if (alternateAmmo) { icon.overrideSprite = ammIcons[6]; // slug, magnum } else { icon.overrideSprite = ammIcons[5]; // hollow, magnum } break; case 44: icon.overrideSprite = ammIcons[11]; // magcart, magpulse break; case 45: if (alternateAmmo) { icon.overrideSprite = ammIcons[3]; // teflon, pistol } else { icon.overrideSprite = ammIcons[2]; // standard, pistol } break; case 46: icon.enabled = false; // Uses energy, plasma rifle border.enabled = false; energySlider.SetActive(true); energyHeatTicks.SetActive(true); energyOverloadButton.SetActive(true); break; case 47: icon.overrideSprite = ammIcons[14]; // rail round, railgun break; case 48: icon.overrideSprite = ammIcons[4]; // rubber, riotgun break; case 49: if (alternateAmmo) { icon.overrideSprite = ammIcons[13]; // large slag, skorpion } else { icon.overrideSprite = ammIcons[12]; // slag, skorpion } break; case 50: icon.enabled = false; // Uses energy, sparq beam border.enabled = false; energySlider.SetActive(true); energyHeatTicks.SetActive(true); energyOverloadButton.SetActive(true); break; case 51: icon.enabled = false; // Uses energy, stungun border.enabled = false; energySlider.SetActive(true); energyHeatTicks.SetActive(true); energyOverloadButton.SetActive(true); break; } } } } <file_sep>/Assets/Scripts/WeaponShotsText.cs using UnityEngine; using System.Collections; public class WeaponShotsText : MonoBehaviour { public static string[] weaponShotsInventoryText = new string[]{"RELOAD","n 8","s 20","","OK","",""}; } <file_sep>/Assets/Scripts/LogTextReaderManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LogTextReaderManager : MonoBehaviour { public GameObject moreButton; public GameObject logTextOutput; public Text moreButtonText; //public MFDManager mfdManager; //public GameObject dataTabAudioLogContainer; //public GameObject dataTabManager; // Update is called once per frame void Update () { if (logTextOutput.GetComponent<Text>().text.Length > 568) { moreButtonText.text = "[MORE]"; } else { moreButtonText.text = "[CLOSE]"; } } public void SendTextToReader(int referenceIndex) { logTextOutput.GetComponent<Text>().text = Const.a.audioLogSpeech2Text[referenceIndex]; //mfdManager.OpenTab(4,true,MFDManager.TabMSG.AudioLog,referenceIndex); //dataTabManager.GetComponent<DataTab>().Reset(); //dataTabAudioLogContainer.SetActive(true); //dataTabAudioLogContainer.GetComponent<LogDataTabContainerManager>().SendLogData(referenceIndex); } } <file_sep>/Assets/Scripts/KeypadKeycodeButtons.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class KeypadKeycodeButtons : MonoBehaviour { public KeypadKeycode keypad; public KeycodeDigitImage digit1s; public KeycodeDigitImage digit10s; public KeycodeDigitImage digit100s; public int keycode; public AudioClip SFX; public AudioClip SFX_Incorrect; public AudioClip SFX_Success; private int currentEntry; private int entryOnes; private int entryTens; private int entryHuns; private AudioSource SFXSource; private bool sfxPlayed; private bool done; void Awake () { currentEntry = -1; entryOnes = -1; entryTens = -1; entryHuns = -1; SFXSource = GetComponent<AudioSource>(); sfxPlayed = false; done = false; } public void Keypress (int button) { if (done) return; SFXSource.PlayOneShot(SFX); // Digit key pressed 0 thru 9 if ((button >= 0) && (button <= 9)) SetDigit(button); // Backspace dash '-' button pressed if (button == 10) { if (entryHuns != -1) { entryOnes = entryTens; entryTens = entryHuns; entryHuns = -1; currentEntry = (entryOnes + (entryTens * 10)); return; } if (entryTens != -1) { entryOnes = entryTens; entryTens = -1; currentEntry = entryOnes; return; } if (entryOnes != -1) { entryOnes = -1; currentEntry = -1; return; } } // Clear 'C' key pressed if (button == 11) { currentEntry = -1; entryOnes = -1; entryTens = -1; entryHuns = -1; } } void SetDigit(int value) { if ((value > 9) || (value < 0)) { Const.sprint("BUG: incorrect value sent to keypad controller",Const.a.allPlayers); return; } if (entryOnes == -1) { entryOnes = value; currentEntry = entryOnes; return; } if (entryTens == -1) { entryTens = entryOnes; entryOnes = value; currentEntry = (entryOnes + (entryTens * 10)); return; } if (entryHuns == -1) { entryHuns = entryTens; entryTens = entryOnes; entryOnes = value; currentEntry = (entryOnes + (entryTens * 10) + (entryHuns * 100)); sfxPlayed = false; return; } } void Update () { digit1s.digitIndex = entryOnes; digit10s.digitIndex = entryTens; digit100s.digitIndex = entryHuns; if (done) return; if (GetInput.a.Numpad0()) { Keypress(0); } if (GetInput.a.Numpad1()) { Keypress(1); } if (GetInput.a.Numpad2()) { Keypress(2); } if (GetInput.a.Numpad3()) { Keypress(3); } if (GetInput.a.Numpad4()) { Keypress(4); } if (GetInput.a.Numpad5()) { Keypress(5); } if (GetInput.a.Numpad6()) { Keypress(6); } if (GetInput.a.Numpad7()) { Keypress(7); } if (GetInput.a.Numpad8()) { Keypress(8); } if (GetInput.a.Numpad9()) { Keypress(9); } if (GetInput.a.NumpadMinus()) { Keypress(10); } if (GetInput.a.NumpadPeriod()) { Keypress(11); } if (currentEntry == keycode) { if ((entryHuns != -1) && sfxPlayed == false) { SFXSource.PlayOneShot(SFX_Success); sfxPlayed = true; // prevent play sfx every frame once 3 digits have been entered } keypad.UseTargets(); done = true; } else { if ((entryHuns != -1) && sfxPlayed == false) { SFXSource.PlayOneShot(SFX_Incorrect); sfxPlayed = true; // prevent play sfx every frame once 3 digits have been entered } } } } <file_sep>/Assets/Scripts/RuntimeObject.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RuntimeObject : MonoBehaviour { public bool isRuntimeObject = false; void Awake () { isRuntimeObject = true; // Lets us know if this object is indeed not the prefab but rather an instance of a prefab } } <file_sep>/Assets/Scripts/EReaderSectionsButtons.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EReaderSectionsButtons : MonoBehaviour { public MultiMediaTabManager mmtm; public EReaderSectionsButtonHighlight ersbh0; public EReaderSectionsButtonHighlight ersbh1; public EReaderSectionsButtonHighlight ersbh2; public int index; public void OnClick() { switch (index) { case 0: mmtm.OpenEmailTableContents(); ersbh0.Highlight(); ersbh1.DeHighlight(); ersbh2.DeHighlight(); break; case 1: mmtm.OpenLogTableContents(); ersbh0.DeHighlight(); ersbh1.Highlight(); ersbh2.DeHighlight(); break; case 2: mmtm.OpenDataTableContents(); ersbh0.DeHighlight(); ersbh1.DeHighlight(); ersbh2.Highlight(); break; } } } <file_sep>/Assets/Scripts/EnergyTickManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class EnergyTickManager : MonoBehaviour { public GameObject playerObject; public PlayerEnergy playerEnergy; public GameObject[] energyTicks; public Sprite[] tickImages; private Image tickImage; private int tempSpriteIndex; private float lastEnergy; void Awake () { tickImage = GetComponent<Image>(); } void Update (){ if (lastEnergy != playerEnergy.energy) DrawTicks(); lastEnergy = playerEnergy.energy; // reason why this script can't be combined with health ticks script } void DrawTicks() { tempSpriteIndex = -1; int step = 0; while (step < 256) { if (playerEnergy.energy < (256 - step)) { tempSpriteIndex++; } step += 11; } //Debug.Log(tempSpriteIndex.ToString()); if (tempSpriteIndex >= 0 && tempSpriteIndex < 24) { tickImage.overrideSprite = tickImages[tempSpriteIndex]; } /* int h = 0; int tickcnt = 0; // Clear health ticks for (int i=0;i<24;i++) { energyTicks[i].SetActive(false); } // Keep drawing ticks out until playerHealth is met while (h <= playerEnergy.energy) { energyTicks[tickcnt].SetActive(true); tickcnt++; h = h + 11; }*/ } }<file_sep>/Assets/Scripts/TestEnvironment.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestEnvironment : MonoBehaviour { public GameObject[] hideStuff; // Use this for initialization void Start () { for (int i = 0; i < hideStuff.Length; i++) hideStuff[i].SetActive(false); } } <file_sep>/Assets/Scripts/GrenadeCurrent.cs using UnityEngine; using System.Collections; public class GrenadeCurrent : MonoBehaviour { [SerializeField] public int grenadeCurrent = new int(); [SerializeField] public int grenadeIndex = new int(); public int[] grenadeInventoryIndices = new int[]{0,1,2,3,4,5,6}; public float nitroTimeSetting; public float earthShakerTimeSetting; public static GrenadeCurrent GrenadeInstance; public CapsuleCollider playerCapCollider; void Start() { GrenadeInstance = this; GrenadeInstance.grenadeCurrent = 0; // Current slot in the grenade inventory (7 slots) GrenadeInstance.grenadeIndex = 0; // Current index to the grenade look-up tables nitroTimeSetting = Const.a.nitroDefaultTime; earthShakerTimeSetting = Const.a.earthShDefaultTime; } } <file_sep>/Assets/Scripts/Trigger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trigger : MonoBehaviour { public float delayBeforeFire = 0f; public float delayBeforeReset = 1.0f; public float initialDelayOnAwake = 0f; public bool allowNPC = false; public bool ignoreSecondaryTriggers = false; public int numPlayers = 0; public int numNPCs = 0; public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; private GameObject recentMostActivator; private float delayFireFinished; private float delayResetFinished; public bool firing; void Awake () { InitialState(); } void Start () { InitialState(); } void OnEnable() { InitialState(); } void InitialState () { delayResetFinished = Time.time + initialDelayOnAwake; delayFireFinished = Time.time; firing = false; } void Update () { if (firing) { if (delayFireFinished < Time.time) { UseTargets(recentMostActivator); recentMostActivator = null; firing = false; } } } public void UseTargets (GameObject activator) { UseData ud = new UseData(); ud.owner = activator; if (target != null) { target.SendMessageUpwards("Targetted", ud); } if (target1 != null) { target1.SendMessageUpwards("Targetted", ud); } if (target2 != null) { target2.SendMessageUpwards("Targetted", ud); } if (target3 != null) { target3.SendMessageUpwards("Targetted", ud); } } void TriggerTripped (Collider col, bool initialEntry) { if (((col.gameObject.tag == "Player") && (col.gameObject.GetComponent<PlayerHealth>().hm.health > 0f)) || (allowNPC && (col.gameObject.tag == "NPC") && (col.gameObject.GetComponent<HealthManager>().health > 0f)) ) { if (delayResetFinished < Time.time) { if (recentMostActivator != null) { if (ignoreSecondaryTriggers) return; } if (initialEntry && col.gameObject.tag == "Player") numPlayers++; if (initialEntry && col.gameObject.tag == "NPC") numNPCs++; delayFireFinished = Time.time + delayBeforeFire; delayResetFinished = Time.time + delayBeforeReset; firing = true; } } } void OnTriggerEnter (Collider col) { TriggerTripped(col,true); } void OnTriggerStay (Collider col) { TriggerTripped (col, false); } void OnTriggerExit (Collider col) { if (col.gameObject.tag == "Player") numPlayers--; if (col.gameObject.tag == "NPC") numNPCs--; } } <file_sep>/Assets/Scripts/LightAnimation.cs using UnityEngine; using System.Collections; public class LightAnimation : MonoBehaviour { [Tooltip("Set minimum intensity of light animations")] public float minIntensity = 0f; [Tooltip("Set maximum intensity of light animations (overrides Light settings)")] public float maxIntensity = 1f; [Tooltip("Whether the light is on")] public bool lightOn = true; //useful for disabling light via switch, for instance [Tooltip("Whether to interpolate smoothly between intensities")] public bool lerpOn = true; [Tooltip("Alternating lerpUp then lerpDown for set times (float)")] public float[] intervalSteps; //alternating [Tooltip("Whether each alternating step should lerp (bool)")] public bool[] intervalStepisLerping; //lerp for this step? assign per step [Tooltip("Current interval element in float array")] public int currentStep; public float lerpRef = 0f; private bool lerpUp; private bool noSteps = false; private float lerpTime = 0.5f; private float stepTime; private float lerpStartTime; private Light animLight; private float differenceInIntensity; private float setIntensity; private float lerpValue; void Awake () { animLight = GetComponent<Light>(); animLight.intensity = minIntensity; currentStep = 0; //lightOn = true; lerpUp = true; differenceInIntensity = (maxIntensity - minIntensity); if (intervalSteps.Length != 0) { stepTime = intervalSteps[currentStep]; lerpTime = Time.time + stepTime; lerpStartTime = Time.time; } else { noSteps = true; //setIntensity = GetComponent<Light>().intensity; animLight.intensity = maxIntensity; } } public void Targetted (UseData ud) { lightOn = true; animLight.intensity = maxIntensity; animLight.enabled = true; } void Update () { if (lightOn) { if (!noSteps) { if (lerpUp) { // Going from minIntensity to maxIntensity if (lerpTime < Time.time) { animLight.intensity = maxIntensity; lerpUp = false; currentStep++; if (currentStep == intervalSteps.Length) currentStep = 0; stepTime = intervalSteps[currentStep]; lerpTime = Time.time + stepTime; lerpStartTime = Time.time; if (lerpTime == 0f) lerpTime = 0.1f; } else { if (lerpOn) { if (currentStep < intervalStepisLerping.Length) { if (intervalStepisLerping[currentStep]) { lerpValue = (Time.time - lerpStartTime)/(lerpTime - lerpStartTime); // percent towards goal time animLight.intensity = minIntensity + (differenceInIntensity * (lerpValue)); } } } } } else { // Going from maxIntensity to minIntensity if (lerpTime < Time.time) { animLight.intensity = minIntensity; lerpUp = true; currentStep++; if (currentStep == intervalSteps.Length) currentStep = 0; stepTime = intervalSteps[currentStep]; lerpTime = Time.time + stepTime; lerpStartTime = Time.time; if (lerpTime == 0f) lerpTime = 0.1f; } else { if (lerpOn) { if (currentStep == intervalSteps.Length) currentStep = 0; if (currentStep < intervalStepisLerping.Length) { if (intervalStepisLerping[currentStep]) { lerpValue = (Time.time - lerpStartTime)/(lerpTime - lerpStartTime); // percent towards goal time animLight.intensity = minIntensity + (differenceInIntensity * (1-lerpValue)); } } } } } } else { // Light is on but no steps so set to editor setting animLight.intensity = maxIntensity; } } else { // Light is turned off. animLight.intensity = 0f; } } } <file_sep>/Assets/Scripts/LogicRelay.cs using UnityEngine; using System.Collections; public class LogicRelay : MonoBehaviour { public GameObject target; public GameObject target1; public GameObject target2; public GameObject target3; public float delay = 0f; private float delayFinished; private GameObject playerCamera; void Awake () { delayFinished = 0f; } public void Targetted (GameObject owner) { playerCamera = owner; // set playerCamera to owner of the input (always should be the player camera) if (delay > 0) { delayFinished = Time.time + delay; } else { UseTargets(); } } public void UseTargets () { if (target != null) { target.SendMessageUpwards("Targetted", playerCamera); } if (target1 != null) { target1.SendMessageUpwards("Targetted", playerCamera); } if (target2 != null) { target2.SendMessageUpwards("Targetted", playerCamera); } if (target3 != null) { target3.SendMessageUpwards("Targetted", playerCamera); } } void Update () { if ((delayFinished < Time.time) && delayFinished != 0) { delayFinished = 0; UseTargets(); } } } <file_sep>/Assets/Scripts/FPSCounter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Rendering; using System.Runtime.InteropServices; using System; public class FPSCounter : MonoBehaviour { private float deltaTime = 0.0f; private float msecs; private float fps; private string textString; private Text text; private float tickFinished; public float tickSecs = 0.1f; private int count; void Start() { text = GetComponent<Text> (); deltaTime = Time.time; count = 0; tickFinished = Time.time + tickSecs; } void Update() { //deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f; count++; deltaTime += Time.unscaledDeltaTime; if (tickFinished < Time.time) { //msecs = (Time.time - timeStart); msecs = deltaTime/count*1000f; //msecsGPU = deltaTime/countGUI*1000f; deltaTime = 0; fps = count * (1 / tickSecs); count = 0; //msecs = deltaTime * 1000.0f; //fps = 1.0f / deltaTime; textString = string.Format ("{0:0.0} ms ({1:0.0} fps)", msecs, fps); text.text = textString; tickFinished = Time.time + tickSecs; } } } <file_sep>/Assets/Scripts/LogInventory.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class LogInventory : MonoBehaviour { public bool[] hasLog; public bool[] readLog; //public int[] logCountFromLevel; public int[] numLogsFromLevel; public static LogInventory a; public int lastAddedIndex = -1; public CenterTabButtons centerTabButtonsControl; private AudioSource SFXSource; private AudioClip SFXClip; void Awake() { SFXSource = GetComponent<AudioSource>(); if (SFXSource == null) SFXSource = gameObject.AddComponent<AudioSource>(); a = this; } void Update () { if(GetInput.a.RecentLog()) { if (lastAddedIndex != -1) PlayLastAddedLog(lastAddedIndex); } } public void PlayLog (int logIndex) { if (logIndex == -1) return; // Play the log audio if (Const.a.audioLogType[lastAddedIndex] == 1) { SFXClip = Const.a.audioLogs[lastAddedIndex]; SFXSource.PlayOneShot(SFXClip); } MFDManager.a.SendAudioLogToDataTab(logIndex); centerTabButtonsControl.TabButtonClickSilent(4); } void PlayLastAddedLog (int logIndex) { if (logIndex == -1) return; PlayLog(logIndex); lastAddedIndex = -1; } } <file_sep>/Assets/Scripts/WeaponIconManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class WeaponIconManager : MonoBehaviour { [SerializeField] public Sprite[] wepIcons; public void SetWepIcon (int index) { if (index >= 0) GetComponent<Image>().overrideSprite = Const.a.useableItemsIcons[index]; } } <file_sep>/Assets/Scripts/MainMenuButtonHighlight.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainMenuButtonHighlight : MonoBehaviour { public MenuArrowKeyControls pageController; public int menuItemIndex; public Text subtext; public GameObject pad; public Sprite padlit; public Sprite paddrk; void DeHighlight () { Color tempcol = subtext.color; tempcol.a = 0.5f; subtext.color = tempcol; pad.GetComponent<Image>().overrideSprite = paddrk; } void Highlight () { Color tempcol = subtext.color; tempcol.a = 1.0f; subtext.color = tempcol; pad.GetComponent<Image>().overrideSprite = padlit; } public void CursorHighlight () { Highlight(); pageController.SetIndex(menuItemIndex); } public void CursorDeHighlight () { DeHighlight(); pageController.currentIndex = 0; } } <file_sep>/Assets/Scripts/ButtonListenFKey1.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class ButtonListenFKey1 : MonoBehaviour { private Button button; public KeyCode Fkey; void Awake () { button = GetComponent<Button>(); } void Update () { if(Input.GetKeyDown(Fkey)) button.onClick.Invoke(); } } <file_sep>/Assets/Scripts/ProjectileEffectImpact.cs using UnityEngine; using System.Collections; public class ProjectileEffectImpact : MonoBehaviour { public Const.PoolType impactType; public GameObject host; [HideInInspector] public DamageData dd; [SerializeField] public int hitCountBeforeRemoval = 1; private Vector3 tempVec; private int numHits; //private Rigidbody rbody; private void OnEnable() { numHits = 0; // reset when pulled from pool //rbody = GetComponent<Rigidbody>(); } void OnCollisionEnter (Collision other) { if (other.gameObject != host) { numHits++; if (numHits >= hitCountBeforeRemoval) { // get an impact effect GameObject impact = Const.a.GetObjectFromPool(impactType); // enable the impact effect if (impact != null) { impact.transform.position = other.contacts[0].point; impact.SetActive(true); } HealthManager hm = other.contacts[0].otherCollider.gameObject.GetComponent<HealthManager>(); if (hm != null) hm.TakeDamage(dd); gameObject.SetActive(false); // disable the projectile }// else { // Vector3 dir = other.contacts[0].normal; //rbody.AddForce(dir * rbody.velocity.magnitude * 0.75f, ForceMode.Impulse); //buggy, added to physics material instead //} } } } <file_sep>/Assets/Scripts/WeaponTextManager.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class WeaponTextManager : MonoBehaviour { [SerializeField] public string[] wepText; public void SetWepText (int index) { if (index >= 0) GetComponent<Text>().text = Const.a.useableItemsNameText[index]; } } <file_sep>/Assets/Scripts/LaserDrawing.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class LaserDrawing : MonoBehaviour { public GameObject followStarter; public Vector3 startPoint; public Vector3 endPoint; public float lineLife = 0.15f; public LineRenderer line; void Awake () { line = GetComponent<LineRenderer>(); line.startWidth = 0.2f; line.endWidth = 0.2f; line.enabled = true; } void Update () { //if (followStarter != null) { // endPoint = followStarter.transform.position; // //} line.SetPosition(0,startPoint); line.SetPosition(1,endPoint); } void OnEnable() { StartCoroutine(DisableLine()); line.enabled = true; } IEnumerator DisableLine() { yield return new WaitForSeconds(lineLife); Vector3 sp = new Vector3(5000f, 5000f, 5000f); Vector3 ep = sp; line.SetPosition(0, sp); line.SetPosition(1, ep); line.enabled = false; } }
90e31073150c841bc2d2d389ca3b43e2d2ce1eff
[ "Markdown", "C#", "Python", "INI" ]
166
C#
HeadClot/Citadel
1bd2e321703af7d3e400522762db7e1c09ed7208
0cab6c5397847a014ae5b2878de58b81030b4396
refs/heads/master
<file_sep>platform :ios, '8.0' target 'podXMPP' do use_frameworks! pod 'XMPPFramework', '~> 4.0.0' end<file_sep># XMPPDemo QQ IM 仿照qq做的一个XMPP及时通讯聊天的软件
e952b624dff5b19213b2fa448079ff2a46f25d80
[ "Markdown", "Ruby" ]
2
Ruby
LiuPN/XMPPDemo
df849c5443e0769eade53e4fa1a3c48a660c7671
3000770608a484d78fd4a911e7d08aee24b835de
refs/heads/master
<file_sep>package com.example.firebasecrud; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.app.ActivityOptions; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import com.example.firebasecrud.R; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.example.firebasecrud.model.Lecturer; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import java.util.Map; public class AddLecturer extends AppCompatActivity { EditText addLecturerNameInput, addLecturerExpertiseInput; RadioButton radioButton; RadioGroup addLecturerGenderRG; String addLecturerName="", addLecturerExpertise="", addLecturerGender="male", action = ""; Button addLecturerButton; Toolbar addLecturerTB; Lecturer lecturer; private DatabaseReference mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_lecturer); mDatabase = FirebaseDatabase.getInstance().getReference(); addLecturerTB = findViewById(R.id.addLecturerToolbar); setSupportActionBar(addLecturerTB); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); addLecturerExpertiseInput = findViewById(R.id.addLecturerExpertise); addLecturerNameInput = findViewById(R.id.addLecturerName); addLecturerNameInput.addTextChangedListener(theTextWatcher); addLecturerExpertiseInput.addTextChangedListener(theTextWatcher); addLecturerButton = findViewById(R.id.addLecturerButton); addLecturerGenderRG = findViewById(R.id.addLecturerGender); addLecturerGenderRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { radioButton = findViewById(i); addLecturerGender = radioButton.getText().toString(); if (!addLecturerName.isEmpty() && !addLecturerExpertise.isEmpty() && !addLecturerGender.isEmpty()) { addLecturerButton.setEnabled(true); } else { addLecturerButton.setEnabled(false); } } }); Intent intent = getIntent(); action = intent.getStringExtra("action"); if (action.equals("add")) { getSupportActionBar().setTitle(R.string.addlecturer); addLecturerButton.setText(R.string.addlecturer); addLecturerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addLecturerName = addLecturerNameInput.getEditableText().toString().trim(); addLecturerExpertise = addLecturerExpertiseInput.getEditableText().toString().trim(); addLecturerGender = radioButton.getText().toString(); addLecturer(addLecturerName, addLecturerGender, addLecturerExpertise); } }); } else{ getSupportActionBar().setTitle("Edit Lecturer"); lecturer = intent.getParcelableExtra("edit_data_lect"); addLecturerNameInput.setText(lecturer.getName()); addLecturerExpertiseInput.setText(lecturer.getExpertise()); if(lecturer.getGender().equalsIgnoreCase("male")){ addLecturerGenderRG.check(R.id.addLecturerMale); }else{ addLecturerGenderRG.check(R.id.addLecturerFemale); } addLecturerButton.setText("Edit Lecturer"); addLecturerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addLecturerName = addLecturerNameInput.getEditableText().toString().trim(); addLecturerExpertise = addLecturerExpertiseInput.getEditableText().toString().trim(); addLecturerGender = radioButton.getText().toString(); Map<String,Object> params = new HashMap<>(); params.put("name", addLecturerName); params.put("expertise", addLecturerExpertise); params.put("gender", addLecturerGender); mDatabase.child("lecturer").child(lecturer.getId()).updateChildren(params).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Intent intent; intent = new Intent(AddLecturer.this, LecturerData.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AddLecturer.this); startActivity(intent, options.toBundle()); finish(); } }); } }); } } public void addLecturer(String mname, String mgender, String mexpertise) { String mid = mDatabase.child("lecturer").push().getKey(); Lecturer lecturer = new Lecturer(mid, mname, mgender, mexpertise); mDatabase.child("lecturer").child(mid).setValue(lecturer).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(AddLecturer.this, "Lecturer Added Successfully", Toast.LENGTH_SHORT).show(); addLecturerName = addLecturerNameInput.getEditableText().toString().trim(); addLecturerExpertise = addLecturerExpertiseInput.getEditableText().toString().trim(); addLecturerGender = radioButton.getText().toString(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(AddLecturer.this, "Insert Data Failed!", Toast.LENGTH_SHORT).show(); } }); } private TextWatcher theTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { addLecturerName = addLecturerNameInput.getEditableText().toString().trim(); addLecturerExpertise = addLecturerExpertiseInput.getEditableText().toString().trim(); if (!addLecturerName.isEmpty() && !addLecturerExpertise.isEmpty() && !addLecturerGender.isEmpty()) { addLecturerButton.setEnabled(true); } else { addLecturerButton.setEnabled(false); } } @Override public void afterTextChanged(Editable editable) { } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.lecturer_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { Intent intent = new Intent(AddLecturer.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AddLecturer.this); startActivity(intent, options.toBundle()); finish(); return true; } else if (id == R.id.lecturer_list) { Intent intent = new Intent(AddLecturer.this, LecturerData.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AddLecturer.this); startActivity(intent, options.toBundle()); finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent intent; intent = new Intent(AddLecturer.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(AddLecturer.this); startActivity(intent, options.toBundle()); finish(); } } <file_sep>rootProject.name='BSapps' include ':app'
0e347c28aab5367a27b063727815ed53eed9e63f
[ "Java", "Gradle" ]
2
Java
bsaputra01/BSappsss
1070687e28fa2557a023a7d68e99f6de42c00913
bd1347413e83f1159337fb5af05d029ab431c61a
refs/heads/main
<file_sep> import React from 'react'; import {Button,StyleSheet,Text,View,} from 'react-native'; const Styles = StyleSheet.create({ MainPageView :{ flex:1, justifyContent : 'center', alignItems:'center' }, }); const Details = ({navigation}) => { return ( <View style={Styles.MainPageView}> <Text>Details</Text> <Button title = "Go To Details ... Again" onPress={() => navigation.push('Details')} /> <Button title = "Go To Home" onPress={() => navigation.navigate('Home')} /> <Button title = "Go Back" onPress={() => navigation.goBack()} /> <Button title = "Go To First Screen" onPress={() => navigation.popToTop()} /> </View> ); }; export default Details;<file_sep>import React from 'react'; import {Button,StyleSheet,Text,View,StatusBar} from 'react-native'; import { useTheme } from '@react-navigation/native'; const Home = ({navigation}) => { const { colors } = useTheme(); const theme = useTheme(); return ( <View style={Styles.MainPageView}> <StatusBar barStyle= { theme.dark ? "light-content" : "dark-content" }/> <Text style={{color: colors.text}}>Home</Text> <Button title = "Go To Details" onPress={() => navigation.navigate('Details')} /> </View> ); }; const Styles = StyleSheet.create({ MainPageView :{ flex:1, justifyContent : 'center', alignItems:'center' }, }); export default Home; <file_sep>import React from 'react'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import Home from './Home'; import Details from './Details'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import Icon from 'react-native-vector-icons/Ionicons'; import ExploreScreen from './ExploreScreen'; import SupportScreen from './SupportScreen'; import ProfileScreen from './ProfileScreen'; const HomeStock = new createNativeStackNavigator(); const DetailsStock = new createNativeStackNavigator(); const Stack = new createNativeStackNavigator(); const Tab = createBottomTabNavigator(); const MainScreen = () =>{ return( <Tab.Navigator initialRouteName="HomeStockScreen" activeColor='#fff' > <Tab.Screen name="HomeStockScreen" component={HomeStockScreen} options={{ tabBarLabel: 'Home', tabBarColor:'#009387', tabBarIcon: ({ color }) => ( <Icon name="ios-Home" color={color} size={26} /> ), }} /> <Tab.Screen name="DetailsStockScreen" component={DetailsStockScreen} options={{ tabBarLabel: 'Details', tabBarColor:'#009387', tabBarIcon: ({ color }) => ( <Icon name="bell" color={color} size={26} /> ), tabBarBadge: 3, }} /> <Tab.Screen name="Profile" component={ProfileScreen} options={{ tabBarLabel: 'Profile', tabBarColor:'#009387', tabBarIcon: ({ color }) => ( <Icon name="account" color={color} size={26} /> ), }} /> </Tab.Navigator> )} const HomeStockScreen = ({navigation}) => ( <HomeStock.Navigator screenOptions ={{ headerStyle :{ backgroundColor : '#009387' }, headerTintColor:'#fff', headerTitleStyle :{ fontWeight :'bold' }, }} > <Stack.Screen name="Home" component={Home} /> </HomeStock.Navigator> ) const DetailsStockScreen = ({navigation}) => ( <DetailsStock.Navigator screenOptions ={{ headerStyle :{ backgroundColor : '#009387' }, headerTintColor:'#fff', headerTitleStyle :{ fontWeight :'bold' } }} > <Stack.Screen name="Details" component={Details} /> </DetailsStock.Navigator> ) export default MainScreen;
2e3110fc11e48a4d9180e06fe483cc6bda789034
[ "JavaScript" ]
3
JavaScript
React-Native-All-Projects/Navigation
2a12bfaeaf6c5480a09089a11b3e19ff8dabbb64
b27139f709f3a175a716d32b22f1008c7cd38855
refs/heads/master
<file_sep># snake water gun game import random print("hey user!welcome to SNAKE,WATER,GUN game") list=["snake","water","gun"] user_count=0 comp_count=0 i=0 while(i<10): rand = random.choice(list) choice = input("enter your choice b/w snake,water and gun\n") if rand == choice: print("draw") elif rand == "snake" and choice == "gun": user_count = user_count + 1 print(f"my choice was {rand}.") print("you won") i = i + 1 elif choice == "snake" and rand == "gun": comp_count = comp_count + 1 print(f"my choice was {rand}.") print("I won") i = i + 1 elif rand == "water" and choice == "snake": user_count = user_count + 1 print(f"my choice was {rand}.") print("you won") i = i + 1 elif choice == "snake" and rand == "water": comp_count = comp_count + 1 print(f"my choice was {rand}.") print("I won") i = i + 1 elif rand == "gun" and choice == "water": user_count = user_count + 1 print(f"my choice was {rand}.") print("you won") i = i + 1 elif choice == "gun" and rand == "water": comp_count = comp_count + 1 print(f"my choice was {rand}.") print("I won") i = i + 1 else: print("you entered wrong input!try again!") print("THE RESULT IS :- ") diff1=comp_count-user_count diff2=user_count-comp_count if comp_count>user_count: print(f"i won by {diff1}.") elif comp_count<user_count: print(f"you won by {diff2}.") elif comp_count==user_count: print("it's a draw match")
ccafe528e03c2ec965c0d39295294e392cf39edc
[ "Python" ]
1
Python
barsha001/snake_water_gun
ac62a2ae5cd23a0842d40ff927ad67e1e78c6753
44fd78abf3bbad478fdaf80f7e478b4e78bf2e8d
refs/heads/master
<repo_name>taliaa10/React-Book-Store<file_sep>/src/BookList.js import React, { Component } from "react"; class BookList extends Component { render() { let bookItems = this.props.books.map(book => { return ( <div key={book.imageLink} className="book"> <a target="_blank" rel="noopener noreferrer" href={book.link}> <img alt="{book.name}" src={`https://raw.githubusercontent.com/benoitvallon/100-best-books/master/static/${book.imageLink}`} /> </a> <h4 className="book__title">{book.title}</h4> </div> ); }); return <div className="books__container">{bookItems}</div>; } } export default BookList; <file_sep>/src/partials/Header.js import React, { Component } from "react"; class Header extends Component { render() { return ( <nav className="nav__navContainer"> <div className="nav__navContent"> {/* <h1>goodreads</h1> */} <ul> <li> <a href="#">Home</a> </li> <li> <a href="#">My Books</a> </li> <li> <a href="#">Browse</a> </li> <li> <a href="#">Community</a> </li> </ul> <input placeholder="Search books"></input> <ul className="authLinks"> <li> <a href="#">Sign In</a> </li> <li> <a href="#">Join</a> </li> </ul> </div> </nav> ); } } export default Header; <file_sep>/README.md https://serene-shaw-64b52e.netlify.com <img src="public/Screen-Shot.png" />
a5efdb09613fb8d54db386b1401bb2ab39a1b53d
[ "JavaScript", "Markdown" ]
3
JavaScript
taliaa10/React-Book-Store
6540e72b446939def008eb1767176c40a2ebeac7
8a505735dcbee360da4643b8789e1f4d93321b46
refs/heads/master
<repo_name>Marmot-App/Marmot-iOS<file_sep>/Example/Marmot/extensions/network.swift // // network.swift // Marmot_Example // // Created by linhey on 2019/1/23. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit @objc(MT_network) @objcMembers class MT_network: NSObject { } <file_sep>/Marmot/Classes/MarmotWebView.swift // // Marmot // // Copyright (c) 2017 linhay - https://github.com/linhay // // 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 import WebKit #if canImport(Khala) import Khala #endif extension WKWebView: MarmotCompatible { /// 缓存数据类型 /// /// - diskCache: 在磁盘缓存上 /// - offlineWebApplicationCache: html离线Web应用程序缓存 /// - memoryCache: 内存缓存 /// - localStorage: 本地存储 /// - cookies: Cookies /// - sessionStorage: 会话存储 /// - indexedDBDatabases: IndexedDB数据库 /// - webSQLDatabases: 查询数据库 public enum WebsiteDataTypes: String, CaseIterable { case diskCache = "WKWebsiteDataTypeDiskCache" case offlineWebApplicationCache = "WKWebsiteDataTypeOfflineWebApplicationCache" case memoryCache = "WKWebsiteDataTypeMemoryCache" case localStorage = "WKWebsiteDataTypeLocalStorage" case cookies = "WKWebsiteDataTypeCookies" case sessionStorage = "WKWebsiteDataTypeSessionStorage" case indexedDBDatabases = "WKWebsiteDataTypeIndexedDBDatabases" case webSQLDatabases = "WKWebsiteDataTypeWebSQLDatabases" } fileprivate struct ObjectKey { static var handler = UnsafeRawPointer(bitPattern: "Marmot.WKWebView.handler".hashValue)! } fileprivate var handler: MarmotHandler { get { if let value = objc_getAssociatedObject(self, ObjectKey.handler) as? MarmotHandler { return value }else { self.handler = MarmotHandler(webview: self) return self.handler } } set { objc_setAssociatedObject(self, ObjectKey.handler, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } public extension Marmot where Base: WKWebView { public func begin(injectJS: Bool = true) { base.configuration.userContentController.add(base.handler, name: "marmot") if injectJS { let bundlePath = Bundle(for: MarmotHandler.self).bundlePath + "/Marmot.bundle/" try? FileManager.default.contentsOfDirectory(atPath: bundlePath) .compactMap { $0.hasSuffix(".js") ? bundlePath + $0 : nil } .forEach { self.injectJS(path: $0) } } } var customSchemes: [String]? { guard let controller = NSClassFromString("WKBrowsingContextController") as? NSObject.Type else { return nil } return controller.value(forKey: "customSchemes") as? [String] } /// 移除 webview 缓存 /// /// - Parameter types: 缓存类型 @available(iOS 9.0, *) public func removeData(types: [WKWebView.WebsiteDataTypes]){ let set = Set(types.map({ $0.rawValue })) let date = Date(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: set, modifiedSince: date, completionHandler: { }) } /// 移除 webview 缓存 @available(iOS, introduced: 2.0, deprecated: 9.0, message: "please adopt removeData(types: [WKWebView.WebsiteDataTypes]).") public func removeData(){ guard let libraryDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory,.userDomainMask, true).first else { return } let webkitFolderInLib = libraryDir + "/WebKit" let webKitFolderInCaches = "\(libraryDir)/Caches/\(libraryDir)/WebKit" /* iOS8.0 WebView Cache的存放路径 */ try? FileManager.default.removeItem(atPath: webKitFolderInCaches) try? FileManager.default.removeItem(atPath: webkitFolderInLib) } var browsingContextController: NSObject.Type? { guard let inten = base.value(forKey: "browsingContextController") else { return nil } return type(of: inten) as? NSObject.Type } public func registerSchemeForCustomProtocol(schemes: [String]) { let sel = Selector(("registerSchemeForCustomProtocol:")) if let controller = browsingContextController, controller.responds(to: sel) { schemes.forEach({ controller.perform(sel, with: $0) }) } } public func unregisterSchemeForCustomProtocol(schemes: [String]) { let sel = Selector(("unregisterSchemeForCustomProtocol:")) if let controller = browsingContextController, controller.responds(to: sel) { schemes.forEach({ controller.perform(sel, with: $0) }) } } public func injectJS(path: String) { do { let js = try String(contentsOfFile: path, encoding: .utf8) self.injectJS(value: js) }catch { print(error.localizedDescription) } } public func injectJS(value: String) { let script = WKUserScript(source: value, injectionTime: .atDocumentStart, forMainFrameOnly: false) base.configuration.userContentController.addUserScript(script) } } <file_sep>/Example/Marmot/js-extensions/MT.ts /** * 在这里可以获取和设备有关的一些信息,例如设备语言、设备型号等等。 * * @class MT_device */ class MT_device { private baseURL: string = 'mt://device/' /** * 获取系统信息 * * @returns {MTMessage} * @memberof MT_device */ public info(): MTMessage { return new MTMessage(this.baseURL + 'info') } /** * 获取设备的内存/磁盘空间: */ public space(): MTMessage { return new MTMessage(this.baseURL + 'space') } /** * 在有 Taptic Engine 的设备上触发一个轻微的振动 * level: 0 ~ 2 表示振动等级 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ public taptic(level: string): MTMessage { return new MTMessage(this.baseURL + 'taptic').setParam({ value: level }) } /** * 打开/关闭 手电筒 * level: 0 ~ 1 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ public torch(level: string): MTMessage { return new MTMessage(this.baseURL + 'torch').setParam({ value: level }) } } /** * 剪贴板对于 iOS 的数据分享和交换很重要 * * @class MT_clipboard */ class MT_clipboard { private baseURL: string = 'mt://clipboard/' /** * 获取剪切板上文本 * * @returns {MTMessage} * @memberof MT_clipboard */ public text(): MTMessage { return new MTMessage(this.baseURL + 'text') } /** * 设置剪切板上文本 * * @param {string} value * @returns {MTMessage} * @memberof MT_clipboard */ public setText(value: string): MTMessage { return new MTMessage(this.baseURL + 'setText').setParam({ value: value }) } } /** * 和 iOS 系统本身相关的接口 * * @class MT_system */ class MT_system { private baseURL: string = 'mt://system/' /** * 设置/获取 屏幕亮度 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ brightness(level: number): MTMessage { return new MTMessage(this.baseURL + 'brightness').setParam({ value: level }) } /** * 设置/获取 系统音量 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ volume(level: number): MTMessage { return new MTMessage(this.baseURL + 'volume').setParam({ value: level }) } /** * 拨打电话 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ call(number: string): MTMessage { return new MTMessage(this.baseURL + 'call').setParam({ value: number }) } /** * 发送短信 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ sms(number: string): MTMessage { return new MTMessage(this.baseURL + 'sms').setParam({ value: number }) } /** * 发送邮件 * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ mailto(address: string): MTMessage { return new MTMessage(this.baseURL + 'mailto').setParam({ value: address }) } /** * FaceTime * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ facetime(address: string): MTMessage { return new MTMessage(this.baseURL + 'facetime').setParam({ value: address }) } } /** * 用于与系统自带的传感器交互,例如获取加速度 * * @class MT_motion */ class MT_motion { private baseURL: string = 'mt://motion/' /** * 开始监听 传感器 * * @param {number} [updateInterval=0.1] * @returns {MTMessage} * @memberof MT_motion */ startUpdates(updateInterval: number = 0.1): MTMessage { return new MTMessage(this.baseURL + 'startUpdates').setParam({ updateInterval: updateInterval }) } /** * 停止监听传感器 * * @returns {MTMessage} * @memberof MT_motion */ stopUpdates(message: MTMessage) { message.removeListen() return new MTMessage(this.baseURL + 'stopUpdates').post() } } class MT_location { private baseURL: string = 'mt://location/' /** * 从地图上选择一个点 * * @returns {MTMessage} * @memberof MT_location */ select(): MTMessage { return new MTMessage(this.baseURL + 'select') } /** * 单次定位 * * @returns {MTMessage} * @memberof MT_location */ fetch(): MTMessage { return new MTMessage(this.baseURL + 'fetch') } /** * 监听地理位置更新标识 * * @type {number} * @memberof MT_location */ updatingLabel: number = 0 /** * 监听地理位置更新 * * @returns {MTMessage} * @memberof MT_location */ updating(): MTMessage { this.updatingLabel += 1 return new MTMessage(this.baseURL + 'updating').setParam({ label: this.updatingLabel }) } /** * 停止地理位置更新 * * @param {MTMessage} message * @memberof MT_location */ stopUpdate(message: MTMessage) { new MTMessage(this.baseURL + 'stopUpdate').setParam({ label: message.params["label"] }).post() } /** * 停止所有的地理位置更新 * * @returns * @memberof MT_location */ stopAllUpdates() { new MTMessage(this.baseURL + 'stopAllUpdates').post() } /** * 监听罗盘更新标识 * * @type {number} * @memberof MT_location */ updatingHeadingLabel: number = 0 /** * 监听罗盘更新 * * @returns * @memberof MT_location */ updatingHeading() { this.updatingLabel += 1 return new MTMessage(this.baseURL + 'updatingHeading').setParam({ label: this.updatingHeadingLabel }) } /** * 移除罗盘更新 * * @param {MTMessage} message * @memberof MT_location */ stopHeadingUpdate(message: MTMessage) { new MTMessage(this.baseURL + 'stopHeadingUpdate').setParam({ label: message.params["label"] }).post() } /** * 移除所有的罗盘更新 * * @returns * @memberof MT_location */ stopAllHeadingUpdate() { new MTMessage(this.baseURL + 'stopAllHeadingUpdate').post() } } class MT_qrcode { private baseURL: string = 'mt://qrcode/' scan(): MTMessage { return new MTMessage(this.baseURL + 'scan') } } class MT_events { private baseURL: string = 'mt://events/' shakeDetected(): MTMessage { return new MTMessage(this.baseURL + 'shakeDetected') } } class MT { public device: MT_device = new MT_device() public clipboard: MT_clipboard = new MT_clipboard() public system: MT_system = new MT_system() public motion: MT_motion = new MT_motion() public location: MT_location = new MT_location() public qrcode: MT_qrcode = new MT_qrcode() public events: MT_events = new MT_events() } window.mt = new MT(); <file_sep>/Example/Marmot/extensions/motion.swift // // motion.swift // Marmot_Example // // Created by linhey on 2019/1/16. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import CoreMotion import Khala /// 用于与系统自带的传感器交互,例如获取加速度 @objc(MT_motion) @objcMembers class MT_motion: NSObject { let manager: CMMotionManager = { return CMMotionManager() }() func startUpdates(_ info: KhalaInfo, closure: @escaping KhalaClosure) -> KhalaInfo { guard manager.isDeviceMotionAvailable else { return ["error": "isDeviceMotionAvailable is false"] } if let updateInterval = info["updateInterval"] as? Double { manager.deviceMotionUpdateInterval = updateInterval } manager.startDeviceMotionUpdates(to: OperationQueue.main) { (motion, error) in guard let motion = motion else { closure(["error": error?.localizedDescription ?? ""]) return } var result = KhalaInfo() result["attitude"] = [ "yaw": motion.attitude.yaw, "pitch": motion.attitude.pitch, "roll": motion.attitude.roll, "quaternion": [ "y": motion.attitude.quaternion.y, "x": motion.attitude.quaternion.x, "w": motion.attitude.quaternion.w, "z": motion.attitude.quaternion.z ], "rotationMatrix": [ "m11": motion.attitude.rotationMatrix.m11, "m12": motion.attitude.rotationMatrix.m12, "m13": motion.attitude.rotationMatrix.m13, "m21": motion.attitude.rotationMatrix.m21, "m22": motion.attitude.rotationMatrix.m22, "m23": motion.attitude.rotationMatrix.m23, "m31": motion.attitude.rotationMatrix.m31, "m32": motion.attitude.rotationMatrix.m32, "m33": motion.attitude.rotationMatrix.m33 ] ] result["magneticField"] = [ "accuracy": motion.magneticField.accuracy.rawValue, "field": [ "x": motion.magneticField.field.x, "y": motion.magneticField.field.y, "z": motion.magneticField.field.z ] ] result["rotationRate"] = [ "x": motion.rotationRate.x, "y": motion.rotationRate.y, "z": motion.rotationRate.z ] result["userAcceleration"] = [ "x": motion.userAcceleration.x, "y": motion.userAcceleration.y, "z": motion.userAcceleration.z ] result["gravity"] = [ "x": motion.gravity.x, "y": motion.gravity.y, "z": motion.gravity.z ] closure(result) } return [:] } func stopUpdates() { manager.stopDeviceMotionUpdates() } } <file_sep>/Example/Marmot/ViewController.swift // // ViewController.swift // Marmot // // Created by linhay on 01/05/2019. // Copyright (c) 2019 linhay. All rights reserved. // import UIKit import WebKit import Marmot import SnapKit import Khala import BLFoundation class ViewController: UIViewController { lazy var webview: WKWebView = { let item = WKWebView() item.mt.begin() URLProtocol.registerClass(MarmotURLRequest.self) item.mt.removeData(types: WKWebView.WebsiteDataTypes.allCases) item.mt.registerSchemeForCustomProtocol(schemes: ["https"]) if let path = Bundle.main.path(forResource: "MT", ofType: "js") { item.mt.injectJS(path: path) } return item }() lazy var btn = UIButton() override func viewDidLoad() { super.viewDidLoad() Khala.rewrite.filters.append(KhalaRewriteFilter({ (item) -> KhalaNode in if item.url.scheme == "mt" { var urlComponents = URLComponents(url: item.url, resolvingAgainstBaseURL: true) urlComponents?.host = "MT_" + (item.url.host ?? "") item.url = urlComponents?.url ?? item.url return item }else{ return item } })) self.view.addSubview(webview) self.view.addSubview(btn) btn.snp.makeConstraints { (make) in make.top.equalTo(self.topLayoutGuide.snp.bottom) make.left.right.equalToSuperview() make.height.equalTo(45) } webview.snp.makeConstraints({ (make) in make.top.equalTo(btn.snp.bottom) make.left.right.equalToSuperview() make.bottom.equalTo(self.bottomLayoutGuide.snp.top) }) btn.setTitleColor(UIColor.black, for: UIControl.State.normal) btn.backgroundColor = UIColor.yellow btn.layer.cornerRadius = 5 btn.layer.masksToBounds = true btn.setTitle("reload", for: UIControl.State.normal) btn.addTarget(self, action: #selector(tapEvent(_:)), for: UIControl.Event.touchUpInside) } @IBAction func tapEvent(_ sender: UIButton) { // let url = URL(string: "http://127.0.0.1:8081/")! // let url = URL(string: "https://m.3pzs.com/")! let url = URL(string: "https://ci.linhey.com/")! webview.load(URLRequest(url: url)) } } <file_sep>/Example/Marmot/extensions/location.swift // // location.swift // Marmot_Example // // Created by linhey on 2019/1/16. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala import CoreLocation import Stem @objc(MT_location) @objcMembers class MT_location: NSObject, CLLocationManagerDelegate { func select(_ closure: @escaping KhalaClosure) { let vc = MTMapViewController(closure: closure) UIViewController.current?.st.push(vc: vc) } private lazy var manager: CLLocationManager = { let manager = CLLocationManager() manager.desiredAccuracy = kCLLocationAccuracyKilometer manager.distanceFilter = 100 manager.delegate = self manager.requestWhenInUseAuthorization() return manager }() private var fetchClosures = [KhalaClosure](){ didSet{ checkStopUpdate() } } private var updatingClosures = [Int: KhalaClosure](){ didSet{ checkStopUpdate() } } private var headingClosures = [Int: KhalaClosure](){ didSet{ checkStopUpdate() } } /// 单次定位 func fetch(_ closure: @escaping KhalaClosure) { guard CLLocationManager.locationServicesEnabled() else { closure(["error": "locationServicesEnabled is false"]) return } self.fetchClosures.append(closure) self.manager.requestLocation() } /// 持续更新定位 func updating(_ info: KhalaInfo, closure: @escaping KhalaClosure) { guard let label = info["label"] as? Int else { closure(["error": "缺少标识"]) return } self.updatingClosures[label] = closure self.manager.startUpdatingLocation() /// 优先返回上次定位结果 if let item = self.manager.location { let result = [ "alt": item.altitude, "lat": item.coordinate.latitude, "lng": item.coordinate.longitude ] closure(result) } } /// 移除定位更新 func stopUpdate(_ info: KhalaInfo) -> KhalaInfo { guard let label = info["label"] as? Int else { return ["error": "缺少标识"] } self.updatingClosures[label] = nil return [:] } /// 移除所有的定位更新 func stopAllUpdates() -> KhalaInfo { self.updatingClosures.removeAll() return [:] } /// 持续更新罗盘 func updatingHeading(_ info: KhalaInfo, closure: @escaping KhalaClosure) { guard CLLocationManager.headingAvailable() else { closure(["error": "not support heading"]) return } guard let label = info["label"] as? Int else { closure(["error": "缺少标识"]) return } self.headingClosures[label] = closure self.manager.startUpdatingHeading() } /// 移除罗盘更新 func stopHeadingUpdate(_ info: KhalaInfo) -> KhalaInfo { guard let label = info["label"] as? Int else { return ["error": "缺少标识"] } self.headingClosures[label] = nil return [:] } /// 移除所有的罗盘更新 func stopAllHeadingUpdate() -> KhalaInfo { self.headingClosures.removeAll() return [:] } } extension MT_location { private func checkStopUpdate() { if self.fetchClosures.isEmpty, CLLocationManager.significantLocationChangeMonitoringAvailable() { self.manager.stopMonitoringSignificantLocationChanges() } if self.updatingClosures.isEmpty { self.manager.stopUpdatingLocation() } if self.headingClosures.isEmpty { self.manager.stopUpdatingHeading() } } private func checkStartUpdate() { if !self.fetchClosures.isEmpty { if CLLocationManager.significantLocationChangeMonitoringAvailable() { self.manager.startMonitoringSignificantLocationChanges() }else { self.manager.startUpdatingLocation() } } if !self.updatingClosures.isEmpty { self.manager.startUpdatingLocation() } if !self.headingClosures.isEmpty { self.manager.startUpdatingHeading() } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways, .authorizedWhenInUse: self.checkStartUpdate() default: break } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let item = locations.first else { return } let result = [ "alt": item.altitude, "lat": item.coordinate.latitude, "lng": item.coordinate.longitude ] self.fetchClosures.forEach { (closure) in closure(result) } self.fetchClosures.removeAll() self.updatingClosures.forEach { (element) in element.value(result) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { let result = [ "error": error.localizedDescription ] self.fetchClosures.forEach { (closure) in closure(result) } self.fetchClosures.removeAll() self.updatingClosures.forEach { (element) in element.value(result) } } func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { let result = ["magneticHeading": newHeading.magneticHeading, "trueHeading": newHeading.trueHeading, "headingAccuracy": newHeading.headingAccuracy, "x": newHeading.x, "y": newHeading.y, "z": newHeading.z] self.headingClosures.forEach { (element) in element.value(result) } } } <file_sep>/Marmot/Assets/Marmot.js window.MTBridge = function (result) { var message = MTEvent.shared.find(result['url'], result['id']); if (!message) { return; } if (result['error']) { if (message._failure) message._failure(new Error(result['error'])); } else { if (message._success) message._success(result['value']); } if (message._complete) message._complete(result); if (message.type == MTMessageType.post) { MTEvent.shared.remove(result['url'], result['id']); return; } }; var MTEvent = /** @class */ (function () { function MTEvent() { /** * message 存储集合 * * @private * @type {({ [key: string]: { [key: number]: MTMessage | number; }; })} * @memberof MTEvent */ this.store = {}; } /** * 元素判空 * * @private * @param {Object} obj * @returns * @memberof MTEvent */ MTEvent.prototype.isEmpty = function (obj) { return !obj || Object.keys(obj).length === 0; }; /** * 添加 message 对象至集合 * * @param {MTMessage} message * @returns {MTMessage} * @memberof MTEvent */ MTEvent.prototype.update = function (message) { if (this.isEmpty(MTEvent.shared.store[message.url])) { MTEvent.shared.store[message.url] = {}; MTEvent.shared.store[message.url]['count'] = 0; } if (message.id) { MTEvent.shared.store[message.url][message.id] = message; } else { var count = MTEvent.shared.store[message.url]['count']; count += 1; MTEvent.shared.store[message.url]['count'] = count; message.id = count; MTEvent.shared.store[message.url][count] = message; } return message; }; /** * 查询 message 对象 * * @param {string} url * @param {number} id * @returns {(MTMessage | null)} * @memberof MTEvent */ MTEvent.prototype.find = function (url, id) { if (!MTEvent.shared.store[url]) return null; if (!MTEvent.shared.store[url][id]) return null; return MTEvent.shared.store[url][id]; }; /** * 移除 message 对象 * * @param {string} url * @param {number} id * @returns * @memberof MTEvent */ MTEvent.prototype.remove = function (url, id) { if (!MTEvent.shared.store[url]) return null; if (!MTEvent.shared.store[url][id]) return null; delete MTEvent.shared.store[url][id]; }; /** * 单例模式 * * @static * @memberof MTEvent */ MTEvent.shared = new MTEvent(); return MTEvent; }()); /** * 发送类型枚举 * * @enum {number} */ var MTMessageType; (function (MTMessageType) { MTMessageType["post"] = "post"; MTMessageType["listen"] = "listen"; })(MTMessageType || (MTMessageType = {})); var MTMessage = /** @class */ (function () { /** 初始化函数 *Creates an instance of NativeMessage. * @param {string} url * @memberof MTMessage */ function MTMessage(url) { this.url = url; } /** * 设置参数 * * @param {object} value * @returns {MTMessage} * @memberof MTMessage */ MTMessage.prototype.setParam = function (value) { this.params = value; return this; }; /** * 设置成功回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ MTMessage.prototype.success = function (cb) { this._success = cb; return this; }; /** * 设置失败回调 * * @param {(error: Error) => void} cb * @returns {MTMessage} * @memberof MTMessage */ MTMessage.prototype.failure = function (cb) { this._failure = cb; return this; }; /** * 设置完成回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ MTMessage.prototype.complete = function (cb) { this._complete = cb; return this; }; /** * 单次异步回调 * * @returns {Promise<object>} * @memberof MTMessage */ MTMessage.prototype.post = function () { var _this = this; var result; if (!this._success && !this._failure) { result = new Promise(function (resolve, reject) { _this._success = resolve; _this._failure = reject; }); } this.id = MTEvent.shared.update(this).id; this.type = MTMessageType.post; this.message = { id: this.id, url: this.url, param: this.params, type: this.type }; window.webkit.messageHandlers.marmot.postMessage(this.message); return result; }; /** * 监听 * * @returns {MTMessage} * @memberof MTMessage */ MTMessage.prototype.listen = function () { this.id = MTEvent.shared.update(this).id; this.type = MTMessageType.listen; this.message = { id: this.id, url: this.url, param: this.params, type: this.type }; window.webkit.messageHandlers.marmot.postMessage(this.message); return this; }; /** * 移除监听 * * @memberof MTMessage */ MTMessage.prototype.removeListen = function () { MTEvent.shared.remove(this.url, this.id); }; return MTMessage; }()); <file_sep>/Marmot/Assets/ts-core/MTMessage.ts /** * 发送类型枚举 * * @enum {number} */ enum MTMessageType { post = 'post', listen = 'listen' } class MTMessage { /** * 发送至 app 端 url 链接. * * @type {string} * @memberof MTMessage */ public url: string; /** * message id * * @type {number} * @memberof MTMessage */ public id: number; /** * message 携带参数, 需要可解析为json字符串类型 * * @type {object} * @memberof MTMessage */ public params: object; /** * 发送类型 * * @type {MTMessageType} * @memberof MTMessage */ public type: MTMessageType; /** * 发送app数据 * * @type {object} * @memberof MTMessage */ public message: object; /** * 成功回调 * * @memberof MTMessage */ public _success: (value: object) => void; /** * 失败回调 * * @memberof MTMessage */ public _failure: (error: Error) => void; /** * 执行完成回调 * * @memberof MTMessage */ public _complete: (value: object) => void; /** 初始化函数 *Creates an instance of NativeMessage. * @param {string} url * @memberof MTMessage */ constructor(url: string) { this.url = url; } /** * 设置参数 * * @param {object} value * @returns {MTMessage} * @memberof MTMessage */ setParam(value: object): MTMessage { this.params = value return this } /** * 设置成功回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ success(cb: (value: object) => void): MTMessage { this._success = cb return this } /** * 设置失败回调 * * @param {(error: Error) => void} cb * @returns {MTMessage} * @memberof MTMessage */ failure(cb: (error: Error) => void): MTMessage { this._failure = cb return this } /** * 设置完成回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ complete(cb: (value: object) => void): MTMessage { this._complete = cb return this } /** * 单次异步回调 * * @returns {Promise<object>} * @memberof MTMessage */ post(): Promise<object> { var result: Promise<object>; if (!this._success && !this._failure) { result = new Promise((resolve, reject) => { this._success = resolve this._failure = reject }); } this.id = MTEvent.shared.update(this).id this.type = MTMessageType.post this.message = { id: this.id, url: this.url, param: this.params, type: this.type } window.webkit.messageHandlers.marmot.postMessage(this.message); return result } /** * 监听 * * @returns {MTMessage} * @memberof MTMessage */ listen(): MTMessage { this.id = MTEvent.shared.update(this).id this.type = MTMessageType.listen this.message = { id: this.id, url: this.url, param: this.params, type: this.type } window.webkit.messageHandlers.marmot.postMessage(this.message); return this } /** * 移除监听 * * @memberof MTMessage */ removeListen() { MTEvent.shared.remove(this.url, this.id) } } <file_sep>/Example/Marmot/extensions/events.swift // // events.swift // Marmot_Example // // Created by linhey on 2019/1/17. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala extension UIWindow { open override func becomeFirstResponder() -> Bool { return true } } @objc(MT_events) @objcMembers class MT_events: UIResponder { private var shakeEvents = [KhalaClosure](){ didSet{ print("----") } } func shakeDetected(_ closure: @escaping KhalaClosure) { UIApplication.shared.applicationSupportsShakeToEdit = true self.becomeFirstResponder() shakeEvents.append(closure) } override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { } override func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { shakeEvents.forEach { (closure) in closure(["ans":"ok"]) } // shakeEvents.removeAll() } } <file_sep>/Marmot.podspec Pod::Spec.new do |s| s.name = 'Marmot' s.version = '0.1.2' s.summary = 'A javascript bridge with khala.' s.homepage = 'https://github.com/Marmot-App/Marmot-iOS' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'linhay' => '<EMAIL>' } s.source = { :git => 'https://github.com/Marmot-App/Marmot-iOS.git', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.swift_version = '4.2' s.source_files = 'Marmot/Classes/**/*' s.resource_bundles = { 'Marmot' => ['Marmot/Assets/*.js'] } s.dependency 'Khala', '0.1.0' end <file_sep>/Example/Marmot/extensions/clipboard.swift // // clipboard.swift // Marmot_Example // // Created by linhey on 2019/1/16. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala @objc(MT_clipboard) @objcMembers class MT_clipboard: NSObject { func setText(_ info: KhalaInfo) { UIPasteboard.general.string = info["value"] as? String ?? "" } func text() -> KhalaInfo { return ["value": UIPasteboard.general.string ?? ""] } } <file_sep>/Example/Marmot/extensions/qrcode/qrcode.swift // // qrcode.swift // Marmot_Example // // Created by linhey on 2019/1/17. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala import Stem @objc(MT_qrcode) @objcMembers class MT_qrcode: NSObject { func scan(_ info: KhalaInfo, closure: @escaping KhalaClosure) { let vc = QrcodeViewController(closure: closure) UIViewController.current?.st.push(vc: vc) } func decode(_ info: KhalaInfo) { let data = Data(bytes: [10,1,2]) } } <file_sep>/Example/Marmot/extensions/message.swift // // message.swift // Marmot_Example // // Created by linhey on 2019/1/23. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala import MessageUI import Stem @objc(MT_message) @objcMembers class MT_message: NSObject { /// 发送短信 /// /// - Parameter params: 号码: value(string) /// - Returns: 错误信息 func sms(_ info: KhalaInfo, closure: KhalaClosure) { if MFMessageComposeViewController.canSendText() { let vc = MFMessageComposeViewController() vc.recipients = info["recipients"] as? [String] vc.body = info["body"] as? String vc.subject = info["subject"] as? String // todo // attachments = info["attachments"] as? [Any] vc.messageComposeDelegate = self UIViewController.current?.st.present(vc: vc) }else { closure(["error": "无法调起短信界面"]) } } } extension MT_message: MFMessageComposeViewControllerDelegate { func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { controller.dismiss(animated: true, completion: nil) switch result { case .sent: break case .cancelled: break case .failed: break } } } <file_sep>/Marmot/Classes/MarmotHandler.swift // // Marmot // // Copyright (c) 2017 linhay - https://github.com/linhay // // 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 import UIKit import WebKit import Khala class MarmotHandler:NSObject, WKScriptMessageHandler { weak var webview: WKWebView? = nil init(webview: WKWebView) { super.init() self.webview = webview } func eval(dict: [String:Any]) { do { let data = try JSONSerialization.data(withJSONObject: dict, options: []) guard let json = String(data: data, encoding: .utf8) else { return } webview?.evaluateJavaScript("MTBridge(\(json))", completionHandler: { (result, error) in if error != nil { print(error?.localizedDescription ?? "") } }) } catch { print(error.localizedDescription) } } func actionHandler(message: MarmotMessage) { var result = message.body var params = message.params ?? [:] params.updateValue(self, forKey: "webview") params.updateValue(["id": message.id], forKey: "request") guard let value = Khala(str: message.url,params: params)?.call(block: { // 处理属性赋值 if $0["value"] == nil { result["value"] = $0 } else{ result["value"] = $0["value"] } self.eval(dict: result) }) else { return } // 处理属性赋值 if let value = value as? KhalaInfo, value["value"] != nil { result["value"] = value["value"] }else{ result["value"] = value } self.eval(dict: result) } public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let message = MarmotMessage(body: message.body) else { return } actionHandler(message: message) } } <file_sep>/Example/Marmot/js-extensions/Marmot.d.ts declare class MTEvent { /** * message 存储集合 * * @private * @type {({ [key: string]: { [key: number]: MTMessage | number; }; })} * @memberof MTEvent */ private store; /** * 单例模式 * * @static * @memberof MTEvent */ static shared: MTEvent; private constructor(); /** * 元素判空 * * @private * @param {Object} obj * @returns * @memberof MTEvent */ private isEmpty; /** * 添加 message 对象至集合 * * @param {MTMessage} message * @returns {MTMessage} * @memberof MTEvent */ update(message: MTMessage): MTMessage; /** * 查询 message 对象 * * @param {string} url * @param {number} id * @returns {(MTMessage | null)} * @memberof MTEvent */ find(url: string, id: number): MTMessage | null; /** * 移除 message 对象 * * @param {string} url * @param {number} id * @returns * @memberof MTEvent */ remove(url: string, id: number): any; } /** * 发送类型枚举 * * @enum {number} */ declare enum MTMessageType { post = "post", listen = "listen" } declare class MTMessage { /** * 发送至 app 端 url 链接. * * @type {string} * @memberof MTMessage */ url: string; /** * message id * * @type {number} * @memberof MTMessage */ id: number; /** * message 携带参数, 需要可解析为json字符串类型 * * @type {object} * @memberof MTMessage */ params: object; /** * 发送类型 * * @type {MTMessageType} * @memberof MTMessage */ type: MTMessageType; /** * 发送app数据 * * @type {object} * @memberof MTMessage */ message: object; /** * app 返回数据 * * @type {object} * @memberof MTMessage */ value: object; /** * app 返回错误 * * @type {Error} * @memberof MTMessage */ error: Error; /** * 成功回调 * * @memberof MTMessage */ _success: (value: object) => void; /** * 失败回调 * * @memberof MTMessage */ _failure: (error: Error) => void; /** * 执行完成回调 * * @memberof MTMessage */ _complete: (value: object) => void; /** 初始化函数 *Creates an instance of NativeMessage. * @param {string} url * @memberof MTMessage */ constructor(url: string); /** * 设置参数 * * @param {object} value * @returns {MTMessage} * @memberof MTMessage */ setParam(value: object): MTMessage; /** * 设置成功回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ success(cb: (value: object) => void): MTMessage; /** * 设置失败回调 * * @param {(error: Error) => void} cb * @returns {MTMessage} * @memberof MTMessage */ failure(cb: (error: Error) => void): MTMessage; /** * 设置完成回调 * * @param {(value: object) => void} cb * @returns {MTMessage} * @memberof MTMessage */ complete(cb: (value: object) => void): MTMessage; /** * 单次异步回调 * * @returns {Promise<object>} * @memberof MTMessage */ post(): Promise<object>; /** * 监听 * * @returns {MTMessage} * @memberof MTMessage */ listen(): MTMessage; /** * 移除监听 * * @memberof MTMessage */ removeListen(): void; } <file_sep>/Example/Marmot/js-extensions/MT.js /** * 在这里可以获取和设备有关的一些信息,例如设备语言、设备型号等等。 * * @class MT_device */ var MT_device = /** @class */ (function () { function MT_device() { this.baseURL = 'mt://device/'; } /** * 获取系统信息 * * @returns {MTMessage} * @memberof MT_device */ MT_device.prototype.info = function () { return new MTMessage(this.baseURL + 'info'); }; /** * 获取设备的内存/磁盘空间: */ MT_device.prototype.space = function () { return new MTMessage(this.baseURL + 'space'); }; /** * 在有 Taptic Engine 的设备上触发一个轻微的振动 * level: 0 ~ 2 表示振动等级 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ MT_device.prototype.taptic = function (level) { return new MTMessage(this.baseURL + 'taptic').setParam({ value: level }); }; /** * 打开/关闭 手电筒 * level: 0 ~ 1 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ MT_device.prototype.torch = function (level) { return new MTMessage(this.baseURL + 'torch').setParam({ value: level }); }; return MT_device; }()); /** * 剪贴板对于 iOS 的数据分享和交换很重要 * * @class MT_clipboard */ var MT_clipboard = /** @class */ (function () { function MT_clipboard() { this.baseURL = 'mt://clipboard/'; } /** * 获取剪切板上文本 * * @returns {MTMessage} * @memberof MT_clipboard */ MT_clipboard.prototype.text = function () { return new MTMessage(this.baseURL + 'text'); }; /** * 设置剪切板上文本 * * @param {string} value * @returns {MTMessage} * @memberof MT_clipboard */ MT_clipboard.prototype.setText = function (value) { return new MTMessage(this.baseURL + 'setText').setParam({ value: value }); }; return MT_clipboard; }()); /** * 和 iOS 系统本身相关的接口 * * @class MT_system */ var MT_system = /** @class */ (function () { function MT_system() { this.baseURL = 'mt://system/'; } /** * 设置/获取 屏幕亮度 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.brightness = function (level) { return new MTMessage(this.baseURL + 'brightness').setParam({ value: level }); }; /** * 设置/获取 系统音量 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.volume = function (level) { return new MTMessage(this.baseURL + 'volume').setParam({ value: level }); }; /** * 拨打电话 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.call = function (number) { return new MTMessage(this.baseURL + 'call').setParam({ value: number }); }; /** * 发送短信 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.sms = function (number) { return new MTMessage(this.baseURL + 'sms').setParam({ value: number }); }; /** * 发送邮件 * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.mailto = function (address) { return new MTMessage(this.baseURL + 'mailto').setParam({ value: address }); }; /** * FaceTime * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ MT_system.prototype.facetime = function (address) { return new MTMessage(this.baseURL + 'facetime').setParam({ value: address }); }; return MT_system; }()); /** * 用于与系统自带的传感器交互,例如获取加速度 * * @class MT_motion */ var MT_motion = /** @class */ (function () { function MT_motion() { this.baseURL = 'mt://motion/'; } /** * 开始监听 传感器 * * @param {number} [updateInterval=0.1] * @returns {MTMessage} * @memberof MT_motion */ MT_motion.prototype.startUpdates = function (updateInterval) { if (updateInterval === void 0) { updateInterval = 0.1; } return new MTMessage(this.baseURL + 'startUpdates').setParam({ updateInterval: updateInterval }); }; /** * 停止监听传感器 * * @returns {MTMessage} * @memberof MT_motion */ MT_motion.prototype.stopUpdates = function (message) { message.removeListen(); return new MTMessage(this.baseURL + 'stopUpdates').post(); }; return MT_motion; }()); var MT_location = /** @class */ (function () { function MT_location() { this.baseURL = 'mt://location/'; /** * 监听地理位置更新标识 * * @type {number} * @memberof MT_location */ this.updatingLabel = 0; /** * 监听罗盘更新标识 * * @type {number} * @memberof MT_location */ this.updatingHeadingLabel = 0; } /** * 从地图上选择一个点 * * @returns {MTMessage} * @memberof MT_location */ MT_location.prototype.select = function () { return new MTMessage(this.baseURL + 'select'); }; /** * 单次定位 * * @returns {MTMessage} * @memberof MT_location */ MT_location.prototype.fetch = function () { return new MTMessage(this.baseURL + 'fetch'); }; /** * 监听地理位置更新 * * @returns {MTMessage} * @memberof MT_location */ MT_location.prototype.updating = function () { this.updatingLabel += 1; return new MTMessage(this.baseURL + 'updating').setParam({ label: this.updatingLabel }); }; /** * 停止地理位置更新 * * @param {MTMessage} message * @memberof MT_location */ MT_location.prototype.stopUpdate = function (message) { new MTMessage(this.baseURL + 'stopUpdate').setParam({ label: message.params["label"] }).post(); }; /** * 停止所有的地理位置更新 * * @returns * @memberof MT_location */ MT_location.prototype.stopAllUpdates = function () { new MTMessage(this.baseURL + 'stopAllUpdates').post(); }; /** * 监听罗盘更新 * * @returns * @memberof MT_location */ MT_location.prototype.updatingHeading = function () { this.updatingLabel += 1; return new MTMessage(this.baseURL + 'updatingHeading').setParam({ label: this.updatingHeadingLabel }); }; /** * 移除罗盘更新 * * @param {MTMessage} message * @memberof MT_location */ MT_location.prototype.stopHeadingUpdate = function (message) { new MTMessage(this.baseURL + 'stopHeadingUpdate').setParam({ label: message.params["label"] }).post(); }; /** * 移除所有的罗盘更新 * * @returns * @memberof MT_location */ MT_location.prototype.stopAllHeadingUpdate = function () { new MTMessage(this.baseURL + 'stopAllHeadingUpdate').post(); }; return MT_location; }()); var MT_qrcode = /** @class */ (function () { function MT_qrcode() { this.baseURL = 'mt://qrcode/'; } MT_qrcode.prototype.scan = function () { return new MTMessage(this.baseURL + 'scan'); }; return MT_qrcode; }()); var MT_events = /** @class */ (function () { function MT_events() { this.baseURL = 'mt://events/'; } MT_events.prototype.shakeDetected = function () { return new MTMessage(this.baseURL + 'shakeDetected'); }; return MT_events; }()); var MT = /** @class */ (function () { function MT() { this.device = new MT_device(); this.clipboard = new MT_clipboard(); this.system = new MT_system(); this.motion = new MT_motion(); this.location = new MT_location(); this.qrcode = new MT_qrcode(); this.events = new MT_events(); } return MT; }()); window.mt = new MT(); <file_sep>/Example/Marmot/extensions/qrcode/QrcodeViewController.swift import UIKit import SnapKit import Stem import AVFoundation import Khala class QrcodeViewController: UIViewController { lazy var captureSession: AVCaptureSession = { return AVCaptureSession() }() let device = AVCaptureDevice.default(for: .video) lazy var videoPreviewLayer:AVCaptureVideoPreviewLayer = { let item = AVCaptureVideoPreviewLayer(session: captureSession) item.videoGravity = AVLayerVideoGravity.resizeAspectFill return item }() lazy var qrCodeFrameView: UIView = { // 初始化二维码选框并高亮边框 let item = UIView() item.layer.borderColor = UIColor.green.cgColor item.layer.borderWidth = 2 self.view.addSubview(item) self.view.bringSubviewToFront(item) return item }() lazy var messageLabel = UILabel() lazy var torchBtn: UIButton = { let item = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) item.isHidden = true guard let image = UIImage(named: "torch") else { return item } item.setImage(image.st.setTint(color: UIColor.white), for: .normal) item.setImage(image.st.setTint(color: UIColor.lightGray), for: .highlighted) item.setImage(image.st.setTint(color: UIColor.green), for: .selected) item.titleLabel?.font = UIFont.systemFont(ofSize: 12) item.setTitle("轻触点亮", for: .normal) item.setTitle("轻触关闭", for: .selected) item.st.verticalCenterImageAndTitle(spacing: 5) item.st.add(for: UIControl.Event.touchUpInside, action: {_ in item.isSelected = !item.isSelected do{ try self.device?.lockForConfiguration() self.device?.torchMode = item.isSelected ? .on : .off self.device?.unlockForConfiguration() }catch { print(error) } }) self.view.addSubview(item) item.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.equalTo(item.width) make.height.equalTo(item.height) } return item }() var closure: KhalaClosure? = nil init(closure: @escaping KhalaClosure) { super.init(nibName: nil, bundle: nil) self.closure = closure } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() if let device = device, let input = try? AVCaptureDeviceInput(device: device), captureSession.canAddInput(input) { captureSession.addInput(input) } do { let output = AVCaptureVideoDataOutput() if captureSession.canAddOutput(output) { captureSession.addOutput(output) } output.setSampleBufferDelegate(self, queue: DispatchQueue.main) } do { let output = AVCaptureMetadataOutput() if captureSession.canAddOutput(output) { captureSession.addOutput(output) } output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr] } videoPreviewLayer.frame = view.layer.bounds self.view.layer.addSublayer(videoPreviewLayer) // 开始视频捕获 captureSession.startRunning() view.addSubview(messageLabel) messageLabel.frame = CGRect(x: 0, y: 60, width: 200, height: 80) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) captureSession.stopRunning() } func authorization() { let status = AVCaptureDevice.authorizationStatus(for: .video) switch status { case .notDetermined: AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted) in granted ? self.configureCamera() : self.showErrorAlertView() }) case .authorized: self.configureCamera() default: self.showErrorAlertView() } } func configureCamera() { } func showErrorAlertView() { } func turnTorch(on: Bool) { guard device?.hasTorch ?? false else { return } torchBtn.isHidden = !on && (device?.torchMode != .on) } } extension QrcodeViewController: AVCaptureVideoDataOutputSampleBufferDelegate { public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let dict = CMCopyDictionaryOfAttachments(allocator: nil, target: sampleBuffer, attachmentMode: kCMAttachmentMode_ShouldPropagate) as? [String: Any], let exifMetadata = dict[kCGImagePropertyExifDictionary as String] as? [String: Any], let brightnessValue = exifMetadata[kCGImagePropertyExifBrightnessValue as String] as? Double else { return } let brightnessThresholdValue = -0.2 DispatchQueue.main.async { self.turnTorch(on: brightnessValue < brightnessThresholdValue) } } } extension QrcodeViewController: AVCaptureMetadataOutputObjectsDelegate { public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { // 检查:metadataObjects 对象不为空,并且至少包含一个元素 if metadataObjects.isEmpty { qrCodeFrameView.frame = CGRect.zero messageLabel.text = "No QR code is detected" return } // 获得元数据对象 let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if metadataObj.type == AVMetadataObject.ObjectType.qr { // 如果元数据是二维码,则更新二维码选框大小与 label 的文本 let barCodeObject = videoPreviewLayer.transformedMetadataObject(for: metadataObj) qrCodeFrameView.frame = barCodeObject!.bounds if metadataObj.stringValue != nil { closure?(["value": metadataObj.stringValue ?? ""]) closure = nil self.dismiss(animated: true, completion: nil) self.st.pop(animated: true) // messageLabel.text = metadataObj.stringValue } } } } <file_sep>/Example/Marmot/MarmotURLProtocol.swift // // MarmotURLRequest.swift // Marmot_Example // // Created by linhey on 2019/1/26. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import BLFoundation class MarmotURLRequest: URLProtocol, URLSessionDelegate { fileprivate static let WebviewImageProtocolHandledKey = "WebviewImageProtocolHandledKey" override class func canInit(with request: URLRequest) -> Bool{ guard let url = request.url?.absoluteString.lowercased() else { return false } let result = url.contains(".png") || url.contains(".jpg") || url.contains(".jpeg") || url.contains(".gif") guard result else { return false } guard (self.property(forKey: WebviewImageProtocolHandledKey, in: request) as? Bool ?? true) else { return false } // print(url) return true } override init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(request: request, cachedResponse: cachedResponse, client: client) } override class func canonicalRequest(for request: URLRequest) -> URLRequest{ return request } override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { return super.requestIsCacheEquivalent(a, to: b) } static let cache: NSCache<NSString,NSData> = { let item = NSCache<NSString,NSData>() return item }() static let imagesPath: String = { let lib = NSSearchPathForDirectoriesInDomains(.libraryDirectory,.userDomainMask, true).first! print("\(lib)/com.marmot.linhey/images/") return "\(lib)/com.marmot.linhey/images/" }() override func startLoading() { //在磁盘上找到Kingfisher的缓存,则直接使用缓存 func didLoad(with data: Data) { var mimeType = data.contentTypeForImageData() mimeType.append(";charset=UTF-8") let header = ["Content-Type": mimeType, "Content-Length": String(data.count)] let response = HTTPURLResponse(url: self.request.url!, statusCode: 200, httpVersion: "1.1", headerFields: header)! self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) self.client?.urlProtocol(self, didLoad: data) self.client?.urlProtocolDidFinishLoading(self) } func write(data: Data, key: String) { DispatchQueue.global().async { let fileManager = FileManager.default let path = MarmotURLRequest.imagesPath if !fileManager.fileExists(atPath: path) { do { try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } catch _ {} } fileManager.createFile(atPath: path + key, contents: data, attributes: nil) print("cached: \(key)") } } guard let url = self.request.url else { return } let key = url.absoluteString.md5 if let data = MarmotURLRequest.cache.object(forKey: key as NSString) as Data? { print("hitted: \(key)") didLoad(with: data) return } if let data = try? Data(contentsOf:URL(fileURLWithPath: MarmotURLRequest.imagesPath + key)) { print("hitted disk: \(key)") MarmotURLRequest.cache.setObject(data as NSData, forKey: key as NSString) didLoad(with: data) return } guard let request = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else { return } MarmotURLRequest.setProperty(true, forKey: MarmotURLRequest.WebviewImageProtocolHandledKey, in: request) URLSession(configuration: .default).dataTask(with: self.request, completionHandler: { (data, response, error) in print("caching: \(url)") if let error = error { self.client?.urlProtocol(self, didFailWithError: error) return } if let data = data, let response = response { self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed) self.client?.urlProtocol(self, didLoad: data) MarmotURLRequest.cache.setObject(data as NSData, forKey: key as NSString) write(data: data, key: key) return } }).resume() } override func stopLoading() { } } fileprivate extension Data { func contentTypeForImageData() -> String { var c:UInt8 = 0 self.copyBytes(to: &c, count: MemoryLayout<UInt8>.size * 1) switch c { case 0xFF: return "image/jpeg"; case 0x89: return "image/png"; case 0x47: return "image/gif"; default: return "" } } } <file_sep>/Example/Marmot/extensions/device.swift // // File.swift // Marmot-iOS // // Created by linhey on 2018/7/6. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import Khala import SystemConfiguration import SystemConfiguration.CaptiveNetwork import AudioToolbox import BLFoundation import Marmot import Stem @objc(MT_device) @objcMembers class MT_device: NSObject { /// 获取系统信息 func info() -> KhalaInfo { var result = KhalaInfo() result["screen"] = [ "orientation": UIDevice.current.orientation.rawValue, "width": UIScreen.main.bounds.width, "height": UIScreen.main.bounds.height, "scale": UIScreen.main.scale ] result["battery"] = [ "state": UIDevice.current.batteryState.rawValue, "level": UIDevice.current.batteryLevel ] result["version"] = UIApplication.shared.st.info result["language"] = Locale.preferredLanguages.first result["model"] = Device.version.rawValue return result } /// 在有 Taptic Engine 的设备上触发一个轻微的振动 /// /// - Parameter _info: value: 0 ~ 2 表示振动等级 func taptic(_ info: KhalaInfo) { if let value = info["value"] as? Int { UIDevice.current.st.taptic(level: value,isSupportTaptic: false) } } /// 打开/关闭 手电筒 /// /// - Parameter info: value: 0 ~ 1 func torch(_ info: KhalaInfo) -> KhalaInfo { if let value = info["value"] as? Double { UIDevice.current.st.torch(level: value) } return ["value": UIDevice.current.st.torchLevel] } /// 获取设备的内存/磁盘空间: func space() -> KhalaInfo { func toInfo(size: Int) -> [String: Any] { if size > 1000 * 1000 * 1000 { return ["bytes": size, "string": String(format: "%.2f GB", Double(size) / 1000000000)] } if size > 1000 * 1000 { return ["bytes": size, "string": String(format: "%.2f MB", Double(size) / 1000000)] } if size > 1000 { return ["bytes": size, "string": String(format: "%.2f KB", Double(size) / 1000)] } return ["bytes": size, "string": String(format: "%.2f B", Double(size))] } var result = KhalaInfo() result["disk"] = [ "free": toInfo(size: Device.diskSpace.free), "total": toInfo(size: Device.diskSpace.total) ] result["memory"] = [ "free": toInfo(size: Device.memorySpace.free), "used": toInfo(size: Device.memorySpace.used), "total": toInfo(size: Int(ProcessInfo.processInfo.physicalMemory)) ] return result } } <file_sep>/Example/Marmot/js-extensions/MT.d.ts /** * 在这里可以获取和设备有关的一些信息,例如设备语言、设备型号等等。 * * @class MT_device */ declare class MT_device { private baseURL; /** * 获取系统信息 * * @returns {MTMessage} * @memberof MT_device */ info(): MTMessage; /** * 获取设备的内存/磁盘空间: */ space(): MTMessage; /** * 在有 Taptic Engine 的设备上触发一个轻微的振动 * level: 0 ~ 2 表示振动等级 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ taptic(level: string): MTMessage; /** * 打开/关闭 手电筒 * level: 0 ~ 1 * @param {string} level * @returns {MTMessage} * @memberof MT_device */ torch(level: string): MTMessage; } /** * 剪贴板对于 iOS 的数据分享和交换很重要 * * @class MT_clipboard */ declare class MT_clipboard { private baseURL; /** * 获取剪切板上文本 * * @returns {MTMessage} * @memberof MT_clipboard */ text(): MTMessage; /** * 设置剪切板上文本 * * @param {string} value * @returns {MTMessage} * @memberof MT_clipboard */ setText(value: string): MTMessage; } /** * 和 iOS 系统本身相关的接口 * * @class MT_system */ declare class MT_system { private baseURL; /** * 设置/获取 屏幕亮度 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ brightness(level: number): MTMessage; /** * 设置/获取 系统音量 * * @param {number} value | 0 ~ 1之间 * @returns {MTMessage} * @memberof MT_system */ volume(level: number): MTMessage; /** * 拨打电话 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ call(number: string): MTMessage; /** * 发送短信 * * @param {string} number | 手机号码 * @returns {MTMessage} * @memberof MT_system */ sms(number: string): MTMessage; /** * 发送邮件 * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ mailto(address: string): MTMessage; /** * FaceTime * * @param {string} number | 邮件地址 * @returns {MTMessage} * @memberof MT_system */ facetime(address: string): MTMessage; } /** * 用于与系统自带的传感器交互,例如获取加速度 * * @class MT_motion */ declare class MT_motion { private baseURL; /** * 开始监听 传感器 * * @param {number} [updateInterval=0.1] * @returns {MTMessage} * @memberof MT_motion */ startUpdates(updateInterval?: number): MTMessage; /** * 停止监听传感器 * * @returns {MTMessage} * @memberof MT_motion */ stopUpdates(message: MTMessage): Promise<object>; } declare class MT_location { private baseURL; /** * 从地图上选择一个点 * * @returns {MTMessage} * @memberof MT_location */ select(): MTMessage; /** * 单次定位 * * @returns {MTMessage} * @memberof MT_location */ fetch(): MTMessage; /** * 监听地理位置更新标识 * * @type {number} * @memberof MT_location */ updatingLabel: number; /** * 监听地理位置更新 * * @returns {MTMessage} * @memberof MT_location */ updating(): MTMessage; /** * 停止地理位置更新 * * @param {MTMessage} message * @memberof MT_location */ stopUpdate(message: MTMessage): void; /** * 停止所有的地理位置更新 * * @returns * @memberof MT_location */ stopAllUpdates(): void; /** * 监听罗盘更新标识 * * @type {number} * @memberof MT_location */ updatingHeadingLabel: number; /** * 监听罗盘更新 * * @returns * @memberof MT_location */ updatingHeading(): MTMessage; /** * 移除罗盘更新 * * @param {MTMessage} message * @memberof MT_location */ stopHeadingUpdate(message: MTMessage): void; /** * 移除所有的罗盘更新 * * @returns * @memberof MT_location */ stopAllHeadingUpdate(): void; } declare class MT_qrcode { private baseURL; scan(): MTMessage; } declare class MT_events { private baseURL; shakeDetected(): MTMessage; } declare class MT { device: MT_device; clipboard: MT_clipboard; system: MT_system; motion: MT_motion; location: MT_location; qrcode: MT_qrcode; events: MT_events; } <file_sep>/Example/Marmot/extensions/file.swift // // file.swift // Marmot_Example // // Created by linhey on 2019/1/17. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit @objc(MT_file) @objcMembers class MT_file: NSObject { let manager = FileManager.default /// 读取文件 func read(_ info: [String: Any]) -> [String: Any] { guard let path = info["path"] as? String else { return ["error":"can't paeser path"] } guard manager.fileExists(atPath: path) else { return ["error":"file not exists at path: \(path)"] } guard manager.isReadableFile(atPath: path) else { return["error": "can't read file at path: \(path)"] } do{ let value = try String(contentsOfFile: path) return ["value": value] }catch{ return ["error": error.localizedDescription] } } } <file_sep>/Example/Podfile use_frameworks! install! 'cocoapods', :generate_multiple_pod_projects => true target 'Marmot_Example' do pod 'Marmot', :path => '../' pod 'SnapKit' pod 'BLFoundation', '0.9.1' pod 'Stem', '0.0.21' target 'Marmot_Tests' do inherit! :search_paths end end <file_sep>/Marmot/Assets/ts-core/MTEvent.ts class MTEvent { /** * message 存储集合 * * @private * @type {({ [key: string]: { [key: number]: MTMessage | number; }; })} * @memberof MTEvent */ private store: { [key: string]: { [key: number]: MTMessage | number; }; } = {}; /** * 单例模式 * * @static * @memberof MTEvent */ public static shared = new MTEvent(); private constructor() { } /** * 元素判空 * * @private * @param {Object} obj * @returns * @memberof MTEvent */ private isEmpty(obj: Object) { return !obj || Object.keys(obj).length === 0; } /** * 添加 message 对象至集合 * * @param {MTMessage} message * @returns {MTMessage} * @memberof MTEvent */ update(message: MTMessage): MTMessage { if (this.isEmpty(MTEvent.shared.store[message.url])) { MTEvent.shared.store[message.url] = {}; MTEvent.shared.store[message.url]['count'] = 0; } if (message.id) { MTEvent.shared.store[message.url][message.id] = message; } else { var count: number = <number>MTEvent.shared.store[message.url]['count']; count += 1; MTEvent.shared.store[message.url]['count'] = count; message.id = count; MTEvent.shared.store[message.url][count] = message; } return message; } /** * 查询 message 对象 * * @param {string} url * @param {number} id * @returns {(MTMessage | null)} * @memberof MTEvent */ find(url: string, id: number): MTMessage | null { if (!MTEvent.shared.store[url]) return null; if (!MTEvent.shared.store[url][id]) return null; return <MTMessage>MTEvent.shared.store[url][id]; } /** * 移除 message 对象 * * @param {string} url * @param {number} id * @returns * @memberof MTEvent */ remove(url: string, id: number) { if (!MTEvent.shared.store[url]) return null; if (!MTEvent.shared.store[url][id]) return null; delete MTEvent.shared.store[url][id]; } } <file_sep>/Example/Marmot/extensions/system.swift // // App.swift // Marmot_Example // // Created by linhey on 2019/1/7. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala import MessageUI import MediaPlayer import BLFoundation @objc(MT_system) @objcMembers class MT_system: NSObject { /// 设置屏幕亮度 /// /// - Parameter info: value(number) 0.0 ~ 1.0 /// - Returns: 亮度信息 { value: 0.1 ~ 1.0 } func brightness(_ info: KhalaInfo) -> KhalaInfo { if let value = info["value"] as? CGFloat { UIScreen.main.brightness = value return ["value": value] } return ["value": Double(UIScreen.main.brightness).round(places: 2)] } lazy var volumView = MPVolumeView(frame: CGRect(x: 0, y: 100, width: 100, height: 40)) /// 设置系统音量 /// /// - Parameter params: value(number) 0.0 ~ 1.0 /// - Returns: 音量信息 { value: 0.1 ~ 1.0 } func volume(_ info: KhalaInfo) -> KhalaInfo { let slider = volumView.subviews.first { (item) -> Bool in return item.description.contains("MPVolumeSlider") } as? UISlider volumView.removeFromSuperview() UIViewController.current?.view.addSubview(volumView) if let value = info["value"] as? Double { slider?.setValue(Float(value), animated: false) } volumView.removeFromSuperview() return ["value": Double(slider?.value ?? 0)] } /// 拨打电话 /// /// - Parameter params: 号码: value(string) /// - Returns: 错误信息 func call(_ info: KhalaInfo) -> KhalaInfo { if let value = info["value"] as? String { UIApplication.shared.st.open(url: "tel:" + value) }else{ return ["error": "号码不能为空"] } return [:] } /// 发送短信 /// /// - Parameter params: 号码: value(string) /// - Returns: 错误信息 func sms(_ info: KhalaInfo) -> KhalaInfo { if let value = info["value"] as? String { UIApplication.shared.st.open(url: "sms:" + value) } else{ return ["error": "号码:不能为空"] } return [:] } /// 发送邮件 /// /// - Parameter params: 目标邮箱: value(string) /// - Returns: 错误信息 func mailto(_ info: KhalaInfo) -> KhalaInfo { if let value = info["value"] as? String { UIApplication.shared.st.open(url: "mailto:" + value) }else{ return ["error": "邮件地址不能为空"] } return [:] } /// FaceTime /// /// - Parameter params: 目标邮箱: value(string) /// - Returns: 错误信息 func facetime(_ info: KhalaInfo) -> KhalaInfo? { if let value = info["value"] as? String { UIApplication.shared.st.open(url: "facetime:" + value) }else{ return ["error": "邮件地址不能为空"] } return [:] } func makeIcon(params: KhalaInfo) -> KhalaInfo? { return nil } } <file_sep>/Marmot/Assets/ts-core/MTMessageType.ts /** * 发送类型枚举 * * @enum {number} */ export enum MTMessageType { post = 'post', listen = 'listen' } <file_sep>/Example/Marmot/extensions/wx.swift // // wx.swift // Marmot_Example // // Created by linhey on 2019/1/23. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import Khala import BLFoundation import WebKit import Marmot struct WXAPPInfo { static let version = "1.0.0" } @objc(MT_wx) @objcMembers class MT_wx: NSObject { /// 获取系统信息 func getSystemInfo(_ info: KhalaInfo) -> KhalaInfo { guard let webview = info["webview"] as? WKWebView else { return ["error": "webview 未获取到"] } return [ "brand": Device.type.rawValue, "model": Device.version.rawValue, "pixelRatio": UIScreen.main.scale, "screenWidth": UIScreen.main.bounds.width * UIScreen.main.scale, "screenHeight": UIScreen.main.bounds.height * UIScreen.main.scale, "windowWidth": UIScreen.main.bounds.height * webview.frame.width, "windowHeight": UIScreen.main.bounds.height * webview.frame.height, "statusBarHeight": UIScreen.main.bounds.height * UIApplication.shared.statusBarFrame.height, "language": Locale.current.languageCode ?? "", "version": WXAPPInfo.version, "system": UIDevice.current.systemName + " - " + UIDevice.current.systemVersion, "platform": Device.type.rawValue, "fontSizeSetting": "", // "SDKVersion": Marmot.version, "benchmarkLevel": 50 ] } } <file_sep>/Marmot/Assets/ts-core/MTBridge.ts window.MTBridge = (result) => { var message = MTEvent.shared.find(result['url'], result['id']) if (!message) { return } if (result['error']) { if (message._failure) message._failure(new Error(result['error'])); } else { if (message._success) message._success(result['value']); } if (message._complete) message._complete(result) if (message.type == MTMessageType.post) { MTEvent.shared.remove(result['url'], result['id']) return } }
a996185b032073089df202904b0e822d99954a6f
[ "Swift", "TypeScript", "JavaScript", "Ruby" ]
27
Swift
Marmot-App/Marmot-iOS
d26b06b802c6870c88653d6249077140963c9232
a9bf1fcb4449a0128acb825072ca33e322ff43c8
refs/heads/master
<file_sep><?php // this sample of builder design pattern create a string that compatible with SQL syntax from user values // for example create "SELECT name, family FROM users WHERE name = 'amin' AND age > 14" // with this command : // echo $obj -> select('users',['name','family'])->where('name','amin')->where('age',14,'>')->getSQL(); class MYSQLBUILDER { public $query; public function reset(){ $this -> query = new stdclass; } public function select($table,$fields = ['*']){ $this->reset(); $this->query->type = "select"; $this->query->base = "SELECT " . implode(', ', $fields) . " FROM " . $table; return $this; } // INSERT INTO users () VALUES (); public function insert($table,$fields,$values){ $this->reset(); $this->query->type = "insert"; $this->query->base = "INSERT INTO " . $table . " ( " . implode(", ",$fields) . " ) VALUES ( " . implode(", ",$values) . " )"; return $this; } public function where ($field,$value,$operand = "=") { if(!in_array($this->query->type, ['select','delete','update'])){ echo "WHERE section not applied for this type of SQL ( " . $this -> query -> type . " ) <br>" ; return $this; } $this->query->where[] = " $field $operand $value "; return $this; } public function getSQL (){ $query = $this->query->base; if(!empty($this->query->where)){ $query .= " WHERE " . implode(" AND ", $this->query->where) . " ;"; } return $query; } } $obj = new MYSQLBUILDER; echo $obj -> select('users')->where('name','amin')->where('age',14,'>')->getSQL(); echo "<hr>"; echo $obj ->insert('users', ['name','family','age'], ['behrang','raadmanesh',12] )->where('id',10)->getSQL(); echo "<hr>"; echo $obj ->insert('users',['name','family','age'],['behrang','raadmanesh',12])->getSQL(); ?> <file_sep><?php namespace one; const a = 'salam'; namespace two; const a = 'khodaahaafez'; echo \one\a; ?><file_sep><?php interface Handler{ public function setNext(Handler $handler): Handler; public function handle(string $request): ?string; } abstract class AbstractHandler implements Handler{ private $nextHandler; public function setNext(Handler $handler): Handler{ $this->nextHandler = $handler; return $handler; } public function handle(string $request): ?string{ if ($this->nextHandler) { return $this->nextHandler->handle($request); } return null; } } class MonkeyHandler extends AbstractHandler{ public function handle(string $request): ?string{ if($request === 'Banana'){ return "Monkey: I'll eat the " . $request; } else{ return parent::handle($request); } } } class FishHandler extends AbstractHandler{ public function handle(string $request): ?string{ if($request === 'fishFood'){ return "Fish: I'll eat the " . $request; } else{ return parent::handle($request); } } } class DogHandler extends AbstractHandler{ public function handle(string $request): ?string{ if($request === 'Meat'){ return "Dog: I'll eat the " . $request; } else{ return parent::handle($request); } } } function clientCode(Handler $handler){ foreach(['fishFood', 'Burger', 'Tea', 'Banana', 'Meat'] as $food){ echo " Client : Who wants ". $food. '?'; $result = $handler->handle($food); if($result){ echo ' '. $result; } else{ echo " ". $food . " was left untouched"; } } } $monkey = new MonkeyHandler; $fish = new FishHandler; $dog = new DogHandler; $monkey->setNext($fish)->setNext($dog); echo "Chain : Monkey > Fish > Dog" . ' '; clientCode($monkey); echo ' '; echo "subChain : Fish > Dog" . ' '; clientCode($fish); <file_sep><?php class MysqlQueryBuilder { protected $query; protected function reset() { $this->query = new \stdClass; } public function select(string $table, array $fields) { $this->reset(); $this->query->base = "SELECT ". implode(", ", $fields) . " FROM " . $table; //print_r($this->query->base); $this->query->type = 'select'; return $this; } public function where(string $field, string $value, string $operator = '=') { if (!in_array($this->query->type, ['select', 'update', 'delete'])){ return false; } $this->query->where[] = "$field $operator '$value'"; return $this; } public function getSQL(){ $query = $this->query; $sql = $query->base; if(!empty($query->where)){ $sql .= " WHERE " . implode(' AND ', $query->where); } $sql .= ";"; return $sql; } } function clientCode(MysqlQueryBuilder $queryBuilder){ // $query = $queryBuilder->select('users', ['email', 'username'])->getSQL(); $query = $queryBuilder->select('users', ['email'])->where("id", 1, ">")->getSQL(); //$query = $queryBuilder->select('users', ['email'])->where('id', 1)->getSQL(); echo $query; } clientCode(new MysqlQueryBuilder); ?><file_sep><?php class Phones { static protected $model; public function brand($value) { self::$model .= "$value "; return new static; } public function ver($value){ self::$model .= "$value "; return new static; } public function ability($value){ self::$model .= "$value "; return new static; } public function madeIn($value) { self::$model .= "$value "; echo self::$model; } } Phones::brand('samsung')->ver(12)->ability('sms')->madeIn('korean'); ?> <file_sep><?php class Person { private $attribiutes; public function fName ($value) { $this -> attribiutes .= "first name : $value "; return $this; } public function lName ($value) { $this -> attribiutes .= "last name : $value "; return $this; } public function age ($value) { $this -> attribiutes .= "age : $value "; return $this; } public function getAttr(){ return $this->attribiutes; } } $obj1 = new Person; $obj1 ->fName('amin') -> lName('<NAME>') -> age(39); echo $obj1 ->getAttr(); ?><file_sep><?php class Person { private $name; public function __construct($name){ $this -> name = $name; } public function echoName(){ echo $this->name; } /* abstract public function showName(){ echo $this->name; } */ abstract public function viewName(); } class Iranian extends Person { public function viewName(){ echo $this->name; } } $person = new Iranian('ali'); //$person ->echoName(); ?><file_sep><?php class Najjar { private $nextHandler; public function setNext( $handler){ $this->nextHandler = $handler; return $this -> nextHandler; } public function handle( $request){ if ($this->nextHandler) { return $this->nextHandler->doIt($request); } return null; } public function doIt( $request){ if($request === 'KaareChoob'){ return "Najjar: " . $request . " ro be ohde migiram \n"; } else{ return $this->handle($request); } } } class Ahangar { private $nextHandler; public function setNext( $handler){ $this->nextHandler = $handler; return $this -> nextHandler; } public function handle( $request){ if ($this->nextHandler) { return $this->nextHandler->doIt($request); } return null; } public function doIt( $request){ if($request === 'KaareFellezi'){ return "Ahangar: " . $request . " ro be ohde migiram \n"; } else{ return $this->handle($request); } } } class Banna { private $nextHandler; public function setNext( $handler){ $this->nextHandler = $handler; return $this -> nextHandler; } public function handle( $request){ if ($this->nextHandler) { return $this->nextHandler->doIt($request); } return null; } public function doIt( $request){ if($request === 'KaareSaakhtemaani'){ return "Banna: " . $request . " ro be ohde migiram \n"; } else{ return $this->handle($request); } } } class Mohandes { private $nextHandler; public function setNext( $handler){ $this->nextHandler = $handler; return $this -> nextHandler; } public function handle( $request){ if ($this->nextHandler) { return $this->nextHandler->doIt($request); } return null; } public function doIt( $request){ if($request === 'KaareSaakhtemaani'){ return "Mohandes: " . $request . " ro be ohde migiram \n"; } else{ return $this->handle($request); } } } function clientCode($handler,$request){ echo $handler->doIt($request); } $bahman = new Ahangar; $bijan = new Banna; $ramtin = new Najjar; $soroush = new Mohandes; $bahman->setNext($bijan)->setNext($ramtin)->setNext($soroush); while(true) { clientCode($bahman,readline()); } ?><file_sep><?php class Manager { static private $instance = null; private function __construct () { // do some and is not important } static public function getInstance(){ if(self::$instance === null ) { self::$instance = new Manager; } return self::$instance; } } $obj = Manager::getInstance(); var_dump($obj); ?><file_sep><?php // chain of responsibilty design pattern sample // main handler structure interface Handler { public function setNext(Handler $handler) : Handler; public function passToNext(string $request ) : ? string; } abstract class MainHandler implements Handler{ private $nextHandler; public function setNext(Handler $handler) : Handler { $this -> nextHandler = $handler; return $handler; } public function passToNext(string $request ) : ? string { if($this->nextHandler){ return $this->nextHandler->handle($request); // [_] check konam cheraa return } else { return null; } } abstract public function handle(string $request) : ? string; } // handlers 1 class Monkey extends MainHandler { public function handle(string $request) : ? string { if($request === 'bananna'){ return "Monkey say I'll eat your request if that is realy a " . $request . " . <br>"; } else { return parent::passToNext($request); } } } // handlers 2 class Ship extends MainHandler { public function handle(string $request) : ? string{ if($request === 'grass'){ return "Ship say I'll eat your request if that is realy a " . $request . " . <br>"; } else { return parent::passToNext($request); } } } // handlers 3 class Fish extends MainHandler { public function handle(string $request) : ? string{ if($request === 'water'){ return "Fish say I'll eat your request if that is realy a " . $request . " . <br>"; } else { return parent::passToNext($request); } } } // handlers 4 class Dog extends MainHandler { public function handle(string $request) : ? string{ if($request === 'meat'){ return "Dog say I'll eat your request if that is realy a " . $request . " . <br>"; } else { return parent::passToNext($request); } } } // create instance of objects $dog = new Dog; $ship = new Ship; $fish = new Fish; $monkey = new Monkey; // create the chain of objects and so on handlers $monkey->setNext($dog)->setNext($ship)->setNext($fish); // client simple Code function clientCode(Handler $handler) : void { $foods = ['bananna','water','tea','grass']; foreach($foods as $food) { $result = $handler->handle($food); if ($result){ echo $result; } else { echo $food . " remained untoach. <br>"; } } } clientCode($monkey); ?> <file_sep><?php class Person { public $name; public $ability; public $nextPerson = null; public function __construct($name,$ability){ $this->name = $name; $this->ability = $ability; } public function setNext($personObj) { $this->nextPerson = $personObj; return $personObj; } public function checkIfCanThenDoItOrPassToNextPerson($request){ if($this->ability == $request){ echo $this->name . " say I'll do your ( " . $request . " ) works and no need to anyone else."; } else { if($this->nextPerson) { $this->nextPerson->checkIfCanThenDoItOrPassToNextPerson($request); } else { echo "The " . $this->ability . " remained untouch ."; } } } } $person1 = new Person('Amin','Programming'); $person2 = new Person('Bahram','Design'); $person3 = new Person('Raamtin','DataBase'); $person4 = new Person('Fariborz','DevOps'); $person1 -> setNext($person2) -> setNext($person3) -> setNext($person4); $person1->checkIfCanThenDoItOrPassToNextPerson('DataBase'); ?><file_sep><?php interface a { public function echoThing($thing); } interface b { public function showThing($thing); } interface c extends a , b { public function viewThing($thing); } class d implements c { public function echoThing($t){ echo $t." "; } public function viewThing($t){ echo $t." "; } } $obj = new d; $obj -> echoThing('derakht'); $obj -> viewThing('shaakhe'); ?><file_sep><?php // define some CONST for use in program define('APP_TITLE', 'mvc project'); define('BASE_URL', '/My/topLearn_phpMVC/project00002'); define('BASE_DIR', realpath((__DIR__)."/../")); $temporary = str_ireplace(BASE_URL,'',explode('?',$_SERVER['REQUEST_URI'])[0]); $temporary === "/" ? $temporary = "" : $temporary = substr($temporary,1); define('CURREN_ROUTE', $temporary); global $routes; $routes = [ 'get' => [], 'post' => [], 'put' => [], 'delete' => [], ]; ?>
79f44e4ec82e8a1bbfb48eda2e60302bbc12fb49
[ "PHP" ]
13
PHP
aminashoftehyazdi/topLearn_phpMVC
ee46f49a0e3bdc6707ed38b63ed7c5f7d22f5bea
1776ca2671addd2ceaa5d24ea32d6ef0d89a609b
refs/heads/main
<file_sep>using AutoFixture; using AutoFixture.Xunit2; using SocialPodcasts.BLL.Services; using SocialPodcasts.Domain; using System.Linq; using Xunit; namespace SocialPodcasts.BLL.Tests.Services { public class PodcastServiceShould { private PodcastService _sut; public PodcastServiceShould() { var fixture = new Fixture(); var data = fixture.CreateMany<Podcast>(10).ToList(); _sut = new PodcastService(data); } [Fact] public void HaveTenPodcasts() { // arrange // sut already done in constructor // act var podcasts = _sut.GetPodcasts(); var count = podcasts.Count(); // assert Assert.NotEmpty(podcasts); Assert.Equal(10, count); } [Fact] public void AddSpecificPodcast() { // arrange // sut already done in constructor var id = 1; var name = "<NAME>"; // magic strings are bad var ownerId = 3; // act var podcasts = _sut.AddPodcast(id, name, ownerId); // assert Assert.Contains(podcasts, x => x.Id == id && x.Name == name && x.Owner.Id == ownerId); } [Theory] [InlineData(1, "name 1", 1)] [InlineData(2, "name 2", 1)] [InlineData(3, "name 3", 1)] public void AddPodcasts(int id, string name, int ownerId) { // arrange // sut already done in constructor // data from inline data // act var podcasts = _sut.AddPodcast(id, name, ownerId); // assert Assert.Contains(podcasts, x => x.Id == id && x.Name == name && x.Owner.Id == ownerId); } [Fact] public void AddPodcast() { // arrange // sut already done in constructor var fixture = new Fixture(); var id = fixture.Create<int>(); var name = fixture.Create<string>(); var ownerId = fixture.Create<int>(); // act var podcasts = _sut.AddPodcast(id, name, ownerId); // assert Assert.Contains(podcasts, x => x.Id == id && x.Name == name && x.Owner.Id == ownerId); } [Theory] [AutoData] public void AddFixturePodcast(int id, string name, int ownerId) { // arrange // sut already done in constructor // data from auto data // act var podcasts = _sut.AddPodcast(id, name, ownerId); // assert Assert.Contains(podcasts, x => x.Id == id && x.Name == name && x.Owner.Id == ownerId); } } } <file_sep>using SocialPodcasts.Domain; namespace SocialPodcasts.BLL.Services { public class UserService { public User AddUser(string firstName, string lastName) { var user = new User { FirstName = firstName, LastName = lastName, FullName = string.Join(" ", firstName, lastName) }; // create user in the database return user; } public User SetUser(int id, string firstName, string lastName) { // get the user from the database by id var user = new User { Id = id, FirstName = firstName, LastName = lastName, FullName = string.Join(" ", firstName, lastName) }; return user; } } } <file_sep># xunit-samples xUnit Samples Project <file_sep>using AutoFixture; using SocialPodcasts.BLL.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace SocialPodcasts.BLL.Tests.Services { public class UserServiceShould { private UserService _sut; // system under test, convention name public UserServiceShould() { _sut = new UserService(); } [Fact] public void AddUserWithFullName() { // arrange var firstName = "Jimmy"; // magic strings, don't do this var lastName = "Jones"; // magic strings, don't do this // act var user = _sut.AddUser(firstName, lastName); // assert Assert.Equal("<NAME>", user.FullName); } [Fact] public void HaveFullNameWithSpace() { // arrange var firstName = "Jack"; // magic strings, don't do this var lastName = "Smith"; // magic strings, don't do this // act var user = _sut.AddUser(firstName, lastName); // assert Assert.Matches(@"\w\s\w", user.FullName); } // Data driven example [Theory] [InlineData("Jimmy", "Jones")] // hard coding the values is not optimal [InlineData("Jack", "Smith")] [InlineData("Jenny","Tonies")] public void ContainFirstName(string firstName, string lastName) { // act var user = _sut.AddUser(firstName, lastName); // assert Assert.Contains(firstName, user.FullName); } // auto fixture data driven examples [Fact] public void StartWithFirstName() { // arrange var fixture = new Fixture(); var firstName = fixture.Create<string>(); var lastname = fixture.Create<string>(); // act var user = _sut.AddUser(firstName, lastname); // assert Assert.StartsWith(firstName, user.FullName); } } } <file_sep>using System.Collections.Generic; namespace SocialPodcasts.Domain { public class User { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get; set; } // public IEnumerable<Podcast> SubscribedPodcasts { get; set; } // public IEnumerable<Podcast> OwnPodcasts { get; set; } } } <file_sep>using SocialPodcasts.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialPodcasts.BLL.Services { public class PodcastService { private List<Podcast> _data; public PodcastService(List<Podcast> data) { _data = data; } public IEnumerable<Podcast> GetPodcasts() { return _data; } public IEnumerable<Podcast> AddPodcast(int id, string name, int ownerId) { if (_data.Any(x => x.Id == id)) { throw new ArgumentException("A podcast with this id already exists!", nameof(id)); } _data.Add(new Podcast { Id = id, Name = name, Owner = new User { Id = ownerId } }); return _data; } public IEnumerable<Podcast> RemovePodcast(int id) { var item = _data.FirstOrDefault(x => x.Id == id); if (item == null) { throw new ArgumentException("A podcast with this id does not exist!", nameof(id)); } _data.Remove(item); return _data; } } }
99cdaf6c6c3c5cd385da54cf538b4ce2a76d3ac6
[ "Markdown", "C#" ]
6
C#
projectsbydan/xunit-samples
a91f9c51342692e75147245858cde8f0f2355ef4
37c029b7d3f808180d595880f68b725302636e1b
refs/heads/main
<file_sep># Kullanici-Kayit-Sistemi Girilen kullanıcı adı ve yaş bilgisini kullanıcı bilgilerini içeren listede tutan bir react uygulaması ![Ekran görüntüsü 2021-08-23 102728](https://user-images.githubusercontent.com/61868498/130407985-0c3ffedd-af53-4c6b-88e9-bbc4a5ea7f1d.png) <file_sep>import React from "react"; import { Card } from "../UI/Card"; import classes from "./UserList.module.css"; export const UsersList = (props) => { return ( <Card className={classes.users}> <ul> {props.users.map((user) => ( <li> {user.username} ({user.age}) </li> ))} </ul> </Card> ); };
ea53617b499c5349b5037a552d2ed514cb45b2cb
[ "Markdown", "JavaScript" ]
2
Markdown
enesaliovur/Kullanici-Kayit-Sistemi
14e8a0981223d091ad458da6d9c43afef0ba8a92
15cc0fd7cae2a11535cbaf68a18cf301eee63dbb
refs/heads/master
<repo_name>stalmcdonald/MobileNotaryQuote<file_sep>/src/com/cmcdonald/mynotary/MainActivity.java /* * <NAME> * Java II 1303 * Week 1 */ package com.cmcdonald.mynotary; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ Button documents, costPerPage, calc; TextView myQuote; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); documents = (Button) findViewById(R.id.button1); costPerPage = (Button) findViewById(R.id.button2); calc = (Button) findViewById(R.id.button3); myQuote = (TextView) findViewById(R.id.textView1); //setup onclick listeners for buttons documents.setOnClickListener(this); costPerPage.setOnClickListener(this); calc.setOnClickListener(this); } //EXPLICIT INTENT //BUTTONS @Override public void onClick(View v) { // if button 1-2 are pressed go to new activity Intent i = new Intent(this, NumQuote.class); switch (v.getId()){ //buttons case R.id.button1: //DOCS i.putExtra("numbers", "documents"); startActivityForResult(i, 1); break; case R.id.button2: //costPerPage i.putExtra("numbers", "costPerPage"); startActivityForResult(i, 1); break; case R.id.button3: //calculate //converting integer to string int a = Integer.valueOf(documents.getText().toString()); int b = Integer.valueOf(costPerPage.getText().toString()); //displays the sum in a string replacing "Quote" myQuote.setText(" Client Quote: $" + a*b); break; default: break; } } //GET NUMBERS BACK FROM ACTIVITY2 TO BE CALCULATED //capture info being sent back @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(data.getExtras().containsKey("documentsInfo")){ documents.setText(data.getStringExtra("documentsInfo")); } if(data.getExtras().containsKey("costPerPageInfo")){ costPerPage.setText(data.getStringExtra("costPerPageInfo")); } } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.activity_main, menu); // return true; // } } <file_sep>/src/com/cmcdonald/mynotary/NumQuote.java /* * <NAME> * Java II 1303 * Week 1 */ package com.cmcdonald.mynotary; //import java.net.URL; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class NumQuote extends Activity implements OnClickListener { EditText number; Button shareInfo; Button browse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.numquote); number = (EditText)findViewById(R.id.editText1); shareInfo = (Button)findViewById(R.id.button1); // set listener for browse button browse = (Button) findViewById(R.id.browseBttn); shareInfo.setOnClickListener(this); browse.setOnClickListener(new OnClickListener() { //IMPLICIT INTENT WEB BROWSER @Override public void onClick(View interwebs) { // Sends user to Notary Service website when button is clicked //Website gives more information if suggested prices are not what user wants Uri uriUrl = Uri.parse("http://www.123notary.com/mobilenotary.htm"); Intent browse_intent = new Intent(Intent.ACTION_VIEW, uriUrl); startActivity(browse_intent); } }); } //ACTIVITY2 TAKES IN A NUMBER TO DISPLAY IT ON ACTIVITY1 @Override public void onClick(View v) { // get info from edit text and send back String s = number.getText().toString(); //get info from intent that opens numQuote class Intent i = getIntent (); //looking for i.putextras String msg = i.getStringExtra("numbers"); if(msg.contentEquals("documents")){ i.putExtra("documentsInfo", s); setResult(RESULT_OK, i); finish(); } //takes the results and closes the page and appends to MainActivity in its button if(msg.contentEquals("costPerPage")){ i.putExtra("costPerPageInfo", s); setResult(RESULT_OK, i); finish(); } } }
da4d75d82fe9b04eb24b565c081bb1e9a7f9e998
[ "Java" ]
2
Java
stalmcdonald/MobileNotaryQuote
f3b03c235e00f1cc5353b2429169276ec5390ba1
6b96d976bb12f43f4fff1a3b53f0db9eaad2797d
refs/heads/main
<file_sep>package Test; public class Demo { public static void main(String[] args) { System.out.println("I got my first bike in the hood from crackhead billy for $25"); } } //C:\Users\washi\IdeaProjects\testhomework\src\main\java\Test\Demo.java
5c2259db56e37a298fe0eaa29cc94649016269ed
[ "Java" ]
1
Java
MekhiW34/Demo
b95453bdeeb1ad586c844af4b6776a3dcee444c7
066b696bfb07f47fcd2b1d4049372b4424efa8a4
refs/heads/develop
<file_sep>import { Router } from 'express'; import ServiceController from '../controllers/service'; const router = Router(); const { createService, getAllServices, updateService, deleteService } = ServiceController; router.post('/', createService); router.get('/', getAllServices); router.put('/:id', updateService); router.delete('/:id', deleteService); export default router; <file_sep>[![Build Status](https://travis-ci.com/Diama1/portfolio-backend.svg?token=<KEY>&branch=develop)](https://travis-ci.com/Diama1/portfolio-backend) [![Coverage Status](https://coveralls.io/repos/github/Diama1/portfolio-backend/badge.svg?branch=develop)](https://coveralls.io/github/Diama1/portfolio-backend?branch=develop) # My Portfolio<file_sep>module.exports = (sequelize, DataTypes) => { const Service = sequelize.define('Service', { title: { type: DataTypes.STRING, allowNull: false, unique: true }, description: { type: DataTypes.STRING, allowNull: false }, image: { type: DataTypes.TEXT, allowNull: false }, }, {}); Service.associate = () => { // associations can be defined here }; return Service; }; <file_sep>import db from '../../sequelize/models'; const { Service } = db; /** * @author <NAME> * @class Services * @description this class performs the whole service */ class Services { /** * * @param {Object} req - Request object * @param {Object} res - Response object * @returns {Object} - Response object */ static async createService(req, res) { const { title, description, image } = req.body; const data = { title, description, image }; const response = await Service.findAll({ where: { title } }); if (!response[0]) { const newService = await Service.create({ title: data.title, description: data.description, image: data.image }); return res.status(201).json({ data: newService, message: 'Service created successfully' }); } } /** * * @param {Object} req - Request object * @param {Object} res - Response object * @returns {Object} - Response object */ static async getAllServices(req, res) { const allServices = await Service.findAll(); if (!allServices[0]) return res.status(200).send({ message: 'Whoops! No Service found!' }); res.status(200).send({ services: allServices }); } /** * * @param {Object} req - Request object * @param {Object} res - Response object * @returns {Object} - Response object */ static async updateService(req, res) { const { id } = req.params; const { title, description, image } = req.body; const data = { title, description, image }; const response = await Service.findAll({ where: { id } }); if (response) { await Service.update( { title: data.title, description: data.description, image: data.image }, { where: { id }, logging: false } ); res.status(200).json({ NewService: data, message: 'updated', }); } } /** * * @param {Object} req - Request object * @param {Object} res - Response object * @returns {Object} - Response object */ static async deleteService(req, res) { const { id } = req.params; await Service.destroy({ where: { id } }); res.status(200).json({ message: 'the service has been deleted successfully' }); } } export default Services; <file_sep>import chai from 'chai'; import chaiHttp from 'chai-http'; import { async } from 'regenerator-runtime'; import server from '../src/index'; import db from '../src/sequelize/models'; const { Service } = db; // eslint-disable-next-line no-unused-vars const should = chai.should(); const serviceMock = { title: 'Hello', description: 'We create hello', image: 'hadhadjahda', }; const updateMock = { title: 'Helloo', description: 'We create hellooo', image: 'hadhadjahdaa', }; let newService; chai.use(chaiHttp); const { expect } = chai; describe('Service', () => { before(async () => { const service = { title: 'UX & UI', description: 'we develop better UX', image: 'dfdddfdwwdw' }; newService = await Service.create(service); }); it('should create the service', (done) => { chai.request(server) .post('/api/service') .send(serviceMock) .end((err, res) => { expect(res).to.have.status(201); expect(res.body.message).to.be.a('string'); done(); }); }); it('should get all services in the db', (done) => { chai.request(server) .get('/api/service') .end((err, res) => { expect(res.body).to.be.an('object'); expect(res).to.have.status(200); expect(res.body.services).to.be.an('array'); done(); }); }); it('should update a specific service', (done) => { chai.request(server) .put(`/api/service/${newService.id}`) .send(updateMock) .end((err, res) => { expect(res.body).to.be.an('object'); expect(res).to.have.status(200); done(); }); }); it('should delete a specific service', (done) => { chai.request(server) .delete(`/api/service/${newService.id}`) .end((err, res) => { expect(res.body.message).to.equal('the service has been deleted successfully'); expect(res).to.have.status(200); done(); }); }); });
2c56a4f9ce0e6a7b0d2dfbbb146530b17e9dbab6
[ "JavaScript", "Markdown" ]
5
JavaScript
Diama1/portfolio-backend
dcb10c766b0ae78974e4ca1c50ac06c2cc8a307b
62777ca1d36168f5329402e6f9b1aa426f402615
refs/heads/master
<repo_name>HarukaKajita/jpro_report05<file_sep>/us162039/jpro_report05.cpp #include <iostream> #include <cstdlib> #include <fstream> using namespace std; class BinTree { private: class BinNode { public: string data; int appearanceNum; BinNode* left; BinNode* right; BinNode(string a = 0, BinNode * b = NULL, BinNode * c = NULL) { data = a; left = b; right = c; appearanceNum = 1; } void printNode() { cout << data << "[" << appearanceNum << "] "; #ifdef _DEBUG cout << "this = " << this << endl; cout << "left = " << left << endl; cout << "right = " << right << endl; #endif // DEBUG } }; BinNode* root; void traverse(BinNode* rp); BinNode* addNode(BinNode* rp, BinNode* node); BinNode* delNode(BinNode* rp, int appearanceNum); public: BinTree() { root = NULL; } void printTree() { traverse(root); } void insert(string str) { BinNode* np = new BinNode(str); root = addNode(root, np); } void remove(int apppearanceNum) { root = delNode(root, apppearanceNum); } }; void BinTree::traverse(BinNode* rp) { if (rp == NULL) return; traverse(rp->left); rp->printNode(); traverse(rp->right); } BinTree::BinNode* BinTree::addNode(BinNode* rp, BinNode* node) { if (node == NULL) return rp; if (rp == NULL) return node; else { if (node->data == rp->data) { rp->appearanceNum++; } else if (node->data < rp->data) { rp->left = addNode(rp->left, node); } else { rp->right = addNode(rp->right, node); } return rp; } } BinTree::BinNode* BinTree::delNode(BinNode* rp, int appearanceNum) { if (rp == NULL) return NULL; rp->left = delNode(rp->left, appearanceNum); #ifdef _DEBUG cout << rp->data << " : " << rp->appearanceNum << endl; #endif // _DEBUG if (appearanceNum == rp->appearanceNum) { #ifdef _DEBUG cout << "削除します" << endl; cout << "right = " << right << endl; cout << "left = " << left << endl; #endif // _DEBUG BinNode* left = rp->left; BinNode* right = rp->right; delete rp; rp = addNode(right, left);//rp下のツリーの再構成 //再構成後のツリーに対して削除処理 rp = delNode(rp, appearanceNum); return rp; } else rp->right = delNode(rp->right, appearanceNum); return rp; } int main() { BinTree bt; // 空の二進木を作成 string str; ifstream fin("words.txt"); if (!fin) { cerr << "ファイルを開けませんでした。" << endl; exit(EXIT_FAILURE); } while (fin >> str) { bt.insert(str); //単語をツリーに入力 } bt.printTree(); // bt の木全体を表示する cout << endl; int appearanceNum = 0; while (cout << "何回出現した単語を削除しますか --> " && cin >> appearanceNum) { bt.remove(appearanceNum); bt.printTree(); cout << endl; } return 0; } <file_sep>/ex12/ex12/prac12.cpp #include <iostream> using namespace std; //#define DEBUG class BinTree{ private: class BinNode{ public: int data; BinNode* left; BinNode* right; BinNode(int a = 0, BinNode* b = NULL, BinNode* c = NULL){ data = a; left = b; right = c; } void printNode(){cout << data << " ";} }; BinNode* root; void traverse(BinNode* rp); BinNode* addNode(BinNode* rp, BinNode* node); BinNode* delNode(BinNode* rp, int x); public: BinTree(){root = NULL;} void printTree(){traverse(root);} void insert(int x){ BinNode* np = new BinNode(x); root = addNode(root, np); } void remove(int x){ root = delNode(root, x); } }; void BinTree::traverse(BinNode* rp){ if(rp == NULL) return; traverse(rp->left); rp->printNode(); traverse(rp->right); } BinTree::BinNode* BinTree::addNode(BinNode* rp, BinNode* node){ if(node == NULL) return rp; if(rp == NULL) return node; else{ if(node->data <= rp->data){ rp->left = addNode(rp->left, node); } else { rp->right = addNode(rp->right, node); } return rp; } } BinTree::BinNode* BinTree::delNode(BinNode* rp, int x){ if(rp == NULL) return NULL; #ifdef DEBUG cout << "del : " << x << endl; cout << "now : " << rp->data << endl; if(rp->left)cout << "left : " << rp->left->data << endl; if(rp->right)cout << "right : " << rp->right->data << endl; #endif if(x == rp->data){ BinNode* left = rp->left; BinNode* right = rp->right; delete rp; return addNode(right, left); } else{ if(x < rp->data){ rp->left = delNode(rp->left, x); } else { rp->right = delNode(rp->right, x); } return rp; } } int main(){ BinTree bt; // 空の二進木を作成 int x; cout << "正整数をいくつか入力せよ --> "; while(cin >> x && x >0){ // 負数が入力されるまで正整数を入力 bt.insert(x); // x をデータとして持つノードを木に追加 } bt.printTree(); // bt の木全体を表示する cout << endl; while(cout << "削除したい正整数 --> " && cin >> x && x > 0){ bt.remove(x); bt.printTree(); cout << endl; } return 0; }
a965e3d448f8eb5f6909fd2b7ef9d073c1dcc3ac
[ "C++" ]
2
C++
HarukaKajita/jpro_report05
a2f1fa6f9ed30f20cf353cd8c79ffa687196e22c
b139c9bb341a59baa1a1bb9803d7112f3bbe3ab1
refs/heads/master
<repo_name>Alezco05/Prueba<file_sep>/js/app.js const contacto = document.getElementById('contacto'); contacto.addEventListener('submit', validarPersona); function validarPersona(event){ const nombre = document.querySelector('#nombre').value; const email = document.querySelector('#email').value; const mensaje = document.querySelector('#mensaje').value; const error = document.querySelector('#error'); const div = document.createElement('div'); if (nombre != "") { let caracteres = nombre.length; let expresion = /^[a-zA-Z]*$/; if (caracteres > 12) { div.innerHTML += "<br>Escriba menos de 12 caracteres</br>"; error.appendChild(div); return false; } if (!expresion.test(nombre)) { div.innerHTML += "<br>Escriba su nombre con solo letras su nombre</br>"; error.appendChild(div); return false; } } if (email !== "") { let expresion = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;; if (!expresion.test(email)) { div.innerHTML += "<br>Escriba correctamente el email</br>"; error.appendChild(div); return false; } } if (mensaje === "") { div.innerHTML += "<br>Escriba su mensaje</br>"; error.appendChild(div); return false; } return true; } <file_sep>/js/validar.js var d=document; d.querySelector("#submit").onclick=validarDatos; d.getElementById('simple-msg').style.color='red'; reglaNom=/^[a-zñ | A-ZÑ]+[a-zñ | A-ZÑ\s]+[a-zñ | A-ZÑ]$/ reglaApe=/^[a-zñ | A-ZÑ]+[a-zñ | A-ZÑ\s]+[a-zñ | A-ZÑ]$/ reglaEmail=/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; function validarDatos(){ el=d.getElementById('nombre'); if (!validarRequeridos(el))return; if (!validarERegular(el,reglaNom))return; el=d.getElementById('comentario'); if (!validarRequeridos(el))return; if (!validarERegular(el,reglaApe))return; el=d.getElementById('correo'); if (!validarRequeridos(el))return; if (!validarERegular(el,reglaEmail))return; /* Respuesta positiva */ d.getElementById('simple-msg').style.color='green'; d.getElementById('simple-msg').style.fontWeight='bold'; d.getElementById('simple-msg').innerHTML="Todo ready " } function validarRequeridos(el) { sw=true; if (el.checkValidity()==false && el.required){ d.getElementById('simple-msg').innerHTML="<p> Debe Ingresar "+el.id+"<p>" sw=false; }else{ d.getElementById('simple-msg').innerHTML="" } return sw; } function validarERegular(el,regla){ sw=true; valor=el.value; if (!regla.test(valor)) { d.getElementById("simple-msg").innerHTML="<p> Debe ingresar un "+el.id+" Valido(s) </p>" sw=false; } return sw; } <file_sep>/contacto.php <?php include_once 'controller/controller.php'; include_once 'views/head.php'; ?> <style> body{ background-color: black; } </style> <body> <!-- header section --> <section class="banner" role="banner" id="home"> <header id="header"> <div class="header-content clearfix"> <a class="logo" href="Index.php">Master <span>Chefs</span> </a> </div> </header> <section id="contact" class="section"> <div class="container"> <div class="section-header"> <h2 class="wow fadeInDown animated">Contacto</h2> <p class="wow fadeInDown animated">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa <br> semper aliquam quis mattis quam.</p> </div> <div class="row"> <div class="col-md-8 col-md-offset-2 conForm"> <form method="post" id="contacto"> <input type="text" placeholder="Máximo 12 Caracteres" maxlength="12" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" name="nombre" id="nombre" placeholder="Escriba su nombre" required> <input type="email" placeholder="Escriba su correo" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" name="email" id="email" placeholder="Escriba su email" required> <textarea name="mensaje" id="mensaje" cols="30" rows="10" placeholder="Mensaje" class="col-xs-12 col-sm-12 col-md-12 col-lg-12"></textarea> <input type="submit" value="Enviar" class="submitBnt"> <div id="error" style= color:white></div> </form> </div> </div> </div> </section> </body> </html> <script src = "js/app.js"></script> <?php $registro = new Correo(); $registro -> registroEmail(); ?><file_sep>/controller/controller.php <?php require_once 'conexion.php'; require_once 'model.php'; class Correo { public function registroEmail(){ if(isset($_POST["nombre"])){ if(preg_match(('/^[a-zA-Z0-9]*$/'), $_POST["nombre"]) && preg_match(('/^[a-zA-Z0-9]*$/'), $_POST["mensaje"]) && preg_match(('/^[^\s@]+@[^\s@]+\.[^\s@]+$/'), $_POST["email"]) ) { $datosController = array( "nombre"=>$_POST["nombre"], "mensaje"=>$_POST["mensaje"], "email"=>$_POST["email"]); $respuesta = Datos::registroMensajes($datosController, "contactos"); if($respuesta == "success"){ //$asunto = "Email de prueba"; //mail($_POST["email"],$asunto,$_POST["mensaje"],$_POST["nombre"]); header("location:index.php"); } else{ header("location:error.html"); } } } } } ?> <file_sep>/index.php <?php include_once "views/head.php"; include_once "views/nav.php"; ?> <div id="first-slider"> <div id="carousel-example-generic" class="carousel slide carousel-fade"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> <li data-target="#carousel-example-generic" data-slide-to="3"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <!-- Item 1 --> <div class="item active slide1"> <div class="row"><div class="container"> <div class="col-md-9 text-left"> <h3 data-animation="animated bounceInDown">LLENAR</h3> <h4 data-animation="animated bounceInUp">Create beautiful slideshows </h4> </div> </div></div> </div> <!-- Item 2 --> <div class="item slide2"> <div class="row"><div class="container"> <div class="col-md-7 text-left"> <h3 data-animation="animated bounceInDown">LLenar</h3> <h4 data-animation="animated bounceInUp">Create beautiful slideshows </h4> </div> </div></div> </div> <!-- Item 3 --> <div class="item slide3"> <div class="row"><div class="container"> <div class="col-md-7 text-left"> <h3 data-animation="animated bounceInDown">LLenar</h3> <h4 data-animation="animated bounceInUp">Bootstrap Image Carousel Slider</h4> </div> </div></div> </div> </div> <!-- Fin--> <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <i class="fa fa-angle-left"></i><span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <i class="fa fa-angle-right"></i><span class="sr-only">Next</span> </a> </div> </div> </section> <section id="intro" class="section intro"> <div class="container"> <div class="col-md-10 col-md-offset-1 text-center"> <h3>Bienvenido</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> </div> </section> <!-- Inicio --> <!-- section --> <section id="Bride_Groom"> <div class="container"> <div class="row"> <div class="section-header"> <h2 class="wow fadeInDown animated">Show</h2> <p class="wow fadeInDown animated">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa <br> semper aliquam quis mattis quam.</p> </div> <div id="content24" data-section="content-24" class="data-section"> <div class="col-md-4"> <img src="images/img1.jpg" alt="bride" class="img-middle"/> <div class="align-center"> <h4>Master Chefs L,A</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.</p> <a href="index.php" class="morebtn">More</a> </div> </div> <div class="col-md-4"> <img src="images/img1.jpg" alt="bride" class="img-middle"/> <div class="align-center"> <h4>Master Chefs</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.</p> <a href="index.php" class="morebtn">More</a> </div> </div> <div class="col-md-4"> <img src="images/img1.jpg" alt="bride" class="img-middle"/> <div class="align-center"> <h4>Master Chefs Kids</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.</p> <a href="index.php" class="morebtn">More</a> </div> </div> </div> </div> </div> </section> <section id="services" class="services service-section"> <div class="container"> <div class="section-header"> <h2 class="wow fadeInDown animated">Servicios</h2> <p class="wow fadeInDown animated">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa <br> semper aliquam quis mattis quam.</p> </div> <div class="row"> <div class="col-md-4 col-sm-6 services text-center"> <span class="icon icon-heart"></span> <div class="services-content"> <h5>Pasteleria</h5> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.</p> </div> </div> <div class="col-md-4 col-sm-6 services text-center"> <span class="icon icon-gift"></span> <div class="services-content"> <h5>Concursos</h5> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.</p> </div> </div> <div class="col-md-4 col-sm-6 services text-center"> <span class="icon icon-phone"></span> <div class="services-content"> <h5>Fecha de inicio</h5> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.</p> </div> </div> </div> </div> </section> <section id="content-3-10" class="content-block data-section nopad content-3-10"> <div class="image-container col-sm-6 col-xs-12 pull-left"> <div class="background-image-holder"> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col-sm-6 col-sm-offset-6 col-xs-12 content"> <div> <h3>Quienes somos</h3> </div> <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit</p> <p>Duis eu libero scelerisque ligula sagittis faucibus eget quis lacus.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit</p> </div> <a href="#gallery" class="btn btn-outline btn-outline outline-dark">Galeria</a> </div> </div><!-- /.Fin--> </div><!-- /.Fin --> </section> <!-- video --> <section class="video-section"> <div class="container"> <div class="row"> <div id="content24" data-section="content-24" class="data-section"> <div class="col-md-6"> <h3>Videos</h3> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p> <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.</p> <p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.</p> </div> <div class="col-md-6"> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="https://player.vimeo.com/video/220040442?title=0&byline=0&portrait=0" allowfullscreen=""></iframe> </div> </div> </div> </div><!-- Fin --> </div> </section> <!-- Fin --> <!-- Galeria --> <section id="gallery" class="gallery section"> <div class="container-fluid"> <div class="section-header"> <h2 class="wow fadeInDown animated">Galeria</h2> <p class="wow fadeInDown animated">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa <br> semper aliquam quis mattis quam.</p> </div> <div class="row no-gutter"> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpg" class="work-box"> <img src="images/portfolio/01.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpeg" class="work-box"> <img src="images/portfolio/07.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- Cubrir --> </a> </div> <div class="col-lg-3 col-md-6 col-sm-6 work"> <a href="images/portfolio/01.jpeg" class="work-box"> <img src="images/portfolio/08.jpg" alt=""> <div class="overlay"> <div class="overlay-caption"> <p><span class="icon icon-magnifying-glass"></span></p> </div> </div> <!-- overlay --> </a> </div> </div> </div> </section> <!-- gallery section --> <!-- Informacion de chefs --> <section id="teams" class="section teams"> <div class="container"> <div class="section-header"> <h2 class="wow fadeInDown animated">Chefs</h2> <p class="wow fadeInDown animated">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa <br> semper aliquam quis mattis quam.</p> </div> <div class="row"> <div class="col-md-3 col-sm-6"> <div class="person"><img src="images/foto1.jpg" alt="" class="img-responsive"> <div class="person-content"> <h4>Chefs 1</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit eget risus vitae massa.</p> </div> </div> </div> <div class="col-md-3 col-sm-6"> <div class="person"> <img src="images/foto2.png" alt="" class="img-responsive"> <div class="person-content"> <h4>Chefs 2</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit eget risus vitae massa.</p> </div> </div> </div> <div class="col-md-3 col-sm-6"> <div class="person"> <img src="images/foto3.jpg" alt="" class="img-responsive"> <div class="person-content"> <h4>Chefs 3</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit eget risus vitae massa.</p> </div> </div> </div> <div class="col-md-3 col-sm-6"> <div class="person"> <img src="images/foto4.jpg" alt="" class="img-responsive"> <div class="person-content"> <h4>Chefs 4</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit eget risus vitae massa.</p> </div> </div> </div> </div> </div> </section> <!-- Fin --> <!-- Datos --> <section id="testimonials" class="section testimonials no-padding"> <div class="container-fluid"> <div class="row no-gutter"> <div class="flexslider"> <ul class="slides"> <li> <div class="col-md-12"> <blockquote> <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget risus vitae massa semper aliquam quis mattis consectetur adipiscing elit.." </p> <p>Chefs 1</p> </blockquote> </div> </li> <li> <div class="col-md-12"> <blockquote> <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint amet laudantium porro. Quo corporis consectetur consequuntur nesciunt voluptates ut, voluptas nemo repellat eligendi necessitatibus, veniam deserunt. Unde quam, necessitatibus consequuntur!" </p> <p>Chefs 2</p> </blockquote> </div> </li> <li> <div class="col-md-12"> <blockquote> <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem sed sunt, sit obcaecati vero autem saepe magni sapiente debitis molestias aperiam beatae, quidem, provident accusantium sint libero modi eius nihil?" </p> <p>Chefs 3</p> </blockquote> </div> </li> <li> <div class="col-md-12"> <blockquote> <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus, nobis minus tempora. Dolorum impedit quasi voluptas sequi sunt velit, architecto nemo. Quaerat eos excepturi perspiciatis consectetur atque facere consequuntur natus!" </p> <p>Chefs 4</p> </blockquote> </div> </li> </ul> </div> </div> </div> </section> <!-- Fin --> <?php include "views/footer.php"; include "javascript.php"; ?>
c4fdecdb881938e398d60486970794b29d78504e
[ "JavaScript", "PHP" ]
5
JavaScript
Alezco05/Prueba
59efe045273831cf7946d226b28a65bbf0b6372a
7cbcdaade526bebff45c9aff8b011befe3c1618b
refs/heads/master
<file_sep>'use strict' import React from 'react' import { StyleSheet } from 'react-native' const hairlineWidth = StyleSheet.hairlineWidth export const BG_COLOR = '#d2d5dc' export default StyleSheet.create({ wrapper: { flexDirection: 'row', backgroundColor: '#f4f4f4', }, main: { flex: 1, alignSelf: 'flex-end', }, row: { flexDirection: 'row', }, }) export const keyStyle = { wrapper: { flex: 1, height: 48, backgroundColor: '#fff', }, bd: { flex: 1, alignItems: 'center', justifyContent: 'center', borderRightWidth: hairlineWidth, borderTopWidth: hairlineWidth, borderColor: '#a5a5a5', }, border: { borderColor: '#FFF', }, mainText: { fontSize: 20, color: '#000', }, otherText: { fontSize: 10, color: '#333', }, bg_d2d5dc: { backgroundColor: BG_COLOR, }, bgLessL: { backgroundColor: '#fff', }, dot: { height: 30, fontSize: 30, lineHeight: 25, }, }
d31e511047691547014b0398cd1728d3b3554d08
[ "JavaScript" ]
1
JavaScript
Astrocoders/react-native-keyboard
3a6f6ff24adea7e922a43d4f7ef5be534e738dd8
0385580e330527ab7d80f04012a25e82297dcb21
refs/heads/master
<repo_name>t2ym/xliff-conv<file_sep>/README.md [![Build Status](https://travis-ci.org/t2ym/xliff-conv.svg?branch=master)](https://travis-ci.org/t2ym/xliff-conv) [![Coverage Status](https://coveralls.io/repos/github/t2ym/xliff-conv/badge.svg?branch=master)](https://coveralls.io/github/t2ym/xliff-conv?branch=master) [![npm](https://img.shields.io/npm/v/xliff-conv.svg)](https://www.npmjs.com/package/xliff-conv) [![Bower](https://img.shields.io/bower/v/xliff-conv.svg)](https://customelements.io/t2ym/xliff-conv/) # xliff-conv XLIFF to/from JSON converter for Polymer [i18n-behavior](https://github.com/t2ym/i18n-behavior) ## Features - Update bundle.*.json values with those from XLIFF - Generate XLIFF from bundles - Map todo operations in bundles onto XLIFF states - Update todo operations in bundles with XLIFF states - Concise and flexible expressions to customize conversion - Handy migration from [xliff2bundlejson](https://github.com/t2ym/xliff2bundlejson) - [UMD](https://github.com/ruyadorno/generator-umd) support ## Install ### For Node.js ```javascript npm install --save-dev xliff-conv ``` [Quick Tour](https://github.com/t2ym/polymer-starter-kit-i18n#quick-tour) with polymer-starter-kit-i18n ### For Browsers ```javascript bower install --save xliff-conv ``` ## Import ### On Node.js ```javascript var XliffConv = require('xliff-conv'); ``` ### On Browsers ```html <script src="path/to/bower_components/xliff-conv/xliff-conv.js"></script> ``` ## Examples ### Import XLIFF task on gulp #### Note: This task has to be processed before [Leverage task with unbundle](https://github.com/t2ym/gulp-i18n-leverage#leverage-task-with-unbundle) to pick up outputs of this task. #### Input: - Next XLIFF files in source - Current bundle JSON files in source (as output templates) #### Output: - Overwritten bundle JSON files in source ```javascript var gulp = require('gulp'); var JSONstringify = require('json-stringify-safe'); var stripBom = require('strip-bom'); var through = require('through2'); var XliffConv = require('xliff-conv'); // Import bundles.{lang}.xlf gulp.task('import-xliff', function () { var xliffPath = path.join('app', 'xliff'); var xliffConv = new XliffConv(); return gulp.src([ 'app/**/xliff/bundle.*.xlf' ]) .pipe(through.obj(function (file, enc, callback) { var bundle, bundlePath; var base = path.basename(file.path, '.xlf').match(/^(.*)[.]([^.]*)$/); var xliff = String(file.contents); if (base) { try { bundlePath = path.join(file.base, 'locales', 'bundle.' + base[2] + '.json'); bundle = JSON.parse(stripBom(fs.readFileSync(bundlePath, 'utf8'))); xliffConv.parseXliff(xliff, { bundle: bundle }, function (output) { file.contents = new Buffer(JSONstringify(output, null, 2)); file.path = bundlePath; callback(null, file); }); } catch (ex) { callback(null, file); } } else { callback(null, file); } })) .pipe(gulp.dest('app')) .pipe($.size({ title: 'import-xliff' })); }); ``` ### Export XLIFF task on gulp #### Note: If the `todo` items in JSON files are removed, the corresponding `trans-unit`s are treated as `approved="yes"` and `state="translated"`. #### Input: - Next bundles object in gulpfile.js #### Output: - bundle.{lang}.xlf XLIFF in DEST_DIR/xliff ```javascript var gulp = require('gulp'); var through = require('through2'); var XliffConv = require('xliff-conv'); var bundles; // bundles object generated by preprocess and leverage tasks // Generate bundles.{lang}.xlf gulp.task('export-xliff', function (callback) { var DEST_DIR = 'dist'; var srcLanguage = 'en'; var xliffPath = path.join(DEST_DIR, 'xliff'); var xliffConv = new XliffConv(); var promises = []; try { fs.mkdirSync(xliffPath); } catch (e) { } for (var lang in bundles) { if (lang) { (function (destLanguage) { promises.push(new Promise(function (resolve, reject) { xliffConv.parseJSON(bundles, { srcLanguage: srcLanguage, destLanguage: destLanguage }, function (output) { fs.writeFile(path.join(xliffPath, 'bundle.' + destLanguage + '.xlf'), output, resolve); }); })); })(lang); } } Promise.all(promises).then(function (outputs) { callback(); }); }); ``` ## API ### Constructor `var xliffConv = new XliffConv(options)` #### `options` object - date: Date, default: new Date() - date attribute value for XLIFF - xliffStates: Object, default: XliffConv.xliffStates.default - todo.op to XLIFF state mapping table - patterns: Object, default: XliffConv.patterns - A set of named regular expressions for pattern matching - logger: Function, default: console.log - information logger - warnLogger: Function, default: console.warn - warning logger - errorLogger: Function, default: console.error - error logger #### `XliffConv.xliffStates` object - predefined mapping tables for `options.xliffStates` ```javascript XliffConv.xliffStates = { // All state-less unapproved strings are regarded as needs-translation 'default': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[approved]' ] }, // Aannotations {{name}} and tags <tag-name> are regarded as translated 'annotationsAsTranslated': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[approved]', '[source~=annotationsAndTags]' ] }, // Newly added annotations {{name}} and tags <tag-name> are regarded as translated 'newAnnotationsAsTranslated': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[approved]', '[state==new&&source~=annotationsAndTags]' ] }, // Newly added annotations {{name}} and tags <tag-name> are regarded as translated only at export 'newAnnotationsAsTranslatedAtExport': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[approved]', '[export&&state==new&&source~=annotationsAndTags]' ] }, // Annotations {{name}} and tags <tag-name> are skipped in translation by translate=no 'annotationsAsNoTranslate': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[source~=annotationsAndTags&&translate:=no&&state:=final]', '[approved]' ], }, /* === State Mapping Tables for migration from xliff2bundlejson === */ // All state-less strings are regarded as approved=yes 'approveAll': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '' ] }, // State-less translated strings need review 'reviewTranslated': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '[!state&&!approved&&source==target]', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n', '[!state&&!approved&&source!=target]' ], 'default': [ 'translated', 'signed-off', 'final', '[approved]' ] }, // State-less translated strings are regarded as approved=yes 'approveTranslated': { 'add' : [ 'new' ], 'replace': [ 'needs-translation', 'needs-adaptation', 'needs-l10n', '[!state&&!approved&&source==target]', '' ], 'review' : [ 'needs-review-translation', 'needs-review-adaptation', 'needs-review-l10n' ], 'default': [ 'translated', 'signed-off', 'final', '[!state&&!approved&&source!=target]', '[approved]' ] } /* Expression format: [condition1&&condition2&&...&&effect1&&effect2&&...] - expression is true when all the conditions are true - optional effects are processed if the expression is true Operators for conditions: parameter - true if parameter is non-null !parameter - true if parameter is undefined, null, or '' parameter1==parameter2 - true if parameter1 is equal to parameter2 parameter1!=parameter2 - true if parameter1 is not equal to parameter2 parameter~=pattern - true if parameter matches the regular expression options.patterns.pattern - if options.patterns.pattern is undefined, pattern is treated as the matching string tag.attribute~=pattern - true if attribute value of tag matched the regular expression options.patterns.pattern - if options.patterns.pattern is undefined, pattern is treated as the matching string Operators for effects: tag.attribute:=value - assign attribute of tag with the string value attribute:=value - assign predefined alias attribute with the string value tag:=value - assign textContent of tag with the string value Predefined parameters: Undefined parameters are treated as strings for matching state - state attribute of target id - id attribute of trans-unit component - component name in id restype - restype attribute of trans-unit. 'x-json-string' for strings source - text content of source tag target - text content of target tag approved - true if approved attribute of trans-unit is 'yes' import - true on XLIFF import (parseXliff); false on XLIFF export (parseJSON) export - true on XLIFF export (parseJSON); false on XLIFF import (parseXliff) Predefined tags: file - file tag trans-unit - trans-unit tag source - source tag target - target tag Predefined alias attributes: translate - alias for trans-unit.translate approved - alias for trans-unit.approved state - alias for target.state */ }; ``` #### `XliffConv.patterns` object - predefined named regular expressions for `options.patterns` ```javascript XliffConv.patterns = { 'annotationsAndTags': /^({{[^{} ]*}}|\[\[[^\[\] ]*\]\]|<[-a-zA-Z]{1,}>)$/, 'annotations': /^({{[^{} ]*}}|\[\[[^\[\] ]*\]\])$/, 'numbers': /^[0-9.]{1,}$/, 'tags': /^<[-a-zA-Z]{1,}>$/ }; ``` ### `xliffConv.parseXliff(xliff, options, callback)` method - xliff: String, XLIFF as a string - options: Object, options.bundle as target bundle JSON object - callback: Function, callback(output) with output JSON object ### `xliffConv.parseJSON(bundles, options, callback)` method - bundles: Object, bundles object - options.srcLanguage: String, default: 'en' - `<file source-language>` attribute - options.destLanguage: String, default: 'fr' - `<file target-language>` attribute - options.xmlSpace: String, default: 'default' - `<file xml:space>` attribute - options.dataType: String, default: 'plaintext' - `<file datatype>` attribute - options.original: String, default: 'messages' - `<file original>` attribute - options.productName: String, default: 'messages' - `<file product-name>` attribute - options.xmlHeader: String, default: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xliff PUBLIC "-//XLIFF//DTD XLIFF//EN" "http://www.oasis-open.org/committees/xliff/documents/xliff.dtd"> ``` - options.xliffTemplate: String, default: ```xml <xliff version="1.0"> <file xml:space="[options.xmlSpace]" source-language="[options.srcLanguage]" target-language="[options.destLanguage]" datatype="[options.dataType]" original="[options.original]" date="[this.date.toISOString().replace(/[.][0-9]*Z$/, 'Z')]" product-name="[options.productName]"> <header> <tool tool-id="xliff-conv" tool-name="xliff-conv" tool-version="[toolVersion]"/> </header> <body> </body> </file> </xliff> ``` - options.transUnitTemplate: String, default: ```xml <trans-unit> <source></source> <target></target> </trans-unit> ``` - options.addNewAttr: Object, default: `undefined` - Customize id and add a new attribute to `<trans-unit>` with the original id value - labelArrayWithUniqueId is an Object mapping a new attribute value for each id ```javascript xliffConv.parseJSON(bundles, { srcLanguage: srcLanguage, destLanguage: destLanguage, addNewAttr: { newAttrName: labelMapWithUniqueId } }, function (output) { fs.writeFile(path.join(xliffPath, 'bundle.' + destLanguage + '.xlf'), output, resolve); }); ``` ```javascript // example labelMapWithUniqueId Object labelMapWithUniqueId = { // id: attribute value "Factory_audit_address": "ckv7ymf07ahqog4lur12bwobg1z3dsxzkqkdwxan", "alert_info_when_update_config_preferences": "ybsqyempsolypcf4poq1wdxxl8c04oam03ei27bc", "application_title": "rj7rtcdbefchcbrq9itw6sewjifd2v3c5dn99969", "back": "48gtruuew3ndd7pnj26lttt0kbgnlv2iyhtti99v", "barcode_section": "i2d0t2y11b5zlrlhbn5it8qkbxbp7ub0bdgxy7tr", "cancel_title": "bbzgu18z7wl6thj0eh9p83nlcrz4znyfox4khjuq", "client_initial_2_letter": "ilttwryn5jccb4wnhfu3nq9z72ds21m2ho7fnsgs" } ``` ```xml <!-- example trans-unit --> <!-- without options.addNewAttr --> <trans-unit id="Factory_audit_address" approved="yes"> <source>Address</source> <target state="translated">Adresse</target> </trans-unit> <!-- with options.addNewAttr = { resname: labelMapWithUniqueId } above --> <trans-unit id="ckv7ymf07ahqog4lur12bwobg1z3dsxzkqkdwxan" resname="Factory_audit_address" approved="yes"> <source>Address</source> <target state="translated">Adresse</target> </trans-unit> ``` - callback: Function, callback(output) with output XLIFF as a string #### Notes: - With `options.xliffTemplate`, all the attribute values within the template are NOT replaced. It is the caller's responsibility to set appropriate values to the attributes. - With `options.transUnitTemplate`, XliffConv does NOT recognize `<note>` tags in the template in importing XLIFF and discards the contents. ### Custom XLIFF restype attributes | restype | JSON type | Note | |:-----------------|:----------|:---------------------------| | x-json-string | string | Omitted | | x-json-boolean | boolean | "true" or "false" in value | | x-json-number | number | | | x-json-object | object | Unused for now | | x-json-undefined | undefined | Empty string in value | ### Default Mapping of todo.op and XLIFF states #### JSON -> XLIFF | todo.op | XLIFF state | |:--------|:-------------------------| | add | new | | replace | needs-translation | | review | needs-review-translation | | N/A | translated | #### XLIFF -> JSON | XLIFF state | approved | todo.op | Note | |:-------------------------|:----------|:--------|:------------| | new | no or N/A | add | | | needs-translation | no or N/A | replace | | | needs-adaptation | no or N/A | replace | | | needs-l10n | no or N/A | replace | | | N/A | no or N/A | replace | | | needs-review-translation | no or N/A | review | | | needs-review-adaptation | no or N/A | review | | | needs-review-l10n | no or N/A | review | | | translated | yes | N/A | Remove todo | | signed-off | yes | N/A | Remove todo | | final | yes | N/A | Remove todo | | N/A | yes | N/A | Remove todo | ## License [BSD-2-Clause](https://github.com/t2ym/xliff-conv/blob/master/LICENSE.md) <file_sep>/test/test.js /* @license https://github.com/t2ym/xliff-conv/blob/master/LICENSE.md Copyright (c) 2016, <NAME> <<EMAIL>>. All rights reserved. */ 'use strict'; var chai = require('chai'); var XliffConv = require('../xliff-conv'); var XliffConvBasicTest = require('./basic-test.js'); var XliffConvCustomTest = require('./custom-test'); var basicTest = new XliffConvBasicTest(); var customTest = new XliffConvCustomTest(); basicTest.run(XliffConv, chai); customTest.run(XliffConv, chai);
2d1aa84a1cb728ab1c8dc9833d1a9c7729b9a288
[ "Markdown", "JavaScript" ]
2
Markdown
t2ym/xliff-conv
d1b9cc5eb76dd911a9fe01bbb8c5184f7f64be8b
8d3a11ada7b576de919ee6be4973f66dbe0b94d3
refs/heads/main
<file_sep>// 数组去重方法 // 最基本的去重方法 //思路:定义一个新数组,并存放原数组的第一个元素,然后将元素组一一和新数组的元素对比,若不同则存放在新数组中。 function unique(arr){   var res = [arr[0]];   for(var i=1;i<arr.length;i++){     var repeat = false;     for(var j=0;j<res.length;j++){       if(arr[i] == res[j]){         repeat = true;         break;       }     }     if(!repeat){       res.push(arr[i]);     }   }   return res; } // 先排序再去重 function unique(arr){ // sort() 方法用于对数组的元素进行排序。 var arr2=arr.sort(); var res=[arr2[0]]; for(var i=1;i<arr2.length;i++){ if(arr2[i]!==res[res.length-1]){ res.push(arr2[i]); } } return res; } // 利用对象属性去重 // 思路:每次取出原数组的元素,然后在对象中访问整个属性,如果它存在就说明重复 function unique(arr){ var res=[]; var json={}; for(var i=0;i<arr.length;i++){ if(!json[arr[i]]){ res.push(arr[i]); json[arr[i]]=1; } } return res; } // 利用下标查询 function unique(arr){ var newArr=[arr[0]]; for(var i=1;i<arr.length;i++){ if(newArr.indexOf(arr[i]==-1)){ newArr.push(arr[i]); } } return newArr; } // ES6的写法 var unique = (a) => [...new Set(a)] // 如果利用map的话是 function unique(arr){ const seen=new Map(); // filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。 return arr.filter((a)=>!seen.has(a)&&seen.set(a,1)); }<file_sep>// 实现indexof的方法 function indexFun(array,val){ if(!Array.isArray(array)) return; let length=array.length; for(let i=0;i<length;i++){ if(array[i]==val){ return i; } } return -1; }<file_sep># Basic-algorithm Basic algorithm # 基础算法 ## 数组扁平化 思路:递归调用再用concat连接 ```js // 递归实现数组扁平化 function falttenArray(array){ if(!Array.isArray(array))return; let result=[]; //reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个 //值。 result=array.reduce(function(pre,item){ // 判断元素是否为数组,如果是就递归调用,不是就把它加入数组中。 //concat() 方法用于连接两个或多个数组。 return pre.concat(array.isArray(item)?falttenArray(item):item); },[]); return result; } ``` toString()方法实现数组扁平化 ```js // tostring 方法实现数组的扁平化 function flatArr(array){ // split 数组变成字符串,改变了元素的类型 // map()方法按照原始数组元素顺序依次处理元素。 return array.toString().split(",").map(function(item){ return +item; }) } ```
f62338a153693c4f4cc1b8ea0d446764d8d39839
[ "JavaScript", "Markdown" ]
3
JavaScript
caowanjing-code/Basic-algorithm
3ca61f27ad06d9f6207f0674b12c6dc02d5ae043
e170868fa11b9f5ee6ee9634d96d468e6e8833a8
refs/heads/main
<repo_name>dimaShilov9645/Crypto-Exchange<file_sep>/tailwind.config.js module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: {}, fontFamily: { 'sans': ['Roboto'], }, colors: { gray: { light: '#F6F7F8', DEFAULT: '#E3EBEF' }, black: { DEFAULT: '#282828' }, blue: { light: '#80A2B6', DEFAULT: '#11B3FE', dark: '#0095E0' }, red: { DEFAULT: '#E03F3F' }, white: { light: '#EAF1F7', DEFAULT: '#FFFFFF', } } }, variants: { extend: {}, }, plugins: [], }
f31a2dec43cf5d492982df8a73e117faab198e8c
[ "JavaScript" ]
1
JavaScript
dimaShilov9645/Crypto-Exchange
7920240acfb1b5037cfce03626024c358419f2f8
08bc748e1199ccb730e903230900cc36f0f38122
refs/heads/main
<file_sep>// Porfavor, inclua textos no seguinte formato: // home > nome_component > nome_texto > "Texto" const home = { title: "Instituto Glória", tagline:"A Gloria nasceu para acabar com a violência contra mulheres e meninas", home:{ button: "DOE AGORA", }, toolbar: { manifest: "Manifesto", home: "Início", about: "Sobre", news: "Notícias", we: "Quem Faz Acontecer", projects: "Projetos", volunteer: "Voluntariado", }, partners: { title: "Nossos Parceiros" }, research: { title: "Responda a nossa pesquisa!", subtitle: "Não se preocupe! Nossa pesquisa é totalmente <b>anônima</b>", button: "Clique aqui", button_send: "Enviar!", thankyou: "Obrigada!", form: { know: "Você sabe o que é violência física?", suffer: "Você já sofreu algum tipo de violência?", type: "Qual tipo de violência você tem mais medo?", }, }, we:{ title:"Quem é a Gloria?", description: " A Gloria é uma inteligência artificial, uma robozinha, focada em acabar com a violência contra mulheres e meninas. A Gloria busca, através de diversos projetos, coletar e minerar dados em que, a partir de “historias” contadas aprende o melhor caminho para o combate à violência de gênero.", button: "Saiba mais" }, projects:{ title:"Conheça nossos projetos", convida:{ theme:"Saúde", title:"Rede Convida" }, game:{ theme:"Educação", title:"O Mundo de Gloria" }, steam:{ theme:"Empoderamento Feminino", title:"STEAM Girls" }, button:"Saiba mais +" }, data:{ button: "Veja Mais", first_card:{ info: "A cada 7.2 segundos, uma mulher é vítima de VIOLÊNCIA FÍSICA.", counter:"MULHERES JÁ FORAM VÍTIMAS DE VIOLÊNCIA FÍSICA HOJE." }, second_card:{ info: "A cada 1.4 segundo, uma mulher é vítima de ASSÉDIO no Brasil.", counter:"MULHERES JÁ FORAM ASSEDIADAS HOJE. APENAS NO BRASIL." }, third_card:{ info: "A cada 6.9 segundos, uma mulher é vítima de PERSEGUIÇÃO.", counter:"MULHERES JÁ FORAM AMEDRONTADAS OU PERSEGUIDAS HOJE." }, }, form: { email: "E-mail", phone: "Telefone", birth: "Data de Nascimento", gender: { masc: "Masculino", fem: "Feminino", other: "Outros", }, selector: "Selecione", yes: "Sim", no: "Não", violence: { physical: "Física", sexual: "Sexual", psychological: "Psicológica", digital: "Digital", }, send: "Enviar" } } export default home; <file_sep>// Porfavor, inclua textos no seguinte formato: // home > nome_component > nome_texto > "Texto" const volunteer = { title: "Gloria Institute", tagline:"Gloria was born to stop the violence against women and girls", top:{ button: "Be a volunteer", }, toolbar: { manifest: "Manifest", home: "Home", about: "About", news: "News", we: "Creators and Partners", projects: "Projects", volunteer: "Volunteering", }, link:{ title:"Glória's volunteering program", description:"Sign-in for a volunteering at Gloria Institute, fill the form in the link above", } } export default volunteer; <file_sep>const MembersProj = [ /* A definição da chave deve seguir a seguinte regra: - regra geral: usar o primeiro nome mais último sobrenome; - obs: caso o nome tenha algum sufixo, acrescentar a primeira letra do sufixo no final do nome; - exceção 1: usar o "nome de guerra" de professor da UnB (se houver); - exceção 2: usar o sobrenome se for um sobrenome já utilizado para se referir a pessoa. Exemplo: Patrão, Prado, Venzi e Kfouri. Obs.: - todos as letras minúsculas; - não usar acentos ou cedilha. */ { key: "Beatriz", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Fernanda", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } },{ key: "Isabella", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "João", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Kamilla", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Rachel", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Rebeca", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Savia", name: "<NAME>", job: "medicina", belong: true, lab: { active: true, area: "Convida" } }, { key: "Alomar", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Antonio", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Heverton", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Hugo", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Miriam", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "PedroAugusto", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Rhógeris", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Victor", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Walesson", name: "<NAME>", job: "desenvolvedor", belong: true, lab: { active: true, area: "Convida" } }, { key: "Eduardo", name: "<NAME>", job: " ", belong: true, lab: { active: true, area: "Convida" } }, { key: "Amanda", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Ana", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Ingrid", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Izabella", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "João", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Laura", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Stephanie", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Vinicius", name: "<NAME>", job: "comunicação", belong: true, lab: { active: true, area: "Convida" } }, { key: "Isabella", name: "<NAME>", job: "Governança", belong: true, lab: { active: true, area: "Convida" } }, { key: "Isabella", name: "<NAME>", job: "Governança", belong: true, lab: { active: true, area: "Convida" } }, { key: "Alessandra", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "AnaBea", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "AnaCarol", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "Isadora", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "Larrisa", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "Waleska", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "UNOPs" } }, { key: "Raline", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Mapa da Violência" } }, { key: "Graziella", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jovens Embaixadoras Glória" } }, { key: "Karen", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jovens Embaixadoras Glória" } }, { key: "Nathalia", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jovens Embaixadoras Glória" } }, { key: "Maria", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jovens Embaixadoras Glória" } }, { key: "Sara", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jovens Embaixadoras Glória" } }, { key: "Alexandre", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "AmandaSolidade", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Andre", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Antonio", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Daniel", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "EduardoSantos", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Emily", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Fernanda", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Fernando", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Filipe", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Gabriela", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Giovanna", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Gustavo", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Helena", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Henniton", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "HenriqueCamara", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Katia", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Leticia", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Lucas", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Marina", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "MateusPedrosa", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Nicolas", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "MateusPedrosa", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Negrao", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "Renan", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "RhogerisGomes", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "RodrigoAlves", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "SaraGaspar", name: "<NAME>", job: "voluntario", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "SthefanieIole", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, { key: "ThaisFreitas", name: "<NAME>", job: "voluntaria", belong: true, lab: { active: true, area: "Jogo - Mundo de Glória" } }, ]; export default MembersProj;<file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import SiteLayout from '../views/Site.vue' import Home from "../site/Home.vue"; import We from "../site/We.vue"; import About from "../site/About.vue" import Projects from "../site/Projects.vue" import News from "../site/News.vue" import Volunteer from "../site/Volunteer.vue" Vue.use(VueRouter) const routes = [ { path: "/", component: SiteLayout, children: [ { path: '', name: "Home", component: Home }, { path: 'we', name: "We", component: We }, { path: 'about', name: "About", component: About }, { path: 'projects', name: "Projects", component: Projects }, { path: 'news', name: "News", component: News }, { path: 'volunteer', name: "Volunteer", component: Volunteer } ] }, ] const router = new VueRouter({ mode: 'history', routes }) export default router <file_sep>const Members = [ /* A definição da chave deve seguir a seguinte regra: - regra geral: usar o primeiro nome mais último sobrenome; - obs: caso o nome tenha algum sufixo, acrescentar a primeira letra do sufixo no final do nome; - exceção 1: usar o "nome de guerra" de professor da UnB (se houver); - exceção 2: usar o sobrenome se for um sobrenome já utilizado para se referir a pessoa. Exemplo: Patrão, Prado, Venzi e Kfouri. Obs.: - todos as letras minúsculas; - não usar acentos ou cedilha. */ { key: "Cristina", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Communications" } }, { key: "Cristina", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Communications" } }, { key: "Cristina2", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Projects" } }, { key: "Cristina2", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Projects" } }, { key: "Cristina3", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Governances" } }, { key: "Cristina3", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Governances" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Finances" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Finances" } }, { key: "Daniel", name: "<NAME>", job: "Brabo do insta", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Technology" } }, { key: "Daniel", name: "<NAME>", job: "Brabo do insta", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Technology" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Legal" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Legal" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Business" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "Business" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "CEO" } }, { key: "Cristina4", name: "<NAME>", job: "Chief Executive Office", picture: "https://loremflickr.com/250/370/paris/?random=1", belong: true, lab: { active: true, area: "CEO" } }, // template // { // key: "x", // name: "", // job: "Area atuação", // picture: "man", // lab: { // active: false, // area: "xxxxxxxxxxx", // } // }, ]; export default Members;<file_sep>// Porfavor, inclua textos no seguinte formato: // about > nome_component > nome_texto > "Texto" const about = { projects:{ button: "CONHEÇA NOSSOS PROJETOS", }, golden_circle: { title1: "A plataforma", title2: "O CÍRCULO DE OURO", first: "1 - A glória nasceu com o ideal de reduzir (e, por que não, combater) a opressão e violência física, psicológica e sexual contra mulheres", second: "2 - A partir da coleta de dados, geramos conteúdo educacional e criamos uma rede de apoio com as ferramentas necessárias para a melhoria social", third: "3 - Uma plataforma segura e de fácil acesso para mulheres em situação de vulnerabilidade e repressão" }, manifesto: { title: "Veja nosso manifesto!", text: "A Gloria nasceu para buscar soluções sociais transformadoras e deixar um legado para as próximas gerações de homens e mulheres. Somos uma plataforma de transformação social, a partir da coleta de dados, geramos conteúdo educacional e criamos uma rede de apoio com as ferramentas necessárias para a melhoria social.", }, goals: { title: "Em 2 anos, queremos que a Glória esteja no mundo inteiro", text: "O objetivo do projeto é impactar mais de 20 milhões de pessoas, além de gerar relatórios com segmentação por faixa etária, local, dados socioeconômicos e padrão de ocorrências, que auxiliem o público na formação de políticas, projetos e ações para combater a violência contra a mulher" } } export default about; <file_sep> const we = { title: "Instituto Gloria", tagline:"A Glória nasceu para acabar com a violência contra mulheres e meninas", organogram:{ title:"Nosso Time Institucional", ceo:{ head:"<NAME>", department:"CEO" }, business:{ head:"<NAME>", department:"Business" }, legal:{ head:"<NAME>", department:"Legal" }, tech:{ head:"<NAME>", department:"Technology" }, fin:{ head:"<NAME>", department:"Finances" }, gov:{ head:"<NAME>", department:"Governances" }, proj:{ head:"<NAME>", department:"Projects" }, com:{ head:"<NAME>", department:"Communications" }, }, projects:{ title:"Nosso Time de Projetos", convida:{ head:"<NAME>", department:"Convida" }, gloria:{ head:"<NAME>", department:"Gloria" }, steam:{ head:"<NAME>", department:"STEAM Girls" }, game:{ head:"<NAME>", department:"Jogo - Mundo de Glória" }, unops:{ head:"<NAME>", department:"UNOPs" }, ambassador:{ head:"<NAME>", department:"Jovens Embaixadoras Glória" }, map:{ head:"<NAME>", department:"Mapa da Violência" } }, campaigns:{ title:"Nossas Campanhas" }, local:{ local:"pt" } } export default we;<file_sep> const we = { title: "Gloria Institute", tagline:"Gloria was born to stop the violence against women and girls", organogram:{ title:"Our Institutional Team", ceo:{ head:"<NAME>", department:"CEO" }, business:{ head:"<NAME>", department:"Business" }, legal:{ head:"<NAME>", department:"Legal" }, tech:{ head:"<NAME>", department:"Technology" }, fin:{ head:"<NAME>", department:"Finances" }, gov:{ head:"<NAME>", department:"Governances" }, proj:{ head:"<NAME>", department:"Projects" }, com:{ head:"<NAME>", department:"Communications" }, }, projects:{ title:"Our Projects Team", convida:{ head:"<NAME>", department:"Convida" }, gloria:{ head:"<NAME>", department:"Gloria" }, steam:{ head:"<NAME>", department:"STEAM Girls" }, game:{ head:"<NAME>", department:"Game - Glória's World" }, unops:{ head:"<NAME>", department:"UNOPs" }, ambassador:{ head:"<NAME>", department:"Glória Young Ambassador" }, map:{ head:"<NAME>", department:"Violece Map" } }, campaigns:{ title:"Our Campaigns" }, local:{ local:"en" } } export default we;<file_sep>// Porfavor, inclua textos no seguinte formato: // home > nome_component > nome_texto > "Texto" const home = { title: "Gloria Institute", tagline:"Gloria was born to stop the violence against women and girls", home:{ button: "DONATE NOW", }, toolbar: { manifest: "Manifest", home: "Home", about: "About", news: "News", we: "Creators and Partners", projects: "Projects", volunteer: "Volunteering", }, partners: { title: "Our Partners", }, research: { title: "Answer our survey!", subtitle: "Don't worry! Our survey is completely <b>anonymous</b>", button: "Click Here", button_send: "Send!", thankyou: "Thank You!", form: { know: "Do you know what physical violence is?", suffer: "Have you ever suffered any kind of violence?", type: "What kind of violence are you most afraid of?", }, }, title: "Gloria Institute", we:{ title:"Who is Gloria?", description: "Gloria is an artificial intelligence, a robot, focused on ending violence against women and girls. Gloria seeks, through several projects, to collect and mine data in which, from the “stories” told, it learns the best way to combat gender violence.", button: "Find out more" }, projects:{ title:"See our projects", convida:{ theme:"Health", title:"Rede Convida" }, game:{ theme:"Education", title:"O Mundo de Gloria" }, steam:{ theme:"Female Empowerment", title:"STEAM Girls" }, button:"Find out more +" }, data:{ button: "More", first_card:{ info: "Every 7.2 seconds, a woman is victim of dosmetic violence", counter:"WOMEN HAVE BEEN VICTIM OF DOMESTIC VIOLENCE" }, second_card:{ info: "Every 1.4 seconds, a woman is a victim of HARASSMENT.", counter:"WOMEN HAVE ALREADY BEEN HARASSED TODAY." }, third_card:{ info: "Every 6.9 seconds, a woman is a victim of PERSECUTION.", counter:"WOMEN HAVE BEEN PERSECUTTED TODAY." }, }, form: { email: "E-mail", phone: "Phone", birth: "Birth Date", gender: { masc: "Masc", fem: "Fem", other: "Other", }, selector: "Select", yes: "Yes", no: "No", violence: { physical: "Physical", sexual: "Sexual", psychological: "Psychological", digital: "Digital", }, send: "Enviar" } } export default home;<file_sep>// Porfavor, inclua textos no seguinte formato: // home > nome_component > nome_texto > "Texto" const volunteer = { title: "Instituto Glória", tagline:"A Gloria nasceu para acabar com a violência contra mulheres e meninas", top:{ button: "Seja um voluntário(a)", }, toolbar: { manifest: "Manifesto", home: "Início", about: "Sobre", news: "Notícias", we: "Quem Faz Acontecer", projects: "Projetos", volunteer: "Voluntariado", }, link:{ title:"Programa de voluntariado da Glória", description:"Se inscreva para um voluntariado no Instituto Glória, preencha o formulário acima", } } export default volunteer;
42386e840ea37f8c26e9e2c806ffbee85781872e
[ "JavaScript" ]
10
JavaScript
InstitutoGloria/eusouagloria.github.io
85dfd26183795e95523b01b2bb30f2179a4d3703
611933598c20194d41d47bd53b857d11ddaa5d96
refs/heads/master
<repo_name>lacchid/WebApplication<file_sep>/WebApplication.Client/FormMain.cs using System; using System.ComponentModel; using System.ServiceModel; using System.Windows.Forms; using WebApplication.Contract.NeutralVersion; namespace WebApplication.Client { public partial class FormMain : Form { private IWebServiceContract _webService; private FormWait _formWait; public FormMain() { InitializeComponent(); InitWebService(); } private void InitWebService() { try { _webService = new ServicesClient(); return; } catch (Exception e) { MessageBox.Show("Connection Error", Text, MessageBoxButtons.OK); } _webService = null; } private void buttonFibonacci_Click(object sender, EventArgs e) { if (backgroundWorker.IsBusy) return; try { buttonFibonacci.Enabled = false; buttonCancel.Enabled = true; var fibonacciInput = GetComboBoxFibonacciValue(); if (!fibonacciInput.HasValue) return; _formWait = new FormWait(); backgroundWorker.RunWorkerAsync(fibonacciInput); _formWait.Show(this); } catch (Exception exception) { MessageBox.Show("An error has ocurred", "Oups", MessageBoxButtons.OK); FormWaitClose(); buttonFibonacci.Enabled = true; buttonCancel.Enabled = false; } } private void FormWaitClose() { if(_formWait == null) return; _formWait.Close(); _formWait.Dispose(); } private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { FormWaitClose(); buttonFibonacci.Enabled = true; buttonCancel.Enabled = false; if (e.Cancelled) { MessageBox.Show("Canceled by User"); } else if (e.Error != null) { MessageBox.Show("error", e.Error.Message, MessageBoxButtons.OK); } else { if(e.Result != null) MessageBox.Show(e.Result.ToString(), "Result", MessageBoxButtons.OK); } } private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { _formWait?.SetLoaderCompletionPercent(e.ProgressPercentage); } private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { if(!(sender is BackgroundWorker worker)) return; var n = (int) e.Argument; try { e.Result = _webService.Fibonacci(n); } catch (System.ServiceModel.CommunicationException exception) { MessageBox.Show("Connection Error", "Oups", MessageBoxButtons.OK); throw new Exception("Connection Error", exception); } catch (Exception exception) { MessageBox.Show("An error has ocurred", "Oups", MessageBoxButtons.OK); throw new Exception("Connection Error", exception); } for (int i = 1; i <= n; i++) { if (worker.CancellationPending) { e.Cancel = true; break; } System.Threading.Thread.Sleep(250); worker.ReportProgress(i * 100 / n); } } private void buttonCancel_Click(object sender, EventArgs e) { backgroundWorker.CancelAsync(); buttonCancel.Enabled = false; } private void comboBoxFibonacciImput_SelectionChangeCommitted(object sender, EventArgs e) { buttonFibonacci.Enabled = GetComboBoxFibonacciValue() != null; } private int? GetComboBoxFibonacciValue() { if (comboBoxFibonacciImput.SelectedItem is ComboboxItem comboBoxItemSelected && comboBoxItemSelected.Value.HasValue) { return ((ComboboxItem)comboBoxItemSelected).Value; } return null; } } } <file_sep>/WebApplication.Client/FormWait.cs using System; using System.Windows.Forms; namespace WebApplication.Client { public partial class FormWait : Form { public FormWait() { InitializeComponent(); } public void SetLoaderCompletionPercent(int p) { progressBar.Value = p; } } } <file_sep>/WebApplication.Service/SequencesService.cs using WebApplication.Service.Interfaces; namespace WebApplication.Service { public class SequencesService : ISequencesService { decimal ISequencesService.Fibonacci(int n) { return Fibonacci(n); } private static readonly decimal[] fib = new decimal[1000]; private static decimal Fibonacci(int n) { // 1 <= N <= 100 else return -1 if (n < 1 || n > 100) return -1; if (fib[n] == 0) { if ((n == 1) || (n == 2)) { fib[n] = 1; } else { fib[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } } return fib[n]; } } }<file_sep>/WebApplication.Tests/ConvertServiceTests.cs using NUnit.Framework; using WebApplication.Service; using WebApplication.Service.Interfaces; namespace WebApplication.Tests { [TestFixture] public class ConvertServiceTests { private readonly IConvertService _convertService; public ConvertServiceTests() { _convertService = new ConvertService(); } [Test] public void XmlToJson_Test() { var r = _convertService.XmlToJson(string.Empty); Assert.AreEqual(string.Empty, r); r = _convertService.XmlToJson("<foo>hello</bar>"); var containsError = r.Contains("Bad Xml format"); Assert.IsTrue(containsError); r = _convertService.XmlToJson("<TRANS><HPAY><ID idType=\"externalId\">103</ID><STATUS>3</STATUS><EXTRA><IS3DS>0</IS3DS><AUTH>031183</AUTH></EXTRA><INT_MSG/><MLABEL>501767XXXXXX6700</MLABEL><MTOKEN>project01</MTOKEN></HPAY></TRANS>"); Assert.AreEqual("{\r\n \"TRANS\": {\r\n \"HPAY\": {\r\n \"ID\": \"103\",\r\n \"STATUS\": \"3\",\r\n \"EXTRA\": {\r\n \"IS3DS\": \"0\",\r\n \"AUTH\": \"031183\"\r\n },\r\n \"INT_MSG\": null,\r\n \"MLABEL\": \"501767XXXXXX6700\",\r\n \"MTOKEN\": \"project01\"\r\n }\r\n }\r\n}", r); } } }<file_sep>/WebApplication.Tests/SequencesServiceTests.cs using NUnit.Framework; using WebApplication.Service; using WebApplication.Service.Interfaces; namespace WebApplication.Tests { [TestFixture] public class SequencesServiceTests { private readonly ISequencesService _sequencesService; public SequencesServiceTests() { _sequencesService = new SequencesService(); } [Test] public void Fibonacci_Test() { var errorResultExpected = -1; var r = _sequencesService.Fibonacci(0); Assert.AreEqual(errorResultExpected, r); r = _sequencesService.Fibonacci(-999); Assert.AreEqual(errorResultExpected, r); r = _sequencesService.Fibonacci(101); Assert.AreEqual(errorResultExpected, r); //Fibonacci(1) must return 1 r = _sequencesService.Fibonacci(1); Assert.AreEqual(1, r); //Fibonacci(2) must return 1 r = _sequencesService.Fibonacci(2); Assert.AreEqual(1, r); //Fibonacci(6) must return 8 r = _sequencesService.Fibonacci(6); Assert.AreEqual(8, r); r = _sequencesService.Fibonacci(100); Assert.AreEqual(354224848179261915075M, r); } } }<file_sep>/WebApplication.Contract/NeutralVersion/IWebServiceContract.cs using System.ServiceModel; namespace WebApplication.Contract.NeutralVersion { [ServiceContract] public interface IWebServiceContract { [OperationContract] string XmlToJson(string xml); [OperationContract] decimal Fibonacci(int n); } }<file_sep>/WebApplication.Service/Interfaces/ISequencesService.cs namespace WebApplication.Service.Interfaces { public interface ISequencesService { decimal Fibonacci(int n); } }<file_sep>/WebApplication/NeutralVersion/WebService.cs using WebApplication.Contract.NeutralVersion; using WebApplication.Service.Interfaces; namespace WebApplication.NeutralVersion { public class WebService : IWebServiceContract { private readonly IConvertService _convertService; private readonly ISequencesService _sequencesService; public WebService(IConvertService convertService, ISequencesService sequencesService) { _convertService = convertService; _sequencesService = sequencesService; } public string XmlToJson(string xml) { return _convertService.XmlToJson(xml); } public decimal Fibonacci(int n) { return _sequencesService.Fibonacci(n); } } }<file_sep>/WebApplication.Service/ConvertService.cs using System; using System.IO; using System.Xml; using Newtonsoft.Json; using WebApplication.Service.Interfaces; using Formatting = Newtonsoft.Json.Formatting; namespace WebApplication.Service { public class ConvertService : IConvertService { public string XmlToJson(string xml) { if (string.IsNullOrWhiteSpace(xml)) return string.Empty; try { var xmlDocument = new XmlDocument(); using (var stringReader = new StringReader(xml)) { xmlDocument.Load(stringReader); var nodes = xmlDocument.SelectNodes("//*"); if (nodes != null) { foreach (XmlNode node in nodes) { node.Attributes?.RemoveAll(); } } var json = JsonConvert.SerializeXmlNode(xmlDocument.DocumentElement, Formatting.Indented); return json; } } catch (Exception e) { return $"Bad Xml format. Input:{xml}. ExcepionDetails: {JsonConvert.SerializeObject(e)}"; } } } }<file_sep>/README.md # WebApplication en reponse à https://gist.github.com/lemonway/4a2a22949e96863769ce91185bfc2f43 <file_sep>/WebApplication.Client/ServicesClient.cs using System; using System.ServiceModel; using System.Threading; using WebApplication.Contract.NeutralVersion; namespace WebApplication.Client { public class ServicesClient : IWebServiceContract { private readonly IWebServiceContract _webService; public ServicesClient() { var basicHttpBinding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress(new Uri(string.Format("http://{0}:5050/Service.svc", Environment.MachineName))); var channelFactory = new ChannelFactory<IWebServiceContract>(basicHttpBinding, endpointAddress); _webService = channelFactory.CreateChannel(); } public string XmlToJson(string xml) { return _webService.XmlToJson(xml); } public decimal Fibonacci(int n) { return _webService.Fibonacci(n); } } }<file_sep>/WebApplication/Startup.cs using System.ServiceModel; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using SoapCore; using WebApplication.Contract.NeutralVersion; using WebApplication.NeutralVersion; using WebApplication.Service; namespace WebApplication { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.TryAddSingleton<IWebServiceContract, WebService>(); services.AddServices(); services.AddMvc(x => x.EnableEndpointRouting = false); services.AddSoapCore(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSoapEndpoint<IWebServiceContract>("/Service.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer); app.UseSoapEndpoint<IWebServiceContract>("/Service.asmx", new BasicHttpBinding(), SoapSerializer.XmlSerializer); app.UseMvc(); } } } <file_sep>/WebApplication.Service/ConfigureServices.cs using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using WebApplication.Service.Interfaces; namespace WebApplication.Service { public static class ConfigureServices { public static void AddServices(this IServiceCollection services) { services.TryAddSingleton<ISequencesService, SequencesService>(); services.TryAddSingleton<IConvertService, ConvertService>(); } } }<file_sep>/WebApplication.Service/Interfaces/IConvertService.cs namespace WebApplication.Service.Interfaces { public interface IConvertService { string XmlToJson(string xml); } }
9105e1a7039b4891abc54108acb133eba77a058a
[ "Markdown", "C#" ]
14
C#
lacchid/WebApplication
09e5f7a7fb9465124e2c9e668a72fa982651e918
2ccb371cb60119fbd7d96c75c1f8e22a5ea4b00c
refs/heads/master
<file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>Новый тикет</span> </div> <div class="page-text"> <div style="width: 450px; margin: auto;"> <?php echo validation_errors(); ?> <form method="post" action="<? echo base_url();?>tickets/add.html"> <label class="control-label" for="title">Заголовок тикета:</label> <input style="margin-bottom: 15px;" class="form-control" type="text" name="title" id="title"> <label class="control-label" for="text">Опишите вашу проблему:</label> <textarea name="text" class="form-control" style="height: 250px; margin-bottom: 15px;" id="text" type="text"></textarea> <input type="submit" class="btn btn-success"> </form> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Merchant extends CI_Controller { public function __consturct() { parent::__construct(); } public function pay_success() { redirect(); } public function pay_order(){ $this->load->model('model_merchant'); $sign = md5($_POST['MERCHANT_ID'].':'.$_POST['AMOUNT'].':'.$this->config->item('secret2').':'.$_POST['MERCHANT_ORDER_ID']); if($sign !== $_POST['SIGN']) { print "bad sign!"; return; } if(!$this->model_merchant->check_payment($this->input->post('MERCHANT_ORDER_ID'))) { print('bad order id!'); return; } //Зачисляем на баланс if(!$this->model_merchant->update_balance($this->input->post('MERCHANT_ORDER_ID'), $this->input->post('AMOUNT'))) { print 'Error: #35_bad_order_id(balance)'; return; } //Очищаем неоплаченные "квитанции". А почему бы и нет. скрипт мой как-никак $this->model_merchant->clean_pays(); redirect(); } public function pay_fail(){ print "fail"; } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование кейса <? echo $name;?></div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/boxs/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name" value="<? echo $name;?>"> </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">URL кейса</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input4" name="alias" value="<? echo $alias;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Сортировка</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="sort" value="<? echo $sort;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Изображение</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="pic" value="<? echo $pic;?>"> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Прайс</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input3" name="price" value="<? echo $price;?>"> </div> </div> <div class="col-lg-6" style="margin-left: 45px; margin-bottom: 25px;"> <div class="input-group"> <label for="input3" class="pull-right" style="margin-right: 25px;">Скидка</label> <span class="input-group-addon"> <input name="setDiscount" type="checkbox" id="setDiscount" <? if($setDiscount) echo 'checked="checked"';?>> </span> <input type="text" class="form-control" id="discount" name="discount" value="<? echo $discount;?>"> </div> </div> <div class="form-group" style="margin-top: 100px;"> <label for="position" class="col-sm-2 control-label">Позиция:</label> <div class="col-sm-10"> <select class="form-control" name="position" id="position"> <option value="1" <? if($position == 1) echo 'selected';?>>Топ-линия 1</option> <option value="2" <? if($position == 2) echo 'selected';?>>Топ-линия 2</option> <option value="0" <? if($position == 0) echo 'selected';?>>Кейсы</option> <option value="3" <? if($category == 2) echo 'selected';?>>Коллекции</option> </select> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label">URL-суфикс:</label> <div class="col-sm-10"> <select class="form-control" name="category" id="category"> <option value="0" <? if($category == 0) echo 'selected';?>>case</option> <option value="1" <? if($category == 1) echo 'selected';?>>random</option> <option value="2" <? if($category == 2) echo 'selected';?>>collection</option> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox" name="public" <? if($public) echo 'checked="checked"';?>> Опубликовать </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="show" <? if($show) echo 'checked="checked"';?>> Отображать на главной </label> </div> </div> </div> <div class="form-group"> <label for="position" class="col-sm-2 control-label">Тип кейса:</label> <div class="col-sm-10"> <select class="form-control" name="type" id="type"> <? foreach($types as $type1):?> <option <? if($type1['alias'] == $type) echo "selected";?> value="<? echo $type1['alias'];?>"><? echo $type1['alias'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/boxs/box_delete/<? echo $id;?>">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div> <script> $(function() { $('#setDiscount').change(function () { if($('#setDiscount').prop("checked")) $('#discount').addClass('disabled'); else $('#discount').removeClass('disabled'); }); }); </script><file_sep><!DOCTYPE html> <html> <head> <title>Административный раздел</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="<?php echo base_url();?>css/admin/bootstrap.min.css" rel="stylesheet"> <link href="<?php echo base_url();?>css/admin/styles.css" rel="stylesheet"> <link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://select2.github.io/dist/js/select2.min.js"></script> <script type="application/javascript"> $(document).ready(function() { $(".chosen").select2(); }); </script> </head> <body> <div class="header"> <div class="container"> <div class="row"> <div class="col-md-2 pull-right"> <div class="navbar navbar-inverse" role="banner"> <nav class="collapse navbar-collapse bs-navbar-collapse navbar-right" role="navigation"> <ul class="nav navbar-nav"> <li><a href="<? echo base_url();?>" target="_blank">На сайт</a></li> </ul> </nav> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование настроек сайта</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/settings.html" method="post"> <? foreach($settings as $sett):?> <div class="form-group"> <label for="input1" class="col-sm-2 control-label"><? echo $sett['title'];?></label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="<? echo $sett['key'];?>" value="<? echo $sett['value'];?>"> </div> </div> <? endforeach;?> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Изменить</button> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_main extends CI_Model { public $cCount = 0; private $tquery = ""; private $fq = false; public function get_boxs() { $this->db->where('public', 1); $this->db->where('show', 1); $this->db->order_by('sort', 'ASC'); $query = $this->db->get("box"); if($query->num_rows() < 1) return false; return $query->result_array(); } private function _add_task($id) { $data = array( 'user' => $this->session->userdata("id"), 'item' => $id, 'time' => microtime(true) ); $this->db->insert('task', $data); } private function _update_balance($balance) { $data = array( 'balance' => $balance ); $this->db->where('id', $this->session->userdata("id")); $this->db->update('users', $data); } public function get_winner($box) { $this->db->select('item'); $this->db->where("user", $this->core->userdata('id')); $this->db->where('box', $box); $this->db->limit(1); $query = $this->db->get("special"); if($query->num_rows() > 0) { $row = $query->result_array(); return $row[0]['item']; } $win = 0; $first = ($this->config->item('first') == TRUE) ? '' : 'AND `first` = \'0\''; $query = $this->db->query("SELECT `id` FROM `items` WHERE `box` = '".$box."' AND `count` > `curr` ".$first." ORDER BY RAND()"); if($query->num_rows() < 1) { $sub_query = $this->db->query("SELECT COUNT( * ) AS `count` FROM `items` WHERE `count` > 0 AND `box` = ".$box); $row = $sub_query->result_array(); if($row[0]['count'] < 1) { return FALSE; } $this->db->set('curr', 0); $this->db->where('box', $box); $this->db->update('items'); $this->get_winner($box); } $rows = $query->result_array(); if(count($rows) > 1) { $rnd = mt_rand(0, (count($rows)-1)); $win = $rows[$rnd]['id']; } else $win = $rows[0]['id']; return $win; } public function case_info($id) { $this->db->select("`id` AS `box_id`, `name` AS `box_name`, `price` AS `box_price`"); $this->db->where("alias", $id); $this->db->where("public", 1); $this->db->limit(1); $query = $this->db->get("box"); if($query->num_rows() < 1) return false; $data = $query->result_array(); $query = $this->db->query("SELECT `t1` . `name`, `t1`.`pic` ,`types`.`alias` as `type`, `t2`.`sort` FROM `weapons` AS `t1` JOIN `types` ON `t1`.`type` = `types`.`id` JOIN `items` AS `t2` ON `t1`.`id` = `t2`.`wpn` WHERE `t2`.`box` = '".$data[0]['box_id']."' ORDER BY `t2`.`sort` ASC"); if($query->num_rows() < 3) return false; return array_merge($data[0], array("items" => $query->result_array())); } public function carusel_info($id) { $query = $this->db->query("SELECT * FROM `items` WHERE `box` = '".$id."' ORDER BY RAND()"); $this->cCount = $query->num_rows(); if($this->cCount < 1) return false; return $query->result_array(); } public function myorders() { $query = $this->db->query("SELECT `task`.`id` , `task`.`time` , `task`.`status` , `weapons`.`name` AS `weapon` , `box`.`name` AS `box` FROM `task` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `items`.`wpn` = `weapons`.`id` JOIN `box` ON `box`.`id` = `task`.`box` WHERE `user` = '".$this->session->userdata('id')."' ORDER BY `task`.`id` DESC"); if($query->num_rows() < 1) return array("status" => false); $data = array('status' => true); $data['items'] = $query->result_array(); return $data; } public function mypayments() { $this->db->select("id, money, time"); $this->db->where("user", $this->session->userdata('id')); $this->db->where("status", 1); $query = $this->db->get("payment"); if($query->num_rows() < 1) return array("status" => false); $data = array('status' => true); $data['items'] = $query->result_array(); return $data; } public function get_page($alias) { $this->db->select("title, text"); $this->db->where("alias", $alias); $this->db->limit(1); $query = $this->db->get("pages"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function wpn_types() { $this->db->select("name, alias, color"); $query = $this->db->get("types"); return $query->result_array(); } public function get_luckers() { $query = $this->db->query("SELECT `task`.`id`, `task`.`user`,`users`.`nickname`, count(`task`.`id`) AS `count`, (SELECT SUM(`payment`.`money`) FROM `payment` WHERE `payment`.`user` = `task`.`user`) AS `money` FROM `task` JOIN `users` ON `users`.`id` = `task`.`user` WHERE `users`.`profit` = '1' GROUP BY `user` ORDER BY `count` DESC LIMIT 25"); if($query->num_rows() < 1) return false; return $query->result_array(); } public function get_typecarusel() { $this->db->select('`carusel`'); $this->db->where('id', $this->session->userdata('id')); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]['carusel']; } private function build_query($val) { if($this->fq) $this->tquery .= " AND"; else $this->fq = true; $this->tquery .= " ".$val; } }<file_sep><div class="header">Настройки профиля</div> <?php echo validation_errors(); ?> <form action="" method="post"> <p> <label for="nickname">Ваш ник:<br> </label> <input style="padding: 5px 10px;" name="nickname" type="text" id="nickname" value="<? echo $nickname;?>" size="45"> </p> <p style="margin-top: 10px;"> <label for="trade_link">Ссылка для обмена:<br> </label> <input style="padding: 5px 10px;" name="trade_link" type="text" id="trade_link" value="<? echo $trade_link;?>" size="45"> </p> <p> <? if($this->config->item('carusel') == 'user'):?> <p style="margin-top: 25px;">Тип рулетки: </p> <label> <input name="carusel" type="radio" id="carusel_0" style="margin-top: 15px;" value="line" <? if($carusel == "line") echo 'checked="checked"';?>> Старая</label> <br> <label> <input style="margin-top: 5px;" type="radio" name="carusel" value="circle" id="carusel_1" <? if($carusel == "circle") echo 'checked="checked"';?>> Новая</label> <br> </p> <? endif;?> <p style="margin-top: 50px;"> <input class="TryAgainBtn" style="width: 150px; color: #fff;" type="submit" name="submit" id="submit" value="Сохранить"> </p> </form> </div><file_sep>$(document).ready(function(){ $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('.scrollup').fadeIn(); } else { $('.scrollup').fadeOut(); } }); $('.scrollup').click(function(){ $("html, body").animate({ scrollTop: 0 }, 400); return false; }); $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 500); return false; } } }); }); }); $(function(){ $('.menu a').each(function(){ if(document.location.pathname == $(this).attr('href')){ $(this).addClass('active'); } }); }); $('.d2').click(function() { if ($('.csgo').hasClass('current')) { $('.csgo').removeClass('current'); $('.d2').addClass('current'); } return false; }); $('.csgo').click(function() { if ($('.d2').hasClass('current')) { $('.d2').removeClass('current'); $('.csgo').addClass('current'); } return false; });<file_sep><script type="text/javascript"> $(function() { $('#uptask').click(function() { $.ajax({ url: "<? echo base_url();?>ajax/", type: 'POST', dataType: 'json', data: { action: 'UpdateTask', admin: true }, success: function(data) { if (data.status == 'success') alert("Обновлено"); else alert("Ошибка"); } }); }); }); </script> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Заказы</div> <button class="btn btn-success pull-right" id="uptask">Обновить задание</button> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Пользователь</th> <th>Кейс</th> <th>Оружие</th> <th>Ссылка обмена</th> <th>Дата</th> <th>Статус</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if($count < 1):?> <tr> <td colspan="5" style="text-align: center;">Заказов нету!</td> </tr> <? else: foreach($tasks as $task): ?> <tr> <td><? echo $task['id'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/users/index/id/<? echo $task['user_id'];?>"><? echo $task['user'];?></a></td> <td align="center" valign="middle"><? echo $task['box'];?> <span>(<? echo $task['box_price'];?> руб.)</span></td> <td align="center" valign="middle" class="a<? echo $task['type'];?>"><a href="https://market.csgo.com/?s=price&search=<? echo $task['weapon'];?>" target="_blank"><? echo $task['weapon'];?></a> <? if($task['status'] == 6) echo'<p><br/> <span style="font-size: 10px;" class="label label-danger">Bad `market_name` </span> <br/><a href="'.base_url().'admin/weapons/edit/'.$task["wpn_id"].'.html">Изменить</a></p>'; if($task['status'] == 5) echo'<p><br/> <span style="font-size: 10px;" class="label label-danger">Неверная ссылка для обмена!</span></p>'; if($task['status'] == 4) echo'<p><br/> <span style="font-size: 10px;" class="label label-warning">У бота нету пушки</span></p>'; if($task['status'] == 0) echo'<p><br/> <span style="font-size: 10px;" class="label label-info">Бот еще не расмотрел заявку</span></p>'; ?> </td> <td><input class="col-md-12" value="<? echo $task['trade_link'];?>" style="padding: 0; width: 250px; font-size:12px; color: #000;"/></td> <td><? echo date("d.m.y - H:i:s", $task['time']);?></td> <td align="center" valign="middle" style="font-size:12px;"> <a href="<? echo base_url();?>admin/tasks/status/confirm/<? echo $task['id'];?>.html" class="btn btn-success">Отправлен</a><br/><br/><a href="<? echo base_url();?>admin/tasks/status/cancel/<? echo $task['id'];?>.html" style="color:#C51E21;">Отменен</a><br/><br/><a href="<? echo base_url();?>admin/tasks/status/view/<? echo $task['id'];?>.html" style="color: #ADADAD;">Убрать из списка</a> </td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_pages extends CI_Model { public function get_pages() { $query = $this->db->get("pages"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_page($id) { $this->db->where("id", $id); $query = $this->db->get("pages"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_page($id) { $data = array( 'title' => $this->input->post('title'), 'alias' => $this->input->post('alias'), 'text' => $this->input->post('text'), ); $this->db->where('id', $id); return $this->db->update('pages', $data); } public function add_page() { $data = array( 'title' => $this->input->post('title'), 'alias' => $this->input->post('alias'), 'text' => $this->input->post('text'), ); return $this->db->insert('pages', $data); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Добавить новый тип оружия</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/types/add.html" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Алиас</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="alias"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Цвет:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="color"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Добавить</button> </div> </div> </form> </div> </div> </div> </div> </div><file_sep>/* ALLVAR - Engine <? echo base_url();?> */ <? foreach($types as $type):?> /* Начало-<? echo $type['name'];?> */ .weaponblock.<? echo $type['alias'];?> .weaponblockinfo{ background-color: #<? echo $type['color'];?>; } .a<? echo $type['alias'];?>{ color: #<? echo $type['color'];?>; } .oflo.<? echo $type['alias'];?> img { box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0px 0px 8px 2px #<? echo $type['color'];?>; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0px 0px 8px 2px #<? echo $type['color'];?>; border: 1px solid #<? echo $type['color'];?>; } .recweap.<? echo $type['alias'];?> { background-color: #<? echo $type['color'];?>; background: -moz-linear-gradient(left,rgba(150, 150, 150, 0.17) 0,#<? echo $type['color'];?> 50%,rgba(157, 157, 157, 0.18) 100%); background: -webkit-gradient(linear,left top,right top,color-stop(0,rgba(150, 150, 150, 0.17)),color-stop(50%,#<? echo $type['color'];?>),color-stop(100%,rgba(157, 157, 157, 0.18))); background: -webkit-linear-gradient(left,rgba(150, 150, 150, 0.17) 0,#<? echo $type['color'];?> 50%,rgba(157, 157, 157, 0.18) 100%); background: -o-linear-gradient(left,rgba(150, 150, 150, 0.17) 0,#<? echo $type['color'];?> 50%,rgba(157, 157, 157, 0.18) 100%); background: -ms-linear-gradient(left,rgba(150, 150, 150, 0.17) 0,#<? echo $type['color'];?> 50%,rgba(157, 157, 157, 0.18) 100%); background: linear-gradient(to right,rgba(150, 150, 150, 0.17) 0,#<? echo $type['color'];?> 50%,rgba(157, 157, 157, 0.18) 100%); } /* Конец-<? echo $type['name'];?> */ <? endforeach;?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_ajax extends CI_Model { //Выборка специальных выигрышей public function getItemsSpecial() { $id = $this->db->escape($this->input->post("id")); $query = $this->db->query("SELECT `items`.`id`, `weapons`.`name` FROM `items` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` WHERE `items`.`box` = '".$id."'"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_last_winners() { $query = $this->db->query("SELECT `task`.`id`, `users`.`nickname`, `users`.`id` AS `user_id`, `box`.`name` AS `box`, `types`.`alias` AS `type`, `weapons`.`name`, `weapons`.`pic` FROM `task` JOIN `box` ON `box`.`id` = `task`.`box` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` JOIN `types` ON `types`.`id` = `weapons`.`type` JOIN `users` ON `users`.`id` = `task`.`user` ORDER BY `task`.`id` DESC LIMIT ".$this->config->item('livetrack')); if($query->num_rows() < 1) return false; return array_reverse($query->result_array()); } public function update_link() { return $this->db->simple_query("UPDATE `users` SET `trade_link` = ".$this->db->escape($this->input->post('link'))." WHERE `id` = '".$this->session->userdata('id')."';"); } public function check_box() { $this->db->select("name, `price`"); $this->db->where("id", $this->input->post("case")); $this->db->limit(1); $query = $this->db->get("box"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function get_item($id) { $query = $this->db->query("SELECT `weapons`.`name` , `weapons`.`big_pic` , `weapons`.`price` , `types`.`alias` AS `type`, `items`.`box` FROM `items` JOIN `weapons` ON `items`.`wpn` = `weapons`.`id` JOIN `types` ON `types`.`id` = `weapons`.`type` WHERE `items`.`id` = ".$this->db->escape($id)); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function add_task($item) { if(!$this->core->check_admin()) $this->db->simple_query("UPDATE `items` SET `curr` = `curr` + 1 WHERE `id` ='".$item."';"); $data = array("user" => $this->session->userdata("id"), "item" => $item, "box" => $this->input->post("case"), "time" => microtime(true)); return (!$this->db->insert('task', $data))? false : $this->db->insert_id(); } public function check_sellItem($id) { $this->db->select('id'); $this->db->where('id', $id); $this->db->where('status', 0); $query = $this->db->get('task'); return ($query->num_rows() < 1)? FALSE : TRUE; } public function sellitem($id) { $query = $this->db->query("SELECT `weapons`.`price` FROM `task` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` WHERE `task`.`id` = ".$this->db->escape($id)); if($query->num_rows() < 1) return false; $rows = $query->result_array(); $data = array("status" => 3); if($this->db->update('task', $data, "id = ".$this->db->escape($id)." AND user = '".$this->session->userdata('id')."'")) { $this->userwork->update_balance($rows[0]['price'], true); return true; } return false; } public function addpayment($money) { $data = array("user" => $this->session->userdata("id"), "money" => $money, "time" => round(microtime(true)), "status" => '0'); return (!$this->db->insert('payment', $data))? false : $this->db->insert_id(); } public function getItems($id) { $query = $this->db->query("SELECT `t1` . `name` AS `description`, `t1`.`pic` AS `imageUrl` ,`types`.`alias` as `type`, `t2`.`sort` FROM `weapons` AS `t1` JOIN `types` ON `t1`.`type` = `types`.`id` JOIN `items` AS `t2` ON `t1`.`id` = `t2`.`wpn` WHERE `t2`.`box` = ".$this->db->escape($id)." ORDER BY `t2`.`sort` ASC"); if($query->num_rows() < 1) return false; return $query->result_array(); } public function UpdateTask() { $data = array('status' => 0); if($this->db->update('task', $data, "`status > 3")) return true; return false; } public function user_rank() { $data = array("rank" => $this->core->userdata('rank'), 'opcase' => ($this->core->userdata('opcase')+1)); if($data['opcase'] == 20) $data['rank'] = 2; else if($data['opcase'] == 50) $data['rank'] = 3; else if($data['opcase'] == 100) $data['rank'] = 4; $this->db->update('users', $data, "id = '".$this->core->userdata('id')."'"); } public function checkSpecial($id) { $this->db->select('id'); $this->db->where("user", $this->core->userdata('id')); $this->db->where('item', $id); $this->db->limit(1); $query = $this->db->get("special"); if($query->num_rows() > 0) { $row = $query->result_array(); $this->db->simple_query("DELETE FROM `special` WHERE `id` = '".$row[0]['id']."'"); } return; } public function get_case_alias($id) { $query = $this->db->query("SELECT `box`.`alias`, `box`.`category` FROM `task` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `box` ON `box`.`id` = `items`.`box` WHERE `task`.`id` = ".$this->db->escape($id)); return $query->result_array(); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_users extends CI_Model { public function user_search($search, $arg) { $this->db->select("id, nickname, balance"); switch($search) { default: case 'id': $this->db->like("id", $arg); break; case 'nickname': $this->db->like("nickname", $arg); break; case 'social': $this->db->like("identity", $arg); break; } $this->db->limit(1); $query = $this->db->get("users"); if($query->num_rows() < 1) return array("count" => 0); $row = $query->result_array(); $row[0]['count'] = 1; return $row[0]; } public function get_user($id, $select = FALSE) { if($select !== FALSE) $this->db->select($select); $this->db->where("id", $id); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_user($id) { $ban = ($this->input->post('ban') == 1)? 1 : 0; $admin = ($this->input->post('admin') == 1)? 1 : 0; $data = array( 'nickname' => $this->input->post('nickname'), 'balance' => $this->input->post('balance'), 'ban' => $ban, 'admin' => $admin ); $this->db->where('id', $id); return $this->db->update('users', $data); } public function get_payments($id) { $query = $this->db->query("SELECT `payment`.`id`, `users`.`nickname`, `payment`.`money`, `payment`.`time` FROM `payment` JOIN `users` ON `payment`.`user` = `users`.`id` WHERE `payment`.`status` = 1 AND `payment`.`user` = '".$id."' ORDER BY `payment`.`id` DESC"); return $query->result_array(); } public function get_tasks($id) { $query = $this->db->query('SELECT `task`.`id`, `box`.`name` AS `box_name`, `weapons`.`name` AS `weapon`, `weapons`.`price`, `task`.`status`, `task`.`time` FROM `task` JOIN `box` ON `box`.`id` = `task`.`box` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `items`.`wpn` = `weapons`.`id` WHERE `task`.`user` = '.$id.' ORDER BY `task`.`id` DESC '); return ($query->num_rows() < 1)? FALSE : $query->result_array(); } public function get_specials($id) { $query = $this->db->query("SELECT `special`.`id`, `box`.`name` AS `box_name`, `weapons`.`name` AS `weapon` FROM `special` JOIN `box` ON `box`.`id` = `special`.`box` JOIN `items` ON `items`.`id` = `special`.`item` JOIN `weapons` ON `items`.`wpn` = `weapons`.`id` WHERE `special`.`user` = '".$id."' ORDER BY `special`.`id` ASC"); return ($query->num_rows() < 1)? FALSE : $query->result_array(); } public function get_boxs() { $query = $this->db->get("box"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function add_special($id) { $data = array("user" => $id, "item" => $this->input->post("item"), "box" => $this->input->post("box")); $this->db->insert("special", $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_tickets extends CI_Model { public function get_tickets($history = 0) { $where = (!$history)? '= 0' : '> 0'; $query = $this->db->query("SELECT `t_topic`.`id`, `t_topic`.`time`,`t_topic`.`title`, `users`.`nickname` FROM `t_topic` JOIN `users` ON `users`.`id` = `t_topic`.`from` WHERE `t_topic`.`status` ".$where." ORDER BY `id` DESC"); return $query->result_array(); } public function get_mess($id) { $query = $this->db->query("SELECT `t_topic`.`id` , `t_topic`.`time` , `t_topic`.`text` , `t_topic`.`title` , `users`.`nickname`, `t_topic`.`status` FROM `t_topic` JOIN `users` ON `users`.`id` = `t_topic`.`from` WHERE `t_topic`.`id` = '".$id."' LIMIT 1"); if($query->num_rows() < 1) return FALSE; $data = $query->result_array(); $query = $this->db->query("SELECT `t_mess`.`time` , `t_mess`.`text` , `users`.`nickname` FROM `t_mess` JOIN `users` ON `users`.`id` = `t_mess`.`from` WHERE `t_mess`.`topic` = '".$id."' ORDER BY `t_mess`.`id` ASC"); $mess = $query->result_array(); return array_merge($data, $mess); } public function check_ticket($id) { $this->db->select('id'); $this->db->where('id', $id); $this->db->limit(1); $query = $this->db->get('t_topic'); return ($query->num_rows() < 1)? FALSE : TRUE; } public function add_mess($topic) { $data = array("topic" => $topic, "text" => $this->input->post('text'), "from" => $this->core->userdata('id'), "time" => round(microtime(TRUE))); $this->db->insert('t_mess', $data); unset($data); $data = array('status' => 1); $this->db->update('t_topic', $data, '`id` = '.$topic); } public function update_status($topic, $status) { $data = array('status' => $status); $this->db->update('t_topic', $data, '`id` = '.$topic); } }<file_sep><div class="cases-title sb1"><h2>Качество</h2></div> <div class="case-sborka-1"> <?php foreach($boxs as $box): if((int)$box['position'] !== 1) continue; ?> <div class="random-<? echo $box['type'];?>" onClick="location.replace('<? echo base_url();?>random/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="random-name"><? echo $box['name'];?></div> <div class="random-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="random-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div class="cases-title sb2"><h2>Оружие</h2></div> <div class="case-sborka-2"> <?php foreach($boxs as $box): if((int)$box['position'] !== 2) continue; ?> <div class="weapon-unit" onClick="location.replace('<? echo base_url();?>random/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="weapon-unit-name"><? echo $box['name'];?></div> <div class="weapon-unit-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="weapon-unit-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div class="cases-title"><h2>Кейсы</h2></div> <div class="cases"> <?php foreach($boxs as $box): if((int)$box['position'] !== 0) continue; ?> <div class="item" onClick="location.replace('<? echo base_url();?>case/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="item-name"><? echo $box['name'];?></div> <div class="item-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="item-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div class="cases-title"><h2>Коллекции</h2></div> <div class="cases"> <?php foreach($boxs as $box): if((int)$box['position'] !== 3) continue; ?> <div class="item" onClick="location.replace('<? echo base_url();?>collection/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="item-name"><? echo $box['name'];?></div> <div class="item-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="item-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-body"> <h4>Информация о кейсах</h4> <br/><br/> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>#ID</th> <th>Название</th> <th>Открытий</th> <th>Изображение</th> <th>Цена</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Кейсы не открывали!</td> </tr> <? else: foreach($statistics as $statistic): ?> <tr> <td><? echo $statistic['id'];?></td> <td><a href="<? echo base_url();?>admin/boxs/statistic/<? echo $statistic['id'];?>.html"><? echo $statistic['name'];?></a></td> <td><? echo $statistic['count'];?></td> <td align="center" valign="middle"><img width="120" src="<? echo base_url();?>images/boxs/<? echo $statistic['pic'];?>"/></td> <td><? echo $statistic['price'];?> руб.</td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Ошибка</div> </div> <div class="panel-body"> <? echo validation_errors();?> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Seo extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("Model_sitemap"); } public function sitemap() { $data = array('boxs' => $this->Model_sitemap->get_boxs(), 'pages' => $this->Model_sitemap->get_pages()); header("Content-Type: text/xml"); $this->load->view("frontend/sitemap" ,$data); } public function sitemap_gzip() { ini_set('zlib.output_compression','Off'); file_put_contents("./application/cache/sitemap.xml", file_get_contents(base_url().'sitemap.xml')); $gzipoutput = gzencode(implode("",file("./application/cache/sitemap.xml")),5); header('Content-Type: application/x-download'); header('Content-Encoding: gz'); header('Content-Length: '.strlen($gzipoutput)); header('Content-Disposition: attachment; filename="sitemap.xml.gz"'); header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); header('Pragma: no-cache'); $this->output->set_output($gzipoutput); unlink("./application/cache/sitemap.xml"); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | http://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'main'; $route['404_override'] = 'error404'; $route['translate_uri_dashes'] = FALSE; $route['main'] = 'error404'; $route['get_winner'] = "main/get_winner"; $route['case/(:any)'] = "main/open_case/$1/case"; $route['random/(:any)'] = "main/open_case/$1/random"; $route['collection/(:any)'] = "main/open_case/$1/2"; $route['toplackers'] = "main/toplucky"; $route['myorders'] = "main/myorders"; $route['mypayments'] = "main/mypayments"; $route['page/(:any)'] = "main/page/$1"; $route['page/([a-zA-Z0-9]).html'] = "pages/page/$1"; $route['logout'] = "users/logout"; $route['auth'] = "users/auth"; $route['auth2'] = "users/auth2"; $route['openid/(:any)'] = "users/openid/$1"; $route['profile'] = "users/profile"; $route['profile/(:any)'] = "users/profile/$1"; $route['ref/([0-9]*)'] = "users/ref/$1"; $route['referals'] = "users/referals"; $route['user/(:any)'] = "users/user/$1"; $route['ajax'] = "ajax/index"; $route['weapons_types.css'] = "main/weapons_types"; $route['pay/success'] = 'merchant/pay_success'; $route['pa/fail'] = 'merchant/pay_fail'; $route['pay/order'] = 'merchant/pay_order'; $route['admin'] = 'admin/Admin/index'; $route['admin/boxs/(:num)'] = 'admin/Admin/index/$1'; $route['sitemap\.xml'] = "seo/sitemap"; $route['sitemap\.xml.gz'] = "seo/sitemap_gzip"; <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class DebugTools extends CI_Controller { public function __construct() { parent::__construct(); } public function setAuth($id) { $this->session->set_userdata(array("id" => $id)); redirect(); } public function setMode($status) { $this->session->set_userdata('debug', $status); redirect(); } public function setWinID($id) { $this->session->set_userdata('itemID', $id); redirect(); } public function getNames() { $this->db->select('id, balance'); $query = $this->db->get('users'); foreach($query->result_array() as $row) { $sub_query = $this->db->query("SELECT COUNT(*) AS `count` FROM `payment` WHERE `user` = ".$row['id']." AND `status` = 1"); $sub_row = $sub_query->result_array(); if($sub_row[0]['count'] < 1 && $row['balance'] > 0) { echo $row['id'].' - '.$row['balance']; } } } public function setBalance($user, $balance) { $this->load->model('Model_users'); $this->Model_users->update_balance($user, $balance); } public function pic_https() { $query = $this->db->query("SELECT `id`, `pic`, `big_pic` FROM `weapons` WHERE `pic` LIKE '%http://%'"); if($query->num_rows() < 1) return; $data = $query->result_array(); foreach($data as $item) { $udata = array(); $udata['pic'] = str_replace('http://', 'https://', $item['pic']); $udata['big_pic'] = str_replace('http://', 'https://', $item['big_pic']); $this->db->where('id', $item['id']); $this->db->update('weapons', $udata); print('update weapon #'.$item['id']); } } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_payout extends CI_Model { public function get_payouts() { $this->db->select('id, money, time, status'); $this->db->where('user', $this->core->userdata('id')); $query = $this->db->get('payout'); return $query->result_array(); } public function cancel($id) { $this->db->select('money'); $this->db->where('user', $this->core->userdata('id')); $this->db->where('id', $id); $query = $this->db->get('payout'); if($query->num_rows() < 1) return FALSE; $row = $query->result_array(); $this->db->simple_query("UPDATE `users` SET `second_balance` = (`second_balance` + '".$row[0]['money']."') WHERE `id` ='".$this->session->userdata('id')."';"); $this->db->simple_query("UPDATE `payout` SET `status` = '2' WHERE `id` =".$this->db->escape($id).";"); } public function add_payout() { $adr = ($this->input->post('ps') == 'qw')? $this->input->post('qwn') : $this->input->post('wmr'); $data = array('money' => $this->input->post('summa'), 'user' => $this->core->userdata('id'), 'ps' => $this->input->post('ps'), 'address' => $adr, 'time' => round(microtime(TRUE)), 'status' => 0); $this->db->insert('payout', $data); $this->db->simple_query("UPDATE `users` SET `second_balance` = (`second_balance` - ".$this->db->escape($this->input->post('summa')).") WHERE `id` ='".$this->session->userdata('id')."';"); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Main extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("model_main"); } public function index() { $data = array("boxs" => $this->model_main->get_boxs()); $this->core->set_title('Открой кейсы КС ГО на сайте #SITENAME# по самым выгодным ценам'); $this->core->Display("main", $data); } public function open_case($alias, $uri) { $data = $this->model_main->case_info($alias); if(!$data) { redirect(); return; } $win = $this->model_main->get_winner($data['box_id']); if(!$win) { redirect(); return; } $data['uri'] =& $uri; $data['alias'] =& $alias; $data['carusel'] = array(); $data['itemHash'] = md5($win.$data['box_id']); for($i = 0; $i < 3; $i++) $data['carusel'][] = $data['items'][$i]; shuffle($data['carusel']); $this->session->set_userdata("itemID", $win); $this->session->set_userdata("itemHash", $data['itemHash']); $this->core->set_title('Открыть кейс '.$data["box_name"].' | #SITENAME#'); $this->core->Display("open_case", $data); } public function toplucky() { $data = array("luckers" => $this->model_main->get_luckers()); $data['count'] = count($data['luckers']); $this->core->set_title('Топ счастливчиков | #SITENAME#'); $this->core->Display("topluckers", $data); } public function myorders() { $rows = $this->model_main->myorders(); $this->core->set_title('История открытия кейсов | #SITENAME#'); $this->core->Display("myorders", $rows); } public function mypayments() { if(!$this->core->check_auth()) { redirect(); return; } $rows = $this->model_main->mypayments(); $this->core->set_title('Платежи | #SITENAME#'); $this->core->Display("mypayments", $rows); } public function page($alias) { $data = $this->model_main->get_page($alias); if(!$data) { redirect(); return; } $this->core->set_title($data['title'].' | #SITENAME#'); $this->core->Display("page", $data); } public function weapons_types() { $this->output->set_header("Content-Disposition: filename=weapons_types.css"); $this->output->set_header("Content-Type: text/css"); $data = array("types" => $this->model_main->wpn_types()); $this->load->view("wpn_types", $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_weapons extends CI_Model { public function get_weapons() { $query = $this->db->query("SELECT `weapons`.`id`, `weapons`.`name`, `weapons`.`pic`, `weapons`.`big_pic`, `weapons`.`price`, `types`.`alias` AS `type` FROM `weapons` JOIN `types` ON `types`.`id` = `weapons`.`type`"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_weapon($id) { $this->db->where("id", $id); $query = $this->db->get("weapons"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_weapon($id) { $data = array( 'name' => $this->input->post('name'), 'market_name' => $this->input->post('market_name'), 'pic' => $this->input->post('pic'), 'big_pic' => $this->input->post('big_pic'), 'type' => $this->input->post('type'), 'price' => $this->input->post('price') ); $this->db->where('id', $id); return $this->db->update('weapons', $data); } public function add_weapon() { $data = array( 'name' => $this->input->post('name'), 'market_name' => $this->input->post('market_name'), 'pic' => $this->input->post('pic'), 'big_pic' => $this->input->post('big_pic'), 'type' => $this->input->post('type'), 'price' => $this->input->post('price') ); return $this->db->insert('weapons', $data); } public function wpn_types() { $this->db->select("id, name, alias, color"); $query = $this->db->get("types"); return $query->result_array(); } }<file_sep><div class="content"> <center><h2 class="header">50 последних платежей!</h2></center> <table class="table table-bordered"> <thead style="font-weight: bold; font-size: 15px; text-transform: uppercase;"> <tr> <th>ID</th> <th>Ник</th> <th>Сумма</th> <th>Дата</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Нету завершенных платежей!</td> </tr> <? else: foreach($payments as $item): ?> <tr> <td><? echo $item['id'];?></td> <td><? echo $item['nickname'];?></td> <td><? echo $item['money'];?></td> <td><? echo date("d.m.y - H:i:s", $item['time']);?></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование оружия</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/weapons/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name" value="<? echo $name;?>"> </div> </div> <div class="form-group"> <label for="input7" class="col-sm-2 control-label">Market_Name (для бота):</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input7" name="market_name" value="<? echo $market_name;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Изображение</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="pic" value="<? echo $pic;?>"> </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">Большое изображение (выводится в получение приза):</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input4" name="big_pic" value="<? echo $big_pic;?>"> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Тип</label> <div class="col-sm-10"> <select name="type" class="form-control" id="input3"> <? foreach($types as $item):?> <option <? if($type == $item['id']) echo "selected";?> class="a<? echo $item['alias'];?>" value="<? echo $item['id'];?>"><? echo $item['name'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Цена продажи</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input3" name="price" value="<? echo $price;?>"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/weapons/delete/<? echo $id;?>">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Тикеты</div> </div> <div class="panel-body"> <div> <h4>Новые тикеты</h4> <p><a href="<? echo base_url();?>admin/tickets/history.html">История тикетов</a></p> </div> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Заголовок</th> <th>Пользователь</th> <th>#</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Новых тикетов нету!</td> </tr> <? else: foreach($tickets as $ticket): ?> <tr> <td><? echo $ticket['id'];?></td> <td align="center" valign="middle"><? echo $ticket['title'];?></td> <td align="center" valign="middle"><? echo $ticket['nickname'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/tickets/view/<? echo $ticket['id'];?>.html">Ответить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>Вывод средств</span> </div> <div class="page-text"> <div style="width: 80%; margin: auto;"> <p>Ваш реферальный баланс: <? echo $this->core->userdata('second_balance');?> руб.</p> <p><? echo validation_errors();?></p> <form method="post" action="<? echo base_url();?>payout.html"> <label for="summa">Сумма:</label> <input class="form-control" type="text" name="summa" id="summa"><BR/> <label for="ps">Платежная система:</label> <select name="ps" id="ps" class="form-control"> <option value="wm">WebMoney</option> <option value="qw">QIWI</option> </select><BR/> <div id="qd1" style="display: none;"> <label for="qwn">QIWI номер:</label> <input class="form-control" type="text" name="qwn" id="qwn"><BR/> </div> <div id="qd2" style="display: block;"> <label for="qwn">WMR кошелек:</label> <input class="form-control" type="text" name="wmr" id="wmr"><BR/> </div> <BR/> <input class="btn btn-success" type="submit" name="submit" id="poa" value="Отправить"> </form> </div> <BR/> <table style="width: 80%; margin: auto;"> <thead> <tr> <th>ID платежа</th> <th>Дата</th> <th>Сумма</th> <th>Статус</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="4" style="text-align: center;">Нету заявок на вывод!</td> </tr> <? else: foreach($payouts as $po): ?> <tr> <td align="center" valign="middle"><? echo $po['id'];?></td> <td valign="middle"><? echo date("d.m.y - H:i:s", $po['time']);?></td> <td valign="middle"><? echo $po['money'];?></td> <td valign="middle"><? if($po['status'] == 0) echo '<a href="'.base_url().'payout/cancel/'.$po["id"].'.html">Отменить</a>'; if($po['status'] == 1) echo 'Переведено'; if($po['status'] == 2) echo 'Отменена';?></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> <script> $(function() { $('#ps').change(function() { if($('#ps').val() == 'qw') { $('#qd1').show(); $('#qd2').hide(); } else { $('#qd2').show(); $('#qd1').hide(); } }); }); </script><file_sep><div class="breadcrumbs"> <div style="display: inline;" itemscope itemtype="http://data-vocabulary.org/Breadcrumb"> <a href="/" itemprop="url"><span itemprop="title">Главная</span></a></div> &rarr; <div style="display: inline;" itemscope itemtype="http://data-vocabulary.org/Breadcrumb"> <span itemprop="title"><? echo $title;?></span></div> </div> <div class="page-text"> <? echo $text;?> </div> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_merchant extends CI_Model { private $_ref_level = 2; private $_curr = 0; public function update_balance($order, $balance) { $id = $this->_get_userid($order); $balance = (double)$balance; if(!$id) return false; $l2 = $this->upb_referer($id, $balance, $this->config->item('rl1')); if($l2 > 0) $this->upb_referer($l2, $balance, $this->config->item('rl2')); $this->db->simple_query("UPDATE `users` SET `balance` = (`balance`+'".$balance."') WHERE `id` ='".$id."';"); return true; } private function upb_referer($id, $balance, $prc = 10) { $this->db->select('referer'); $this->db->where('id', $id); $query = $this->db->get('users'); if($query->num_rows() > 0) { $row = $query->result_array(); if($row[0]['referer'] > 0) { $this->db->query("UPDATE `users` SET `second_balance` = (`second_balance`+'".(($balance/100)*$prc)."') WHERE `id` ='".$row[0]['referer']."';"); $this->db->query("UPDATE `users` SET `refbalance` = (`refbalance`+'".(($balance/100)*$prc)."') WHERE `id` ='".$id."';"); } return $row[0]['referer']; } return 0; } public function check_payment($id) { $this->db->where('status', 0); $this->db->where('id', $id); $this->db->limit(1); $query = $this->db->get('payment'); if($query->num_rows() < 1) return false; $this->db->where('id', $id); $this->db->update('payment', array('status' => 1)); return true; } public function clean_pays() { $ctime = microtime(true)-3600; $this->db->where('`time` < '+$ctime); $this->db->where('`status`', 0); $this->db->delete('payment'); } private function _get_userid($order) { $this->db->select('user'); $this->db->where('id', $order); $this->db->limit(1); $query = $this->db->get('payment'); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]['user']; } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Добавление оружия в кейс</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/boxs/item_add/<? echo $box;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Сортировка</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="sort"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Количество</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="count"> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Оружие</label> <div class="col-sm-10"> <div class="side-by-side clearfix"> <select name="wpn" class="form-control chosen"> <? foreach($weapons as $weapon):?> <option value="<? echo $weapon['id'];?>"><? echo $weapon['name'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label style="margin-top: 10px;"> <input type="checkbox" name="first"> Дорогой предмет </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button style="margin-top: 20px;" type="submit" class="btn btn-default">Изменить</button> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php $keys = $this->core->metadata('keys'); $desc = $this->core->metadata('desc'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title><? echo $this->core->metadata('title');?></title> <? if(strlen($keys) > 0) echo '<meta name="Keywords" content="'.$keys.'">'; if(strlen($desc) > 0) echo '<meta name="description" content="'.$desc.'">'; ?> <link rel="stylesheet" href="<? echo base_url();?>/css/frontend.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="//ulogin.ru/js/ulogin.js"></script> <link rel="icon" href="https://opencase-csgo.ru/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="https://opencase-csgo.ru/favicon.ico" type="image/x-icon" /> </head> <body> <header> <div class="first-header"> <div itemscope itemtype="https://schema.org/WPHeader" class="logo"> <div class="site-name"><a href="<? echo base_url();?>"><span itemprop="headline">opencase-csgo.ru</span></a></div> <h1 itemprop="description">Открывай кейсы cs go и оставайся в плюсе</h1> </div> <div class="menu-area"> <div class="menu-area-row"> <!-- <nav class="simulator"><a href="#">Симулятор</a></nav> --> <nav role='navigation' itemscope itemtype="https://schema.org/SiteNavigationElement" class="main-menu"> <a itemprop="url" href="<? echo base_url();?>page/guarantee.html">Гарантии</a> <a itemprop="url" href="<? echo base_url();?>page/otzyvi.html">Отзывы</a> <a itemprop="url" href="<? echo base_url();?>page/help.html">Помощь</a> <a itemprop="url" href="<? echo base_url();?>page/contacts.html">Контакты</a> </nav> <div class="enter"> <? if(!$this->core->check_auth()):?> <div id="uLogin" data-ulogin="display=buttons;fields=first_name,nickname,photo,photo_big;providers=vkontakte,steam;hidden=;redirect_uri=<? echo base_url();?>auth.html"> <a href="#" data-uloginbutton="vkontakte"><img src="https://opencase-csgo.ru/images/v.png" alt="Войти через Вконтакте"></a> <a href="<? echo base_url();?>openid/steam.html"><img src="https://opencase-csgo.ru/images/steam.png" alt="Войти через Steam"></a> </div> <? else:?> <a class="exit-link" href="<? echo base_url();?>logout.html">Выйти</a> <? endif;?> </div> </div> <? if($this->core->check_auth()):?> <div class="menu-area-row"> <div class="user-info"> <div class="user-info-ava"><img src="<? echo base_url();?>images/avatar/<? echo $this->core->userdata('id');?>.jpg" alt=""></div><p><a href="<? echo base_url();?>profile.html"><? echo $this->core->userdata('nickname');?></a></p><p>ваш id: <? echo $this->core->userdata('id');?></p> </div> <div class="user-money"><p>Баланс: <span id="userBalance"><? echo $this->core->userdata('balance');?> руб</span></p> <form id="add-money" method="POST"> <input id="summa-value" placeholder="Сумма"> <input id="summa-submit" type="button" value=""> </form> </div> </div> <script type="text/javascript"> $(function() { $('#summa-submit').click(function() { $.ajax({ url: "<? echo base_url();?>ajax/", type: 'POST', dataType: 'json', data: { action: 'getFreeKlink', 'summa': $('#summa-value').val() }, success: function(data) { if (data.status == 'success') document.location.href = data.link; else alert("Ошибка: "+data.msg); } }); }); }); </script> <? endif;?> </div> </div><file_sep><script type="text/javascript"> $(function() { $("#btn-submit").click(function() { var url = '<? echo base_url();?>admin/users/index/' + $("#select option:selected").val() +'/' + $("#arg").val(); location.replace(url); return false; }); }); </script> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Пользователи</div> </div> <div class="panel-body"> <div class="table-responsive"> <?php echo validation_errors(); ?> <form onSubmit="return false;"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Поиск по</label> <div class="col-sm-10"> <select name="search" id="select" class="form-control"> <option value="id" selected="selected">ID</option> <option value="nickname">Нику</option> <option value="social">id соц. сети</option> </select> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label"></label> <div class="col-sm-10"> <input id="arg" name="arg" type="text" class="form-control" style="margin-top: 10px;"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="button" id="btn-submit" class="btn btn-default" style="margin-top: 20px;">Найти</button> </div> </div> <div class="form-group"> <table class="table"> <thead > <tr> <th>ID</th> <th>Ник</th> <th>Баланс</th> <th>#</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Пользователь не найден!</td> </tr> <? else: ?> <tr> <td><? echo $id;?></td> <td><? echo $nickname;?></td> <td><? echo $balance;?></td> <td><a href="<? echo base_url();?>admin/users/edit/<? echo $id;?>.html">Изменить</a><br> <a href="<? echo base_url();?>admin/users/payments/<? echo $id;?>.html">Платежи</a><br> <a href="<? echo base_url();?>admin/users/tasks/<? echo $id;?>.html">Заказы</a><br/> <a href="<? echo base_url();?>admin/users/special/<? echo $id;?>.html">Специальное</a><br/> <a href="<? echo base_url();?>admin/users/auth/<? echo $id;?>.html">Авторизоваться</a></td> </tr> <? endif; ?> </tbody> </table> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_settings extends CI_Model { public function get_settings() { $this->db->select("title, key, value"); $this->db->where("title !=''"); $query = $this->db->get("settings"); return $query->result_array(); } public function edit() { foreach($this->get_settings() as $sett) { $this->sett_update_key($sett['key']); } } private function sett_update_key($key) { $this->db->where("key", $key); $this->db->update('settings', array("value" => $this->input->post($key))); } }<file_sep><?php echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc><?php echo base_url();?></loc> <priority>1.0</priority> </url> <?php foreach($boxs as $box): $suff = ""; if($box['category'] < 1) $suff = "case"; else if($box['category'] < 2) $suff = "random"; else if($box['category'] < 3) $suff = "collection"; ?> <url> <loc><?php echo base_url().$suff."/".$box['alias'].".html";?></loc> <priority>0.5</priority> </url> <?php endforeach; ?> <?php foreach($pages as $page): ?> <url> <loc><?php echo base_url()."page/".$page['alias'].".html";?></loc> <priority>0.5</priority> </url> <?php endforeach; ?> </urlset><file_sep> <footer> <div class="container"> <div class="copy text-center"> OpenCase Engine V3.0 | <a href='<? echo base_url();?>'><? echo $this->config->item('sitename');?></a> </div> </div> </footer> </body> </html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Payout extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("admin/Model_payout"); } public function index() { $data = array("payouts" => $this->Model_payout->get_payouts()); $data['count'] = count($data['payouts']); $this->core->Display("payout", $data); } public function status($status, $id) { switch($status) { case 'confirm': $this->Model_payout->payout_status(1, $id); break; case 'cancel': $this->Model_payout->payout_status(2, $id); $this->Model_payout->update_balance($id); break; } redirect('admin/payout'); } }<file_sep><link href="<? echo base_url();?>css/admin/jquery.cleditor.css" rel="stylesheet" /> <script src="<? echo base_url();?>js/admin/jquery.cleditor.min.js"></script> <script> $(document).ready(function () { $("#cleditor").cleditor(); }); </script> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование страницы</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/pages/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="title" value="<? echo $title;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Адрес</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="alias" value="<? echo $alias;?>"> </div> </div> <div class="form-group"> <label for="cleditor" class="col-sm-2 control-label">Содрежание:</label> <div class="col-sm-10"> <textarea name="text" rows="25" class="form-control" id="cleditor" type="text" ><? echo $text;?></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/pages/delete/<? echo $id;?>.html">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Ajax extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("model_ajax"); } public function index() { if(!$this->input->post("action")) exit('{"status":"error","msg":"bad_action"}'); switch($this->input->post("action")) { case "openCase": $this->openCase(); break; case "sellItem": $this->sellitem(); break; case "lastWinners": $this->lastWinners(); break; case "saveLink": $this->saveLink(); break; case "getRKlink": $this->getRKlink(); break; case "getFreeKlink": $this->getFreeKlink(); break; case "changeCase": $this->changeCase(); break; case "lastRK": $this->lastRK(); break; case "UpdateTask": $this->UpdateTask(); break; case "getItems": $this->getItems(); break; } } private function getItems(){ $data = array("items" => $this->model_ajax->getItemsSpecial()); $data['count'] = count($data['items']); $this->_Response('success', $data); } private function UpdateTask () { if($this->input->post('admin') == TRUE) { if($this->model_ajax->UpdateTask()) $this->_Response(); } $this->_Response('error'); } private function getRKlink() { if(!$this->session->userdata("id")) $this->_Response('error', array('msg' => 'bad_user_id!')); if((int)$this->input->post('summa') < 10) $this->_Response('error', array('msg' => 'Минимальная сумма пополнения 10 руб.!')); $mrh_login = ""; $mrh_pass1 = ""; $summa = $this->input->post('summa'); $Inv_id = $this->model_ajax->addpayment((int)$this->input->post('summa')); $crc = md5($mrh_login.':'.$summa.':'.$Inv_id.':'.$mrh_pass1); $url = 'https://auth.robokassa.ru/Merchant/Index.aspx?MrchLogin='.$mrh_login.'&OutSum='.$summa.'&InvId='.$Inv_id.'&SignatureValue='.$crc; $this->_Response('success', array('link' => $url)); } private function getFreeKlink() { if(!$this->session->userdata("id")) $this->_Response('error', array('msg' => 'bad_user_id!')); if((int)$this->input->post('summa') < 10) $this->_Response('error', array('msg' => 'Минимальная сумма пополнения 10 руб.!')); $mrch_id = $this->config->item('merchid'); $secret = $this->config->item('secret1'); $summa = $this->input->post('summa'); $Inv_id = $this->model_ajax->addpayment((int)$this->input->post('summa')); $sign = md5($mrch_id.':'.$summa.':'.$secret.':'.$Inv_id); $url = 'http://www.free-kassa.ru/merchant/cash.php?m='.$mrch_id.'&oa='.$summa.'&o='.$Inv_id.'&s='.$sign.'&lang=ru&i=&em='; $this->_Response('success', array('link' => $url)); } private function saveLink() { $this->load->library('form_validation'); $this->form_validation->set_message('check_tl', 'Указанна неверная ссылка'); $this->form_validation->set_rules('link', '`Ссылка для обмена`', 'required|callback_check_tl'); if ($this->form_validation->run() == FALSE) $this->_Response('error', array('link' => $this->core->userdata('trade_link'), 'msg' => strip_tags(form_error('link', '', '')))); else { if($this->model_ajax->update_link()) $this->_Response(); else $this->_Response('error', array('msg' => 'Ошибка записи бд!')); } } private function sellitem() { $idTask = $this->input->post("idTask"); if(!$this->model_ajax->check_sellItem($idTask)) $this->_Response('error', array('msg' => 'Приз не найден в бд или уже был отправлен!"')); $this->load->library('UserWork'); $this->_Response('success', array('db' => $this->model_ajax->sellitem($idTask), 'balance' => $this->userwork->get_balance(), 'case' => $temp[0])); } private function lastWinners() { $data['weapons'] = $this->model_ajax->get_last_winners(); if(!$data['weapons']) $this->_Response('error', array('msg' => 'database empty!')); $data['lw'] = $data['weapons'][0]['id']; if(!$data) $this->_Response('error', array('msg' => 'server_error')); $this->_Response("success", $data); } private function openCase() { $this->load->library('UserWork'); //Проверяем входящие параметры и сверяим их с базой; $id = $this->session->userdata("itemID"); if(!$id) $this->_Response('error', array('msg' => 'missing_item_id')); if(!$this->input->post("case")) $this->_Response('error', array('msg' => 'missing_case_id')); $box = $this->model_ajax->check_box(); if(!$box) $this->_Response('error', array('msg' => 'bad_case_id')); $item = $this->model_ajax->get_item($id); if(md5($id.$this->input->post("case")) !== $this->input->post("itemHash")) $this->_Response('error', array('msg' => 'bad_hash')); if(!$item) $this->_Response('error', array('msg' => 'bad_item_id')); if(!$this->session->userdata('id')) $this->_Response('error', array('msg' => 'bad_user_id')); if(strlen($this->core->userdata('trade_link')) < 1) $this->_Response('error', array('msg' => 'bad_trade_link')); $balance = $this->userwork->get_balance(); if(($box['price']) > $balance) $this->_Response('error', array('msg' => 'little_money')); $this->model_ajax->checkSpecial($id); $id = $this->model_ajax->add_task($id); //Добавляю предмет $this->model_ajax->user_rank(); $this->userwork->update_balance($box['price']);//Обновляю баланс $balance = $balance - $box["price"]; $items = $this->model_ajax->getItems($item["box"]); foreach($items as $key => $val) $items[$key] = str_replace("|", "<br/>", $items[$key]); $this->_Response('success', array("id" => $id, "weapon" => array( "imageUrl" => $item["big_pic"], "description" => $item["name"], "type" => $item["type"], "price" => $item["price"]), "items" => $items, "count" => count($items), "balance" => $balance, "sim" => $this->session->userdata("sim") )); } private function lastRK() { $this->session->set_userdata("lastRK", true); $this->_Response(); } private function _Response($status = "success", $data = array()) { $data['status'] = $status; exit(json_encode($data)); } //Проверка ссылки обмена public function check_tl($str) { return (preg_match("/https\:\/\/steamcommunity\.com\/tradeoffer\/new\/\?partner\=[0-9]*\&token\=[a-z]*/", $str)) ? TRUE : FALSE; } } <file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>Тикеты</span> </div> <div class="page-text"> <div style="width: 80%; margin: auto; text-align:right; margin-bottom: 15px;"><a href="<? echo base_url();?>tickets/add.html" class="btn btn-success">Новый тикет</a></div> <table style="width: 80%; margin: auto;"> <thead> <tr> <th>ID</th> <th>Заголовок</th> <th>Дата</th> <th>Состояние</th> </tr> </thead> <tbody> <? if($count < 1):?> <tr> <td colspan="4" style="text-align: center;">Нету созданных тикетов!</td> </tr> <? else: foreach($tickets as $ticket): ?> <tr> <td align="center" valign="middle"><? echo $ticket['id'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>tickets/view/<? echo $ticket['id'];?>.html"><? echo $ticket['title'];?></a></td> <td valign="middle"><? echo date("d.m.y - H:i:s", $ticket['time']);?></td> <td valign="middle"><? if($ticket['status'] == 0) echo "На расмотрение";?> <? if($ticket['status'] == 1) echo "Есть ответ";?> <? if($ticket['status'] == 2) echo "Закрыт";?></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Чтение тикета - <? echo $mess[0]['title'];?></div> <a href="<? echo base_url();?>admin/tickets/status/<? echo $mess[0]['id'];?>/2.html" class="btn btn-danger pull-right<? if($mess[0]['status'] == 2) echo ' disabled';?>">Закрыть тикет</a> <a href="<? echo base_url();?>admin/tickets/status/<? echo $mess[0]['id'];?>/1.html" class="btn btn-info pull-right<? if($mess[0]['status'] == 1) echo ' disabled';?>" style="margin-right: 10px;">Отметить как прочитанное</a> </div> <div class="panel-body"> <? foreach($mess as $key => $mes):?> <div class="col-xs-7 pull-<? echo ($mes['nickname'] == $mess[0]['nickname'])? 'left':'right';?>"> <p><strong><? echo $mes['nickname'];?></strong>:</p> <p><? echo $mes['text'];?></p> </div> <? endforeach;?> <div class="col-xs-12"> <form method="post" action="<? echo base_url();?>admin/tickets/send/<? echo $mess[0]['id'];?>.html"> <label for="textarea" class="col-sm-2 control-label">Ответ:<br> </label> <textarea class="form-control" style="width: 50%; margin-top: 50px;" name="text" id="textarea"></textarea> <input style="margin-left: 56.5%; margin-top: 15px;" type="submit" value="Отправить" class="btn btn-default"> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("model_admin"); $this->load->library("form_validation"); if(!$this->model_admin->check_admin()) { show_404(); return; } } public function index() { $this->boxs(); } public function boxs() { $data = array("boxs" => $this->model_admin->get_boxs()); $data['count'] = count($data['boxs']); $this->core->aDisplay("boxs", $data); } public function box_edit($id) { $data = $this->model_admin->get_box($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('sort', 'Сортировка', 'required'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('price', 'Цена', 'required'); $this->form_validation->set_rules('discount', 'Цена со скидкой', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("box_edit", $data); } else { $this->model_admin->edit_box($id); redirect("admin/box_edit/".$id); return; } } public function box_add() { $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('sort', 'Сортировка', 'required'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('price', 'Цена', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("box_add"); } else { $this->model_admin->add_box(); redirect("admin/boxs"); return; } } public function box_delete($id) { $this->db->delete('box', array('id' => $id)); $this->db->delete('items', array('box' => $id)); redirect("admin/boxs"); } //Оружия public function weapons() { $data = array("weapons" => $this->model_admin->get_weapons()); $data['count'] = count($data['weapons']); $this->core->aDisplay("weapons", $data); } public function weapon_edit($id) { $data = $this->model_admin->get_weapon($id); $data['types'] = $this->model_admin->wpn_types(); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('big_pic', 'Большое изображение', 'required|min_length[4]'); $this->form_validation->set_rules('type', 'Тип', 'required'); $this->form_validation->set_rules('price', 'Цена', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("weapon_edit", $data); } else { $this->model_admin->edit_weapon($id); redirect("admin/weapon_edit/".$id); return; } } public function weapon_add() { $data = array("types" => $this->model_admin->wpn_types()); $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('big_pic', 'Большое изображение', 'required|min_length[4]'); $this->form_validation->set_rules('type', 'Тип', 'required'); $this->form_validation->set_rules('price', 'Цена', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("weapon_add", $data); } else { $this->model_admin->add_weapon(); redirect("admin/weapons"); return; } } public function weapon_delete($id) { $this->db->delete('weapons', array('id' => $id)); redirect("admin/weapons"); } //Начинка от кейсов public function box_items($id) { $data = array("items" => $this->model_admin->get_items($id)); $data['id'] = $id; $data['count'] = count($data['items']); $this->core->aDisplay("box_items", $data); } public function item_edit($id) { $data = $this->model_admin->get_item($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('wpn', 'Оружие', 'required'); $this->form_validation->set_rules('sort', 'Позиция в кейсе', 'required'); $this->form_validation->set_rules('chance', 'Шанс', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("item_edit", $data); } else { $this->model_admin->edit_item($id); redirect("admin/item_edit/".$id); return; } } public function item_add($id) { $data['box'] = $id; $data['weapons'] = $this->model_admin->get_weapons(); $this->form_validation->set_rules('wpn', 'Оружие', 'required'); $this->form_validation->set_rules('sort', 'Позиция в кейсе', 'required'); $this->form_validation->set_rules('chance', 'Шанс', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("item_add", $data); } else { $this->model_admin->add_item($id); redirect("admin/box_items/".$id); return; } } public function item_delete($id, $box) { $this->db->delete('items', array('id' => $id)); redirect("admin/box_items/".$box); } //Заказы public function task() { $data = array("tasks" => $this->model_admin->get_tasks()); $data['count'] = count($data['tasks']); $this->core->aDisplay("tasks", $data); } public function task_status($status, $id) { switch($status) { case 'confirm': $this->model_admin->task_status(1,1, $id); break; case 'cancel': $this->model_admin->task_status(1,2, $id); break; case 'view': $this->model_admin->task_status(1,0, $id); break; } redirect('admin/task'); } public function pages() { $data = array("pages" => $this->model_admin->get_pages()); $data['count'] = count($data['pages']); $this->core->aDisplay("pages", $data); } public function page_edit($id) { $data = $this->model_admin->get_page($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('title', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Адрес', 'required'); $this->form_validation->set_rules('text', 'Содержание', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("page_edit", $data); } else { $this->model_admin->edit_page($id); redirect("admin/page_edit/".$id); return; } } public function page_add() { $this->form_validation->set_rules('title', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Адрес', 'required'); $this->form_validation->set_rules('text', 'Содержание', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("page_add"); } else { $this->model_admin->add_page(); redirect("admin/pages"); return; } } public function page_delete($id) { $this->db->delete('pages', array('id' => $id)); redirect("admin/pages"); } public function users() { $data = array("count" => 0); $this->form_validation->set_rules('search', 'Тип поиска', 'required'); $this->form_validation->set_rules('arg', 'Аргумент поиска', 'required'); if ($this->form_validation->run()) $data = $this->model_admin->user_search(); $this->core->aDisplay('users', $data); } public function user_edit($id) { $data = $this->model_admin->get_user($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('nickname', 'Ник', 'required'); $this->form_validation->set_rules('balance', 'Баланс', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("user_edit", $data); } else { $this->model_admin->edit_user($id); redirect("admin/user_edit/".$id); return; } } public function user_delete($id) { $this->db->delete('users', array('id' => $id)); redirect("admin/users"); } public function settings() { $this->form_validation->set_rules('sitename', 'Название сайта', 'required'); $this->form_validation->set_rules('ch10', 'Шанс 10%', 'required'); $this->form_validation->set_rules('ch20', 'Шанс 20%', 'required'); $this->form_validation->set_rules('ch30', 'Шанс 30%', 'required'); $this->form_validation->set_rules('rl1', 'Реф. уровень 1', 'required'); $this->form_validation->set_rules('rl2', 'Реф. уровень 2', 'required'); $this->form_validation->set_rules('pstart', 'начальный бонус', 'required'); $this->form_validation->set_rules('carusel', 'тип карусели', 'required'); $this->form_validation->set_rules('timer', 'таймер', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("settings"); } else { $this->model_admin->edit_settings(); redirect("admin/settings"); return; } } public function payments() { $data = array("payments" => $this->model_admin->get_payments()); $data['count'] = count($data['payments']); $this->core->aDisplay("payments", $data); } public function user_payments($id) { $data = array("payments" => $this->model_admin->get_user_payments($id)); $data['count'] = count($data['payments']); $this->core->aDisplay("users_payments", $data); } public function types() { $data = array("types" => $this->model_admin->wpn_types()); $data['count'] = count($data['types']); $this->core->aDisplay("types", $data); } public function type_edit($id) { $data = $this->model_admin->get_type($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('name', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Алиас', 'required'); $this->form_validation->set_rules('color', 'Цвет', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("type_edit", $data); } else { $this->model_admin->edit_type($id); redirect("admin/type_edit/".$id); return; } } public function type_add() { $this->form_validation->set_rules('name', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Алиас', 'required'); $this->form_validation->set_rules('color', 'Цвет', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->aDisplay("type_add"); } else { $this->model_admin->add_type(); redirect("admin/types"); return; } } public function type_delete($id) { $this->db->delete('types', array('id' => $id)); redirect("admin/types"); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Добавление кейса</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/boxs/add" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name" value=""> </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">URL кейса</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input4" name="alias" value=""> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Сортировка</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="sort" value=""> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Изображение</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="pic" value=""> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Прайс</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input3" name="price" value=""> </div> </div> <div class="form-group"> <label for="position" class="col-sm-2 control-label">Позиция:</label> <div class="col-sm-10"> <select class="form-control" name="position" id="position"> <option value="1">Топ-линия 1</option> <option value="2">Топ-линия 2</option> <option value="0">Кейсы</option> <option value="3">Коллекции</option> </select> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label">URL-суфикс:</label> <div class="col-sm-10"> <select class="form-control" name="category" id="category"> <option value="0">case</option> <option value="1">random</option> <option value="2">collection</option> </select> </div> </div> <div class="col-lg-6" style="margin-left: 45px; margin-bottom: 25px;"> <div class="input-group"> <label for="input3" class="pull-right" style="margin-right: 25px;">Скидка</label> <span class="input-group-addon"> <input name="setDiscount" type="checkbox" id="setDiscount"> </span> <input type="text" class="form-control" id="discount" name="discount" value="0"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> <div class="form-group"> <label for="position" class="col-sm-2 control-label">Тип кейса:</label> <div class="col-sm-10"> <select class="form-control" name="type" id="type"> <? foreach($types as $type):?> <option value="<? echo $type['alias'];?>"><? echo $type['alias'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Добавить</button> </div> </div> </form> </div> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Кейсы</div> <a class="btn btn-info pull-right" href="<? echo base_url();?>admin/boxs/box_statistic.html">Статистика</a> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/boxs/add.html" style="margin-right: 10px;">Добавить</a> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Название</th> <th>Сортировка</th> <th>Изображение</th> <th>Цена</th> <th>#</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Кейсы не созданы!</td> </tr> <? else: foreach($boxs as $box): ?> <tr> <td><? echo $box['id'];?></td> <td align="center" valign="middle"><? echo $box['name'];?></td> <td align="center" valign="middle"><? echo $box['sort'];?></td> <td align="center" valign="middle"><img width="120"" src="<? echo base_url();?>images/boxs/<? echo $box['pic'];?>"/></td> <td><? echo $box['price'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/boxs/edit/<? echo $box['id'];?>.html">Изменить</a><br/><br/><a href="<? echo base_url();?>admin/boxs/items/<? echo $box['id'];?>.html">Оружия</a><br/><br/><a href="<? echo base_url();?>admin/boxs/statistic/<? echo $box['id'];?>.html">Статистика</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep>$(document).ready(function() { var isExecuting, itemList, $itemsContainer, $itemsHiddenContainer, rotateStatus; // нажали на «открыть кейс» $('#opencase').on('click', function(e) { window.ubl = false; e.preventDefault(); if (isExecuting) return; isExecuting = true; // посылаем запрос $.ajax({ type: 'POST', url: window.roundcarouselRequestOptions['url'], dataType: 'json', data: { 'action': window.roundcarouselRequestOptions['action'], 'case': window.roundcarouselRequestOptions['case'], 'chance': window.roundcarouselRequestOptions['chance'] } }).done(function (data) { if (data.status === "success") { window.idItem = data.id; dower = false; itemList = data.items; $('#weaponBlock .recweaptitle .name').text(data.weapon.name) $("#weaponImage").attr("src",data.weapon.imageUrl); $("#weaponName").text(data.weapon.description); $(".recweap").addClass(data.weapon.type); $('#SellButton').text('Продать за ('+data.weapon.price+' руб.)'); if(data.sim == false) $('#userBalance').text(data.balance); $itemsContainer = $('.circle .round-case'); $itemsHiddenContainer = $('#itemsHiddenContainer'); rotateStatus = true; itemList.forEach(function(item) { $('<div class="weaponblock ' + item.type + '"><img src="' + item.imageUrl + '" alt=""><div class="weaponblockinfo"><span>' + item.description + '</span></div></div>') .appendTo($itemsHiddenContainer); }); var rotateCallback = function rotateCallback() { rotateStatus = !rotateStatus; if (rotateStatus === false) { if (itemList.length > 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(1)'), itemList.shift()); if (itemList.length > 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(2)'), itemList.shift()); if (itemList.length > 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(5)'), itemList.shift()); if (itemList.length === 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(1)'), data.weapon); } else { if (itemList.length > 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(3)'), itemList.shift()); if (itemList.length > 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(4)'), itemList.shift()); if (itemList.length === 0) replaceItem($itemsContainer.children('.weaponblock:nth-child(1)'), data.weapon); } if (itemList.length > 0) { rotate(180, 2, 2, rotateCallback); } else { if (rotateStatus === false) { rotate(180, 2, 2, rotateCallback); } else { finalize(); } } }; var finalize = function() { // $itemsContainer.css('transform', ''); // $itemsContainer.children('.weaponblock').each(function() { // $(this).css('tran sform', ''); // }); rotate(90, 2, 5, function() { rotate(90, 2, 10, function() { rotate(90, 2, 15, function() { rotate(90, 2, 20, function() { rotate(60, 2, 25, function() { rotate(60, 2, 30, function() { rotate(60, 2, 35, function() { rotate(30, 2, 40, function() { rotate(30, 2, 45, function() { rotate(30, 2, 50, function() { rotate(30, 2, 55, function() { rotate(30, 2, 60, function() { rotate(30, 2, 65, function() { $itemsContainer.css('transform', ''); $itemsContainer.children('.weaponblock').each(function() { $(this).css('transform', ''); }); $('#weaponBlock').arcticmodal({ closeOnOverlayClick: false, openEffect: {type: 'none', speed: 400} }); window.ubl = true; //Конец }); }); }); }); }); }); }); }); }); }); }); }); }); }; // rotate(180, 2, 10, rotateCallback); rotate(30, 1, 40, function() { rotate(30, 1, 30, function() { rotate(30, 1, 20, function() { rotate(30, 2, 30, function() { rotate(30, 2, 20, function() { rotate(30, 2, 15, function() { rotate(180, 2, 10, function() { rotate(180, 2, 10, rotateCallback); }); }); }); }); }); }); }); } else { var txtError = ""; switch(data.msg) { case "little_money": txtError = "На балансе недостаточно средств!"; break; case "bad_item_id": txtError = "Данные о призе не найдены"; break; case "missing_case_id": txtError = "Не найден ID кейса!"; break; case "missing_item_id": txtError = "Не найден ID приза!"; break; case "bad_item_id": txtError = "Неверный ID приза!"; break; case "bad_user_id": txtError = "Авторизуйтесь!"; break; case "missing_upchance": txtError = "Не найден параметр 'upchance'!"; break; case "bad_upchance_value": txtError = "Неверное значение параметра 'upchance'!"; break; } alert(txtError); isExecuting = false; } }); }); // замена item'а function replaceItem($item, data) { $item.removeClass().addClass('weaponblock ' + data.type); $item.children('img').attr('src', data.imageUrl); $item.children('.weaponblockinfo').children('span').html(data.description); } // функция для кручения изображений function rotate(rotationDegree, speed, time, callback) { var initialInnerDeg, initialOuterDeg, innerDeg, outerDeg, $outerCircle, $innerCircle; $outerCircle = $('.round-case'); $innerCircle = $('.round-case .weaponblock'); initialInnerDeg = getRotationAngle($innerCircle, 'isNegative') || 0; initialOuterDeg = getRotationAngle($outerCircle) || 0; innerDeg = initialInnerDeg - speed; outerDeg = initialOuterDeg + speed; function rotateTimer() { $outerCircle.css('transform', 'rotate(' + outerDeg + 'deg'); $innerCircle.css('transform', 'rotate(' + innerDeg + 'deg'); outerDeg += speed; innerDeg -= speed; if ( (outerDeg + speed) > (initialOuterDeg + rotationDegree) ) { speed = 1; } if (outerDeg - speed == initialOuterDeg + rotationDegree) { clearInterval(timer); if (callback) callback(); } } var timer = setInterval(rotateTimer, time); } // вспомогательная функция для получения значения свойства rotate в градусах function getRotationAngle($el, isNegative) { var st = window.getComputedStyle($el[0]); var tr = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || null; if (tr != null && tr != 'none') { var values = tr.split('(')[1].split(')')[0].split(','); var a = values[0]; var b = values[1]; var c = values[2]; var d = values[3]; var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); if (angle < 0) { angle = angle + 360; } if (angle === -0) { angle = angle + 0; } if (isNegative !== undefined) { angle = angle - 360; } } if (angle) return angle; if (tr === null || tr === 'none') return null; } });<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Платежи пользователя</div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead style="font-weight: bold; font-size: 15px; text-transform: uppercase;"> <tr> <th>ID</th> <th>Ник</th> <th>Сумма</th> <th>Дата</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Нету завершенных платежей!</td> </tr> <? else: foreach($payments as $item): ?> <tr> <td><? echo $item['id'];?></td> <td><? echo $item['nickname'];?></td> <td><? echo $item['money'];?></td> <td><? echo date("d.m.y - H:i:s", $item['time']);?></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Pages extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin/Model_pages'); } public function index() { $data = array("pages" => $this->Model_pages->get_pages()); $data['count'] = count($data['pages']); $this->core->Display("pages", $data); } public function edit($id) { $data = $this->Model_pages->get_page($id); if(!$data) { redirect("admin"); return; } $this->load->library("form_validation"); $this->form_validation->set_rules('title', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Адрес', 'required'); $this->form_validation->set_rules('text', 'Содержание', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("page_edit", $data); } else { $this->Model_pages->edit_page($id); redirect("admin/pages/edit/".$id); return; } } public function add() { $this->load->library("form_validation"); $this->form_validation->set_rules('title', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Адрес', 'required'); $this->form_validation->set_rules('text', 'Содержание', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("page_add"); } else { $this->Model_pages->add_page(); redirect("admin/pages"); return; } } public function delete($id) { $this->db->delete('pages', array('id' => $id)); redirect("admin/pages"); } }<file_sep><?php class Tester { public function __construct($params) { print_r($params); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Специальные условия для <? echo $user['nickname'];?></div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/users/special_add/<? echo $user['id'];?>.html">Добавить</a> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead style="font-weight: bold; font-size: 15px; text-transform: uppercase;"> <tr> <th>ID</th> <th>Пушка</th> <th>Кейс</th> <th>#</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Специальные условия не выставленны!</td> </tr> <? else: foreach($specials as $special): ?> <tr> <td><? echo $special['id'];?></td> <td><? echo $special['weapon'];?></td> <td><? echo $special['box_name'];?></td> <td><a href="<? echo base_url();?>admin/users/special_delete/<? echo $special['id'];?>/<? echo $user['id'];?>">Удалить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span><? echo $ticket['title'];?></span> </div> <div class="tickets"> <div class="add-mess"> <? echo validation_errors();?> <? if($ticket['status'] < 2):?> <form method="post" action="<? echo base_url();?>tickets/view/<? echo $ticket['id'];?>.html"> <label for="text" class="control-label">Ответить:</label> <textarea name="text" id="text" class="form-control"></textarea> <input type="submit" class="btn btn-success" style="margin-top: 15px;"> </form> <? endif;?> </div> <div class="ticket from"> <p class="author"><? echo $ticket['nickname'];?>:</p> <p class="text"><? echo $ticket['text'];?></p> <p class="date"><? echo date("d.m.y - H:i:s", $ticket['time']);?></p> </div> <? if($count > 0): foreach($mess as $mes):?> <div class="ticket <? echo ($mes['user_id'] == $ticket['user_id'])?'from':'to';?>"> <p class="author"><? echo $mes['nickname'];?>:</p> <p class="text"><? echo $mes['text'];?></p> <p class="date"><? echo date("d.m.y - H:i:s", $mes['time']);?></p> </div> <? endforeach; endif;?> </div><file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>Реферальная система</span> </div> <div class="page-text"> <? $status = (!isset($status))? false : true;?> <h3 class="header">Ваша реф. ссылка: </h3> <br /> <center><input class="form-control" style="width: 80%;" type="text" value="<? echo base_url();?>ref/<? echo $this->session->userdata('id');?>.html" size="50" readonly></center> <br /> <table style="width: 80%; margin: auto;"> <tbody> <tr> <td style="text-align: center;">За реферала, приглашённого Вами: </td> <td style="text-align: center;"><? echo $this->config->item("rl1");?>% от суммы пополнения пользователя</td> </tr> <tr> <td style="text-align: center;">За реферала, приглашённого Вашим рефералом: </td> <td style="text-align: center;"><? echo $this->config->item("rl2");?>% от суммы пополнения пользователя</td> </tr> <tr> </tr> </tbody> </table> <br /> <h3 class="header">Ваши рефералы: </h3> <br /> <table style="width: 80%; margin: auto;"> <thead> <tr> <th>ID</th> <th>Ник</th> <th>Доход</th> </tr> </thead> <tbody> <? if(!$status):?> <tr> <td colspan="5" style="text-align: center;">У вас нету рефералов!</td> </tr> <? else: foreach($referals as $referal): ?> <tr> <td align="center" valign="middle"><? echo $referal['id'];?></td> <td valign="middle"><? echo $referal['nickname'];?></td> <td valign="middle"><? echo $referal['refbalance'];?> руб.</td> </td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Users extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("model_users"); } public function auth() { if($this->session->userdata('id')) { redirect(); return; } $token = $this->input->post("token"); if(!$token) { redirect(); return; } $user = json_decode(file_get_contents('http://ulogin.ru/token.php?token=' . $token . '&host=' . $_SERVER['HTTP_HOST']), true); $res = $this->model_users->auth($user["network"], $user["identity"], $user["nickname"]); if(!$res) { redirect(); exit(); } $this->session->set_userdata($res); if(!file_exists('./images/avatar/'.$res['id'].'.jpg')) { file_put_contents('./images/avatar/'.$res['id'].'.jpg', file_get_contents($user['photo'])); $this->load->library('image_lib'); $config['source_image'] = './images/avatar/'.$res['id'].'.jpg'; //$config['create_thumb'] = TRUE; $config['maintain_ratio'] = TRUE; $config['width'] = 50; $config['height'] = 50; $this->image_lib->initialize($config); $this->image_lib->resize(); //Большая file_put_contents('./images/avatar/'.$res['id'].'_big.jpg', file_get_contents($user['photo_big'])); $this->load->library('image_lib'); $config['source_image'] = './images/avatar/'.$res['id'].'_big.jpg'; //$config['create_thumb'] = TRUE; $config['maintain_ratio'] = TRUE; $config['width'] = 230; $config['height'] = 230; $this->image_lib->initialize($config); $this->image_lib->resize(); } redirect(); } public function auth2() { $this->load->library('LightOpenID', array('uri' => 'auth2.html', 'method' => 'POST')); $idenity = $this->lightopenid->validate() ? $this->lightopenid->identity : null; if($idenity == null) { redirect(); return; } $Steam64 = str_replace("http://steamcommunity.com/openid/id/", "", $idenity); $profile = json_decode(file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$this->config->item('steamapi')."&steamids=".$Steam64)); $profile = $profile->response->players[0]; $res = $this->model_users->auth("steam", "http://steamcommunity.com/openid/id/".$profile->steamid, $profile->personaname); if(!$res) { redirect(); exit(); } $this->session->set_userdata($res); if(!file_exists('./images/avatar/'.$res['id'].'.jpg')) { file_put_contents('./images/avatar/'.$res['id'].'_buff.jpg', file_get_contents($profile->avatarfull)); copy('./images/avatar/'.$res['id'].'_buff.jpg', './images/avatar/'.$res['id'].'.jpg'); copy('./images/avatar/'.$res['id'].'_buff.jpg', './images/avatar/'.$res['id'].'_big.jpg'); unlink('./images/avatar/'.$res['id'].'_buff.jpg'); $this->load->library('image_lib'); $config['source_image'] = './images/avatar/'.$res['id'].'.jpg'; //$config['create_thumb'] = TRUE; $config['maintain_ratio'] = TRUE; $config['width'] = 50; $config['height'] = 50; $this->image_lib->initialize($config); $this->image_lib->resize(); //Большая $config['source_image'] = './images/avatar/'.$res['id'].'_big.jpg'; //$config['create_thumb'] = TRUE; $config['maintain_ratio'] = TRUE; $config['width'] = 230; $config['height'] = 230; $this->image_lib->initialize($config); $this->image_lib->resize(); } redirect(); } public function openid($idenity = false) { if(!$idenity) { redirect(); return; } $this->load->library('LightOpenID', array('uri' => 'auth2.html', 'method' => 'POST')); switch($idenity) { case 'steam': $this->lightopenid->identity = 'http://steamcommunity.com/openid/?l=english'; header('Location: ' . $this->lightopenid->authUrl()); break; default: redirect(); return; break; } } public function logout() { if(!$this->core->check_auth()) { redirect('404error'); return; } $this->session->sess_destroy(); redirect(); } public function ref($id) { if(!$this->core->check_user((int)$id)) { redirect(); return; } $this->session->set_userdata('ref', $id); redirect(); } public function referals() { if(!$this->core->check_auth()) { redirect('404error'); return; } $data = array("referals" => $this->model_users->get_referals()); $data['status'] = count($data['referals']); $this->core->set_title('Рефералы | #SITENAME#'); $this->core->Display('referals', $data); } public function payref() { if(!$this->core->check_auth()) { show_404(); return; } } public function profile($id = false) { if(!$id && !$this->core->check_auth()) { redirect('404error'); return; } else if(!$id) $id = $this->core->userdata('id'); $data = array("user" => $this->model_users->get_userdata($id)); if($data['user'] == FALSE) { redirect('404error'); return; } $data['tasks'] = $this->model_users->get_usertask($data['user']['id']); $data['count'] = count($data['tasks']); $this->core->set_title('Профиль пользователя '.$data['user']['nickname'].' | #SITENAME#'); $this->core->Display('userinfo', $data); } public function check_login($str) { if($this->model_users->check_login($str)) return true; else { $this->form_validation->set_message('check_login', 'Данный ник уже занят!'); return false; } } }<file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>Топ счастливчиков</span> </div> <div class="page-text"> <table style="width: 80%; margin: auto;"> <thead> <tr> <th>ID</th> <th>Пользователь</th> <th>Количество открытий</th> <th>Профит</th> </tr> </thead> <tbody> <? if($count < 1):?> <tr> <td colspan="5" style="text-align: center;">Счастливчики не найдены!</td> </tr> <? else: $i = 0; foreach($luckers as $lucky): if((int)$lucky['money'] < 1) continue; $i++; ?> <tr> <td align="center" valign="middle"><? echo $i;?></td> <td valign="middle"><? echo $lucky['nickname'];?></td> <td valign="middle"><? echo $lucky['count'];?></td> <td valign="middle"><? echo ((int)$lucky['money'] > 0)?round($lucky['money']+(($lucky['money']/100)*mt_rand(1,20))-mt_rand(1,10)):0;?></td> </td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_types extends CI_Model { public function wpn_types() { $this->db->select("id, name, alias, color"); $query = $this->db->get("types"); return $query->result_array(); } public function get_type($id) { $this->db->where("id", $id); $query = $this->db->get("types"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_type($id) { $data = array( 'name' => $this->input->post('name'), 'alias' => $this->input->post('alias'), 'color' => $this->input->post('color'), ); $this->db->where('id', $id); return $this->db->update('types', $data); } public function add_type() { $data = array( 'name' => $this->input->post('name'), 'alias' => $this->input->post('alias'), 'color' => $this->input->post('color'), ); return $this->db->insert('types', $data); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-body"> <h4><? echo $name;?></h4> <img src="<? echo base_url().'/images/boxs/'.$pic;?>" align="left" class="img-thumbnail" width="150" style="margin-right: 15px;"> <p style="font-size: 14px;"><span>Цена: </span><? echo $price;?> руб.</p> <p style="font-size: 14px;"><span>Открытий: </span><? echo $count;?> раз</p> <p style="font-size: 14px;"><a href="<? echo base_url();?>admin/boxs/items/<? echo $id;?>.html">Информация о текущем круге</a></p> <br/><br/> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Оружие</th> <th>Выпало раз</th> <th>Изображение</th> <th>Цена продажи</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Кейс не открывали!</td> </tr> <? else: foreach($statistics as $statistic): ?> <tr> <td><? echo $statistic['name'];?></td> <td><? echo $statistic['count'];?></td> <td align="center" valign="middle"><img width="120" src="<? echo $statistic['pic'];?>"/></td> <td><? echo $statistic['price'];?> руб.</td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_tickets extends CI_Model { public function get_tickets() { $this->db->select('`id`, `title`, `time`, `status`'); $this->db->where('`from`', $this->core->userdata('id')); $this->db->order_by("time", "DESC"); $query = $this->db->get("t_topic"); if($query->num_rows() < 1) return array(); return $query->result_array(); } public function add_ticket() { $data = array("title" => $this->input->post('title'), "text" => $this->input->post('text'), "from" => $this->core->userdata('id'), "time" => round(microtime(TRUE))); $this->db->insert('t_topic', $data); } public function view_ticket($id) { $data = array(); $query = $this->db->query("SELECT `users`.`nickname`, `users`.`id` AS `user_id` , `t_topic`.`title` , `t_topic`.`text` , `t_topic`.`time` , `t_topic`.`id`, `t_topic`.`status` FROM `t_topic` JOIN `users` ON `t_topic`.`from` = `users`.`id` WHERE `t_topic`.`from` = '".$this->core->userdata('id')."' AND `t_topic`.`id` = ".$this->db->escape($id)." ORDER BY `t_topic`.`time` DESC"); if($query->num_rows() < 1) return FALSE; $row = $query->result_array(); $data['ticket'] = $row[0]; unset($row); unset($query); $query = $this->db->query("SELECT `users`.`nickname`, `users`.`id` AS `user_id`, `t_mess`.`text` , `t_mess`.`time` , `t_mess`.`id` FROM `t_mess` JOIN `users` ON `t_mess`.`from` = `users`.`id` WHERE `t_mess`.`topic` = '".$data['ticket']['id']."' ORDER BY `t_mess`.`time` ASC"); $data['mess'] = $query->result_array(); $data['count'] = count($data['mess']); return $data; } public function add_mess($topic) { $data = array("topic" => $topic, "text" => $this->input->post('text'), "from" => $this->core->userdata('id'), "time" => round(microtime(TRUE))); $this->db->insert('t_mess', $data); unset($data); $data = array('status' => 0); $this->db->update('t_topic', $data, '`id` = '.$topic); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Добавление оружие</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/weapons/add.html" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name"> </div> </div> <div class="form-group"> <label for="input7" class="col-sm-2 control-label">Market_Name (для бота):</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input7" name="market_name"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Изображение</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="pic"> </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">Большое изображение (выводится в получение приза):</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input4" name="big_pic"> </div> </div> <div class="form-group"> <label for="input5" class="col-sm-2 control-label">Тип</label> <div class="col-sm-10"> <select name="type" class="form-control" id="input5"> <? foreach($types as $type):?> <option class="a<? echo $type['alias'];?>" value="<? echo $type['id'];?>"><? echo $type['name'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <label for="input6" class="col-sm-2 control-label">Цена продажи</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input6" name="price"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Добавить</button> </div> </div> </form> </div> </div> </div> </div> </div> </div><file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>История покупок</span> </div> <div class="page-text"> <table> <thead class="theader"> <tr> <th>ID заказа</th> <th>Дата</th> <th>Кейс</th> <th>Предмет</th> <th>Статус</th> </tr> </thead> <tbody class="tbody"> <? if(!$status):?> <tr> <td colspan="5" style="text-align: center;">Вы не сделали ни одной покупки</td> </tr> <? else: foreach($items as $item): ?> <tr> <td align="center" valign="middle"><? echo $item['id'];?></td> <td align="center" valign="middle"><? echo date("d.m.y - H:i:s", $item['time']);?></td> <td align="center" valign="middle"><? echo $item['box'];?></td> <td align="center" valign="middle"><? echo $item['weapon'];?></td> <td align="center" valign="middle"> <? if($item['status'] == 0 || (int)$item['status'] > 3) echo "<strong style='color:#4f4f4f'>В очереди</strong>"; if($item['status'] == 1) echo "<strong style='color: #259B24'>Отправлен</strong>"; if($item['status'] == 2) echo "<strong style='color: #DF1A1E'>Отменен</strong>"; if($item['status'] == 3) echo "<strong style='color: #42C745'>Продан</strong>"; ?> </td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Заказы на выплату</div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Пользователь</th> <th>Платежная система</th> <th>Сумма</th> <th>Дата</th> <th>Статус</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if($count < 1):?> <tr> <td colspan="5" style="text-align: center;">Заказов нету!</td> </tr> <? else: foreach($payouts as $payout): ?> <tr> <td><? echo $payout['id'];?></td> <td align="center" valign="middle"><? echo $payout['nickname'];?></td> <td align="center" valign="middle"><? echo $payout['ps'];?></td> <td align="center" valign="middle"><? echo $payout['money'];?></td> <td><? echo date("d.m.y - H:i:s", $payout['time']);?></td> <td align="center" valign="middle" style="font-size:12px;"><a href="<? echo base_url();?>admin/payout/status/confirm/<? echo $payout['id'];?>.html" class="btn btn-success">Отправлен</a><br/><br/><a href="<? echo base_url();?>admin/payout/status/cancel/<? echo $payout['id'];?>.html" style="color:#C51E21;">Отменен</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Изменения оружия в кейсе</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/boxs/item_edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Сортировка</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="sort" value="<? echo $sort;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Количество</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="count" value="<? echo $count;?>"> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Оружие</label> <div class="col-sm-10"> <select name="wpn" class="form-control chosen" id="input3"> <? foreach($weapons as $weapon):?> <option <? if($weapon['id'] == $wpn) echo 'selected';?> class="a<? echo $weapon['type'];?>" value="<? echo $weapon['id'];?>"><? echo $weapon['name'];?></option> <? endforeach;?> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label style="margin-top: 10px;"> <input name="first" type="checkbox" <? if($first) echo'checked="checked"';?>> Дорогой предмет </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/boxs/item_delete/<? echo $id;?>/<? echo $box;?>.html">Удалить</a> <a class="btn btn-default pull-right" style="margin-right: 10px;" href="<? echo base_url();?>admin/boxs/items/<? echo $box;?>">Вернуться к кейсу</a> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Страницы</div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/pages/add.html">Добавить</a> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Адрес</th> <th>Название</th> <th>#</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Кейсы не созданы!</td> </tr> <? else: foreach($pages as $page): ?> <tr> <td><? echo $page['id'];?></td> <td align="center" valign="middle"><? echo $page['alias'];?></td> <td align="center" valign="middle"><? echo $page['title'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/pages/edit/<? echo $page['id'];?>.html">Изменить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Типы оружий</div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/types/add.html">Добавить</a> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead style="font-weight: bold; font-size: 15px; text-transform: uppercase;"> <tr> <th>ID</th> <th>Название</th> <th>Алиас</th> <th>Цвет</th> <th>#</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Типы оружий не добавлены!</td> </tr> <? else: foreach($types as $type): ?> <tr> <td><? echo $type['id'];?></td> <td align="center" valign="middle"><? echo $type['name'];?></td> <td align="center" valign="middle"><? echo $type['alias'];?></td> <td class="a<? echo $type['alias'];?>"><? echo $type['color'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/type_edit/<? echo $type['id'];?>.html">Изменить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Types extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin/model_types'); } public function index() { $data = array("types" => $this->model_types->wpn_types()); $data['count'] = count($data['types']); $this->core->Display("types", $data); } public function edit($id) { $data = $this->model_types->get_type($id); if(!$data) { redirect("admin/types"); return; } $this->load->library("form_validation"); $this->form_validation->set_rules('name', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Алиас', 'required'); $this->form_validation->set_rules('color', 'Цвет', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("type_edit", $data); } else { $this->model_types->edit_type($id); redirect("admin/types/edit/".$id); return; } } public function add() { $this->load->library("form_validation"); $this->form_validation->set_rules('name', 'Название', 'required'); $this->form_validation->set_rules('alias', 'Алиас', 'required'); $this->form_validation->set_rules('color', 'Цвет', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("type_add"); } else { $this->model_types->add_type(); redirect("admin/types"); return; } } public function delete($id) { $this->db->delete('types', array('id' => $id)); redirect("admin/types"); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Tickets extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin/Model_tickets'); } public function index() { $data = array("tickets" => $this->Model_tickets->get_tickets()); $data['count'] = count($data['tickets']); $this->core->Display("tickets", $data); } public function history() { $data = array("tickets" => $this->Model_tickets->get_tickets(1)); // 1 - история. со статусом 1 $data['count'] = count($data['tickets']); $this->core->Display("tickets_history", $data); } public function status($id, $status) { $this->Model_tickets->update_status($id, $status); redirect('admin/tickets/history'); } public function view($id = 0) { $data = array('mess' => $this->Model_tickets->get_mess($id)); if(!$data['mess']) { redirect('admin/tickets'); return; } $this->core->Display('ticket_view', $data); } public function send($id) { if(!$this->Model_tickets->check_ticket($id)) { redirect('admin/tickets'); return; } $this->load->library("form_validation"); $this->form_validation->set_rules('text', 'Ответ', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("ticket_send"); } else { $this->Model_tickets->add_mess($id); redirect("admin/tickets/view/".$id); return; } } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Settings extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model('admin/Model_settings'); $this->load->library("form_validation"); } public function index() { $data = array("settings" => $this->Model_settings->get_settings()); foreach($data['settings'] as $sett) { $this->form_validation->set_rules($sett['key'], $sett['title'], 'required'); } if ($this->form_validation->run() == FALSE) { $this->core->Display("settings", $data); } else { $this->Model_settings->edit(); redirect("admin/settings"); return; } } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Оружия кейса</div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/boxs/item_add/<? echo $id;?>.html">Добавить</a> </div> <div class="panel-body"> <p style=" font-size:14px;"><p><strong>Длинна круга: </strong><? echo $len;?></p> <p><strong>Текущая прибль за круг: </strong><? echo $len_price;?> руб.</p> <p><strong>Текущая позиция: </strong><? echo $curr;?></p> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Сортировка в кейсе</th> <th>Оружие</th> <th>Изображение</th> <th>Повторений</th> <th>#</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Оружия не добавлены!</td> </tr> <? else: foreach($items as $item): ?> <tr> <td><? echo $item['id'];?></td> <td><? echo $item['sort'];?></td> <td align="center" valign="middle"><a href="https://market.csgo.com/?s=price&search=<? echo $item['name'];?>" target="_blank"><? echo $item['name'];?></a></td> <td align="center" valign="middle"><img width="120"" src="<? echo $item['pic'];?>"/></td> <td><? echo $item['count'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/boxs/item_edit/<? echo $item['id'];?>.html">Изменить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Покупки пользователя</div> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead style="font-weight: bold; font-size: 15px; text-transform: uppercase;"> <tr> <th>ID</th> <th>Кейс</th> <th>Пушка</th> <th>Дата</th> <th>Статус</th> </tr> </thead> <tbody style="font-size: 11px; text-transform: uppercase;"> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Нету покупок!</td> </tr> <? else: foreach($tasks as $task): ?> <tr> <td><? echo $task['id'];?></td> <td><? echo $task['box_name'];?></td> <td><? echo $task['weapon'];?></td> <td><? echo date("d.m.y - H:i:s", $task['time']);?></td> <td> <? if($task['status'] == 0)echo "<span style='color: grey;'>Ожидает</span>";?> <? if($task['status'] == 1)echo "<span style='color: green;'>Отправлено</span>";?> <? if($task['status'] == 2)echo "<span style='color: red;'>Отменен</span>";?> <? if($task['status'] == 3)echo "<span style='color: green;'>Продан</span><br/>(За ".$task['price']." руб.)";?> </td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_boxs extends CI_Model { public function get_boxs() { $query = $this->db->get("box"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_box($id) { $this->db->where("id", $id); $query = $this->db->get("box"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function get_types() { $this->db->select('alias'); $query = $this->db->get('types'); return $query->result_array(); } public function edit_box($id) { $data = array( 'name' => $this->input->post('name'), 'sort' => $this->input->post('sort'), 'pic' => $this->input->post('pic'), 'price' => $this->input->post('price'), 'alias' => $this->input->post('alias'), 'discount' => $this->input->post('discount'), 'category' => $this->input->post('category'), 'position' => $this->input->post('position'), 'type' => $this->input->post('type') ); $data['setDiscount'] = ($this->input->post('setDiscount') == 'on') ? 1 : 0; $data['public'] = ($this->input->post('public') == 'on') ? 1 : 0; $data['show'] = ($this->input->post('show') == 'on') ? 1 : 0; $this->db->where('id', $id); return $this->db->update('box', $data); } public function add_box() { $data = array( 'name' => $this->input->post('name'), 'sort' => $this->input->post('sort'), 'pic' => $this->input->post('pic'), 'alias' => $this->input->post('alias'), 'price' => $this->input->post('price'), 'category' => $this->input->post('category'), 'position' => $this->input->post('position'), 'type' => $this->input->post('type') ); $data['setDiscount'] = ($this->input->post('setDiscount') == 'on') ? 1 : 0; return $this->db->insert('box', $data); } public function get_weapons() { $query = $this->db->query("SELECT `weapons`.`id`, `weapons`.`name`, `types`.`alias` AS `type` FROM `weapons` JOIN `types` ON `types`.`id` = `weapons`.`type`"); return ($query->num_rows() < 1)? array() : $query->result_array(); } //Начинка от кейсов public function get_items($id) { $query = $this->db->query("SELECT `items`.`id` , `items`.`sort` , `items`.`count`, `items`.`curr`, `weapons`.`name` , `weapons`.`pic` FROM `items` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` WHERE `items`.`box` = '".$id."'"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_item($id) { $this->db->where('id', $id); $query = $this->db->get('items'); if($query->num_rows() < 1) return false; $row = $query->result_array(); $data = $row[0]; $this->db->select('id, name, type'); $query = $this->db->get('weapons'); $data['weapons'] = $query->result_array(); return $data; } public function edit_item($id) { $data = array( 'sort' => $this->input->post('sort'), 'count' => $this->input->post('count'), 'wpn' => $this->input->post('wpn'), ); $data['first'] = ($this->input->post('first') == 'on') ? 1 : 0; $this->db->where('id', $id); return $this->db->update('items', $data); } public function add_item($id) { $data = array( 'box' => $id, 'sort' => $this->input->post('sort'), 'count' => $this->input->post('count'), 'wpn' => $this->input->post('wpn'), ); $data['first'] = ($this->input->post('first') == 'on') ? 1 : 0; return $this->db->insert('items', $data); } public function get_box_price($id) { $this->db->select('price'); $this->db->where('id', $id); $this->db->limit(1); $query = $this->db->get('box'); if($query->num_rows() < 1) return FALSE; $row = $query->result_array(); return (int)$row[0]['price']; } public function count_tasks($case) { $query = $this->db->query("SELECT COUNT(*) as `count` FROM `task` WHERE `box` = '".$case."'"); $row = $query->result_array(); return $row[0]['count']; } public function statistic($case) { $query = $this->db->query('SELECT `weapons`.`name`, COUNT(`weapons`.`name`) AS `count`, `weapons`.`pic`, `weapons`.`price` FROM `task` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` WHERE `task`.`box` = '.$case.' GROUP BY `weapons`.`name` ORDER BY `count` DESC'); return $query->result_array(); } public function box_statistic() { $query = $this->db->query('SELECT COUNT( `box` ) AS `count` , `box`.`id` , `box`.`name` , `box`.`pic` , `box`.`price` FROM `task` JOIN `box` ON `box`.`id` = `task`.`box` GROUP BY `box` ORDER BY `count` DESC '); return $query->result_array(); } }<file_sep> <div class="page-content"> <div class="row"> <div class="col-md-2"> <div class="sidebar content-box" style="display: block;"> <ul class="nav"> <!-- Main menu --> <li><a href="<? echo base_url();?>admin/boxs.html"><i class="glyphicon glyphicon-inbox"></i> Кейсы</a></li> <li><a href="<? echo base_url();?>admin/weapons.html"><i class="glyphicon glyphicon-fire"></i> Оружия</a></li> <li><a href="<? echo base_url();?>admin/types.html"><i class="glyphicon glyphicon-list-alt"></i> Типы оружий</a></li> <li><a href="<? echo base_url();?>admin/meta.html"><i class="glyphicon glyphicon-text-width"></i> Meta</a></li> <li><a href="<? echo base_url();?>admin/pages.html"><i class="glyphicon glyphicon-file"></i> Страницы</a></li> <li><a href="<? echo base_url();?>admin/users.html"><i class="glyphicon glyphicon-user"></i> Пользователи</a></li> <li><a href="<? echo base_url();?>admin/tickets.html"><i class="glyphicon glyphicon-user"></i> Тикеты <?php if($ticket):?><span class="badge"><?php echo $ticket;?></span><?php endif;?></a></li> <li><a href="<? echo base_url();?>admin/tasks.html"><i class="glyphicon glyphicon-list-alt"></i> Заказы <?php if($task):?><span class="badge"><?php echo $task;?></span><?php endif;?></a></li> <li><a href="<? echo base_url();?>admin/payout.html"><i class="glyphicon glyphicon-euro"></i> Выплаты</a></li> <li><a href="<? echo base_url();?>admin/settings.html"><i class="glyphicon glyphicon-cog"></i> Настройки</a></li> </ul> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Weapons extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model("admin/Model_weapons"); $this->load->library("form_validation"); } public function index() { $data = array("weapons" => $this->Model_weapons->get_weapons()); $data['count'] = count($data['weapons']); $this->core->Display("weapons", $data); } public function edit($id) { $data = $this->Model_weapons->get_weapon($id); $data['types'] = $this->Model_weapons->wpn_types(); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('market_name', 'Market_name', 'required|min_length[4]'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('big_pic', 'Большое изображение', 'required|min_length[4]'); $this->form_validation->set_rules('type', 'Тип', 'required'); $this->form_validation->set_rules('price', 'Цена', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("weapon_edit", $data); } else { $this->Model_weapons->edit_weapon($id); redirect("admin/weapons/edit/".$id); return; } } public function add() { $data = array("types" => $this->Model_weapons->wpn_types()); $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('market_name', 'Market_name', 'required|min_length[4]'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('big_pic', 'Большое изображение', 'required|min_length[4]'); $this->form_validation->set_rules('type', 'Тип', 'required'); $this->form_validation->set_rules('price', 'Цена', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("weapon_add", $data); } else { $this->Model_weapons->add_weapon(); redirect("admin/weapons"); return; } } public function delete($id) { $this->db->delete('weapons', array('id' => $id)); redirect("admin/weapons"); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Core { private $CI; private $_dir = ''; private $_userdata = array(); private $_title = FALSE; private $_meta = array(); private $_notif = array(); private $_blocks = array(); public function __construct() { $this->CI = &get_instance(); //Загружаю конфиги и пользовательские данные $this->_load_config(); $this->_userdata = $this->_load_userdata(); //Закрываем от стила кук if($this->userdata('auth')) if($this->userdata('ip') !== $this->CI->input->ip_address()) { $this->CI->session->unset_userdata('id'); redirect(); } //Определяюсь сторону сайта $this->_dir = ($this->CI->uri->segment(1) == 'admin')? "backend" : "frontend"; //Погрузка настроек шаблона if($this->_dir == 'frontend') if(file_exists(APPPATH.'views/frontend/blocks.json')) $this->_blocks = json_decode(file_get_contents(APPPATH.'views/frontend/blocks.json'), true); else $this->_blocks = array('header' => TRUE, 'footer' => TRUE, 'user_block' => TRUE, 'last_winner' => TRUE); } public function Display($view, $data = array()) { if($this->CI->config->item('siteoffline') == '1') { if(!$this->check_admin()) { $this->CI->load->view("siteoff"); return; } } $ban = $this->check_ban(); if($ban == 1) { $this->CI->load->view('ban'); return; } if($this->_dir == 'frontend') { //Если title не задан, ищем в бд $this->_meta = $this->_get_meta($this->CI->uri->uri_string()); if(!isset($this->_meta['title']) || strlen($this->_meta['title']) < 1) { if($this->_title) $this->_meta['title'] = $this->_title; else { $this->_meta = $this->_get_meta(); if(!isset($this->_meta['title'])) $this->_meta['title'] = $this->CI->config->item('sitename'); } } $this->_meta['title'] = str_replace('#SITENAME#', $this->CI->config->item('sitename'), $this->_meta['title']); $this->_meta['title'] = str_replace('#SYSNAME#', $this->_title, $this->_meta['title']); } //Конец тайтлов if($this->_dir == 'backend') if(!$this->check_auth() || !$this->check_admin()) { redirect('error404'); return; } // $this->CI->load->view($this->_dir."/header"); if($this->_dir == "frontend" && $this->_blocks['last_winner']) $this->CI->load->view($this->_dir."/last_winner"); else $this->CI->load->view($this->_dir."/menu", $this->_notification()); $this->CI->load->view($this->_dir."/modules/".$view, $data); if($this->_dir == "frontend" && $this->_blocks['user_block']) $this->CI->load->view($this->_dir."/user_block", $this->UserBlock()); $this->CI->load->view($this->_dir."/footer"); } public function metadata($key) { return (isset($this->_meta[$key])) ? $this->_meta[$key] : FALSE; } public function set_title($title) { $this->_title = $title; } private function _notification() { $data = array('task', 'ticket'); $buff = array(); //Шмотки $query = $this->CI->db->query('SELECT COUNT(*) AS `task` FROM `task` WHERE `status` > 3 OR `status` < 1'); $buff = $query->result_array(); $data['task'] = $buff[0]['task']; unset($buff); //Тикеты $query = $this->CI->db->query('SELECT COUNT(*) AS `t_topic` FROM `t_topic` WHERE `status` = 0'); $buff = $query->result_array(); $data['ticket'] = $buff[0]['t_topic']; unset($buff); return $data; } private function _get_meta($uri = '') { $this->CI->db->select('title, keys, desc, text'); $this->CI->db->where('uri', $uri); $this->CI->db->limit(1); $query = $this->CI->db->get('meta'); if($query->num_rows() < 1) return array(); $row = $query->result_array(); return $row[0]; } private function UserBlock() { $data['online'] = $this->online(); $data['users'] = $this->users(); $data['task'] = $this->task(); return $data; } private function task() { $query = $this->CI->db->query("SELECT COUNT(*) AS `task` FROM `task`"); $row = $query->result_array(); return $row[0]['task']; } private function users() { $query = $this->CI->db->query("SELECT COUNT(*) AS `users` FROM `users`"); $row = $query->result_array(); return $row[0]['users']; } private function online() { $session_id = session_id(); $query = $this->CI->db->query("SELECT `id_session` FROM `session` WHERE `id_session` = '".$session_id."'"); if($query->num_rows() < 1) { $this->CI->db->simple_query("INSERT INTO `session` VALUES('".$session_id."', NOW())"); } else { $this->CI->db->simple_query("UPDATE `session` SET `putdate` = NOW(), WHERE `id_session` = '".$session_id."'"); } $this->CI->db->simple_query("DELETE FROM `session` WHERE putdate < NOW() - INTERVAL '5' MINUTE"); $query = $this->CI->db->query("SELECT COUNT( * ) AS `online` FROM `session`"); $row = $query->result_array(); return $row[0]['online']; } public function userdata($key) { return (isset($this->_userdata[$key])) ? $this->_userdata[$key] : FALSE; } private function _load_userdata() { $id = $this->CI->session->userdata('id'); if($id === FALSE) return array('auth' => FALSE); $this->CI->db->where('id', $id); $query = $this->CI->db->get("users"); if($query->num_rows() < 1) return array('auth' => FALSE, 'admin' => FALSE); $row = $query->result_array(); $row[0]['auth'] = TRUE; return $row[0]; } private function _load_config() { $query = $this->CI->db->get("settings"); if($query->num_rows() > 0) { $rows = $query->result_array(); foreach($rows as $row) $this->CI->config->set_item($row['key'], $row['value']); } } //Checks public function check_auth() { return $this->userdata('auth'); } private function check_ban() { return (isset($this->_userdata['ban'])) ? $this->_userdata['ban'] : FALSE; } public function check_im() { $this->CI->db->select('COUNT(*) as `count`'); $this->CI->db->where('to', $this->userdata('id')); $this->CI->db->where('view', 0); $query = $this->CI->db->get('im'); $row = $query->result_array(); return $row[0]['count']; } public function check_admin() { return ($this->_userdata['admin'] == 0)? FALSE : TRUE; } public function check_user($id) { if(is_int($id)) $this->CI->db->where('id', $id); else $this->CI->db->where('nickname', $id); $query = $this->CI->db->get('users'); return ($query->num_rows() < 1) ? false : true; } public function setCase($game) { return ($game == $this->CI->session->userdata("game"))? "current" : ""; } }<file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>История пополнений</span> </div> <div class="page-text"> <table style="width: 80%; margin: auto;"> <thead> <tr> <th>ID платежа</th> <th>Дата</th> <th>Сумма</th> </tr> </thead> <tbody> <? if(!$status):?> <tr> <td colspan="5" style="text-align: center;">Нету завершенных платежей!</td> </tr> <? else: foreach($items as $item): ?> <tr> <td align="center" valign="middle"><? echo $item['id'];?></td> <td valign="middle"><? echo date("d.m.y - H:i:s", $item['time']);?></td> <td valign="middle"><? echo $item['money'];?></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_sitemap extends CI_Model { public function get_boxs() { $this->db->select("alias, category"); $this->db->where("public", 1); $query = $this->db->get("box"); return $query->result_array(); } public function get_pages() { $this->db->select("alias"); $query = $this->db->get("pages"); return $query->result_array(); } }<file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><h2><span>открыть <? echo $box_name;?></span></h2> </div> <div class="roulette"> <div class="roulette-action"> <div class="roulette-track"> <div id="casesCarusel"> <? foreach($carusel as $item):?> <div class="square-case <? echo $item['type'];?>"> <img src="<? echo $item['pic'];?>" alt=""> <div class="square-case-info"> <p><? echo str_replace("|", "</p><p>",$item['name']);?></p> </div> </div> <? endforeach;?> </div> </div> </div> <div class="buy-case"> <? if($this->core->check_auth()):?> <button id="openCase">Открыть кейс</button><span><? echo $box_price;?> руб</span> <? else:?> <button>Авторизуйтесь</button> <? endif;?> </div> <p class="buy-case-agreement">Открывая кейс, вы соглашаетесь с <a href="https://opencase-csgo.ru/page/rules.html">условиями</a> покупки.<br> Перед открытием убедитесь, что вы можете принимать обмены и у вас включен Steam Guard.</p> </div> <div class="cases-box"> <p class="cases-box-note">открыв кейс вы можете получить:</p> <div class="cases-box-area"> <? foreach($items as $item):?> <div class="square-case <? echo $item['type'];?>"> <img src="<? echo $item['pic'];?>" alt=""> <div class="square-case-info"> <p><? echo str_replace("|", "</p><p>",$item['name']);?></p> </div> </div> <? endforeach;?> </div> </div> <div class="case-text-box"> <? echo $this->core->metadata('text');?> </div> <div id="modal-container" style="display: none;"> <div class="modal-overlay"></div> <div class="case-open-wrap"> <div class="case-open"> <img src="<? echo base_url();?>images/modal-bg.jpg" alt="" class="modal-bg"> <div class="case-open-area"> <div class="open-case-info"></div> <div class="case-open-image"> <img id="weaponImage" src="<? echo base_url();?>images/w4.png" alt=""> </div> <div class="case-open-option"> <button onClick="location.reload();">Вывести</button><span>1 мин</span> </div> <div class="case-open-option"> <button id="SellButton">Продать</button><span id="SellPrice">700 руб</span> </div> <p class="case-open-note">Приз будет отправлен по ссылке обмена,<br> которую вы указали. Время ожидания: от 1 минут до 24 часов.</p> <strong></strong> </div> </div> </div> </div> <? if($this->core->check_auth()):?> <script> var c = 0; var dower = true; var upchancePrice = 0; window.idItem = 0; $(function() { Math.rand = function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function shuffle(arr) { var r_i; var v; for (var i = 0; i < arr.length-1; i++) { r_i = Math.rand(0, arr.length-1); v = arr[r_i]; arr[r_i] = arr[arr.length-1]; arr[arr.length-1] = v; } return arr; } $itemsContainer = $('#casesCarusel'); function addItem(item, win) { var el = $('<div class="square-case ' + item.type + '"><img src="' + item.imageUrl + '" alt=""><div class="square-case-info"><p>' + item.description.replace("|","</p><p>") + '</p></div></div>'); el.hide() $itemsContainer.prepend(el) el.fadeIn(1000) c++ } var caseOpenAudio = new Audio(); caseOpenAudio.src = "<? echo base_url();?>audio/open.wav"; caseOpenAudio.volume = 0.2; var caseCloseAudio = new Audio(); caseCloseAudio.src = "<? echo base_url();?>audio/close.wav"; caseCloseAudio.volume = 0.2; var caseScrollAudio = new Audio(); caseScrollAudio.src = "<? echo base_url();?>audio/scroll.wav"; caseScrollAudio.volume = 0.2; $('#openCase').click(function() { if(!dower) return; $.ajax({ url: '<? echo base_url();?>ajax/', type: 'POST', dataType: 'json', data: { action: 'openCase', case: <? echo $box_id;?>, itemHash : '<? echo $itemHash;?>' }, success: function(data) { if (data.status == 'success') { window.ubl = false; dower = false; window.idItem = data.id; var curr = 0; while(true) { if(curr > 59) break; itemList = shuffle(data.items); itemList.forEach(function(item) { if(curr > 59) return; if(curr == 7) addItem(data.weapon, true); else addItem(item, false); curr++; }); } var a = ((curr - 6)*180)+70; $('#casesCarusel').animate({ marginLeft: -1 * Math.rand(a, a+90) }, { duration: 25000, easing: 'swing', start: function() { caseOpenAudio.play(); }, progress: function (a, p){ var c = p*100; if(c > 0.5 && c < 1.5) caseScrollAudio.play(); if(c > 8 && c < 92.5) caseScrollAudio.play(); }, complete: function() { caseCloseAudio.play(); $("#weaponImage").attr("src",data.weapon.imageUrl); $(".open-case-info").html("<p>"+data.weapon.description.replace("|","</p><p>")+"</p>"); $(".open-case-info").addClass(data.weapon.type); $(".case-open-area").addClass(data.weapon.type); $('#SellPrice').text(data.weapon.price+' руб'); if(data.sim == false) $('#userBalance').text(data.balance); window.ubl = true; $('#modal-container').show(500); } }); } if(data.status == "error") { var txtError = ""; switch(data.msg) { case "little_money": txtError = "На балансе недостаточно средств!"; break; case "bad_item_id": txtError = "Данные о призе не найдены"; break; case "missing_case_id": txtError = "Не найден ID кейса!"; break; case "missing_item_id": txtError = "Не найден ID приза! Обновите страницу."; break; case "bad_item_id": txtError = "Неверный ID приза!"; break; case "bad_user_id": txtError = "Авторизуйтесь!"; break; case "missing_upchance": txtError = "Не найден параметр 'upchance'!"; break; case "bad_upchance_value": txtError = "Неверное значение параметра 'upchance'!"; break; case "bad_trade_link": txtError = "У вас не указанна ссылка обмена! Подробнее на странице вашего профиля. (<? echo base_url();?>profile.html)"; break; case "bad_hash": txtError = "Ошибка Hash страницы, нажмите F5!"; break; } alert(txtError); dower = false; } }, error: function(jqXHR, textStatus, errorThrown) { alert('Произошла ошибка! Попробуйте еще раз '); } }); }); $('#SellButton').click(function() { $.ajax({ url: "<? echo base_url();?>ajax/", type: 'POST', dataType: 'json', data: { action: 'sellItem', 'idTask': window.idItem }, success: function(data) { if (data.status == 'success') { var prefix = 'case'; if(data.db == 0) alert("Ошибка записи в бд!"); if(data.case.category == 1) prefix = 'random'; if(data.case.category == 2) prefix = 'collection'; window.location.replace("<? echo base_url();?>"+prefix+"/"+data.case.alias+".html"); } else { alert(data.msg); } } }); }); }); </script> <? endif;?><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_payout extends CI_Model { public function get_payouts() { $query = $this->db->query("SELECT `payout`.`id`, `users`.`nickname`, `payout`.`ps`, `payout`.`money`, `payout`.`time`, `payout`.`status` FROM `payout` JOIN `users` ON `users`.`id` = `payout`.`user` WHERE `payout`.`status` = 0"); return $query->result_array(); } public function payout_status($status, $id) { $data = array( 'status' => $status ); $this->db->where('id', $id); return $this->db->update('payout', $data); } public function update_balance($id) { $this->db->select('user, money'); $this->db->where('id', $id); $query = $this->db->get('payout'); if($query->num_rows() < 1) return FALSE; $row = $query->result_array(); $this->db->query("UPDATE `users` SET `second_balance` = (`second_balance` + ".$row[0]['money'].") WHERE `id` = ".$row[0]['user']); } }<file_sep><div class="case-sborka-1"> <?php foreach($boxs as $box): if((int)$box['position'] !== 1) continue; ?> <div class="random-<? echo $box['type'];?>" onClick="location.replace('<? echo base_url();?>random/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="random-name"><? echo $box['name'];?></div> <div class="random-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="random-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div class="case-sborka-2"> <?php foreach($boxs as $box): if((int)$box['position'] !== 2) continue; ?> <div class="weapon-unit" onClick="location.replace('<? echo base_url();?>random/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="weapon-unit-name"><? echo $box['name'];?></div> <div class="weapon-unit-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="weapon-unit-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div align="center"><a target="_blank" href="https://vk.com/opencases_csgo" rel="nofollow"><img src="https://opencase-csgo.ru/images/opencase-csgo-banner.gif"></a></div> <br/><br/> <div class="main-text" itemscope="" itemtype="http://schema.org/Article"> <h2 itemprop="name">OpenCase-CsGo.ru - лучший сайт открытия кейсов cs go</h2> <div itemprop="articleBody"> <? echo $this->core->metadata('text');?> </div> </div> <div class="cases-title"><h2>Кейсы</h2></div> <div class="cases"> <?php foreach($boxs as $box): if((int)$box['position'] !== 0) continue; ?> <div class="item" onClick="location.replace('<? echo base_url();?>case/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="item-name"><? echo $box['name'];?></div> <div class="item-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="item-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <div class="cases-title"><h2>Коллекции</h2></div> <div class="cases"> <?php foreach($boxs as $box): if((int)$box['position'] !== 3) continue; ?> <div class="item" onClick="location.replace('<? echo base_url();?>collection/<? echo $box['alias'];?>.html')"> <div itemscope itemtype="https://schema.org/ImageObject"><img itemprop="image" src="./images/boxs/<? echo $box['pic'];?>" alt="<? echo $box['name'];?>"></div> <div class="item-name"><? echo $box['name'];?></div> <div class="item-price"><? echo ($box['setDiscount']) ? '<s style="color: #f61b1b">'.$box['discount'].'</s> '.$box['price'] : $box['price'] ;?> руб</div> <div class="item-open"><span>Открыть</span></div> </div> <? endforeach;?> </div> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Tasks extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("admin/Model_tasks"); } public function index() { $data = array("tasks" => $this->Model_tasks->get_tasks()); $data['count'] = count($data['tasks']); $this->core->Display("tasks", $data); } public function status($status, $id) { switch($status) { case 'confirm': $this->Model_tasks->task_status(1,1, $id); break; case 'cancel': $this->Model_tasks->task_status(1,2, $id); break; case 'view': $this->Model_tasks->task_status(1,0, $id); break; } redirect('admin/tasks'); } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Meta данные</div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/meta/add.html">Добавить</a> </div> <div class="panel-body"> <table class="table"> <thead> <tr> <th>ID</th> <th>URI</th> <th>Название</th> <th>#</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Meta данные не найдены!</td> </tr> <? else: foreach($metas as $meta): ?> <tr> <td><? echo $meta['id'];?></td> <td align="center" valign="middle"><? echo $meta['uri'];?></td> <td align="center" valign="middle"><? echo $meta['title'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/meta/edit/<? echo $meta['id'];?>.html">Изменить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div><file_sep><script type="text/javascript"> $(function() { window.ubl = true; var lw = 0; var lastWinners = $('.live-track'); function addWinner(item) { var el = $('<div class="live-unit '+item.type+'" onClick="location.replace(\'<? echo base_url();?>profile/'+item.user_id+'.html\')"><img src="'+item.pic+'" alt=""><div class="live-unit-info"><p>'+item.nickname+'</p><p>'+item.box+'</p><p>'+item.name+'</p></div></div>'); el.hide() lastWinners.prepend(el) el.fadeIn(1000) } function loadLastWinners() { if(!ubl) return; $.ajax({ url: "<? echo base_url();?>ajax/", type: 'POST', dataType: 'json', data: { action: 'lastWinners' }, success: function(data) { if(data.status == 'success') { if(lw !== data.lw) { lastWinners.html(''); $.each(data.weapons, function(index, value){ addWinner(value); }); lw = data.lw; } } }, error: function() { } }); } loadLastWinners(); setInterval(loadLastWinners, 5000); }); </script> <div class="top-winners"> <div class="top-winners-title"><p>Live лента</p><p><a href="<? echo base_url();?>toplackers.html">Топ лакеров</a></p></div> <div class="live-track"></div> </div> </header> <div class="main"><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование пользователя</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/users/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Ник</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="nickname" value="<? echo $nickname;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Баланс</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="balance" value="<? echo $balance;?>"> </div> </div> <div class="form-group"> <label for="input3" class="col-sm-2 control-label">Забанить?</label> <div class="col-sm-10"> <input name="ban" type="checkbox" <? if($ban == 1) echo'checked="checked"';?> value="1"> забанить? </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">Администратор?</label> <div class="col-sm-10"> <input name="admin" type="checkbox" <? if($admin == 1) echo'checked="checked"';?> value="1"> Администратор? </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/user_delete/<? echo $id;?>">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Seo_fix { public function checktag() { if(strpos($_SERVER['REQUEST_URI'], "admin") !== FALSE || $_SERVER['REQUEST_URI'] == "/" || strpos($_SERVER['REQUEST_URI'], "ajax") !== FALSE || strpos($_SERVER['REQUEST_URI'], "sitemap") !== FALSE || strpos($_SERVER['REQUEST_URI'], "pay/") !== FALSE) return; if(strpos($_SERVER['REQUEST_URI'], ".html") == FALSE) { header( 'Location: '.(isset($_SERVER['HTTPS']) ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/error404.html', true, 301 ); exit(); } } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class UserWork { private $_CI; public function __construct() { $this->_CI =& get_instance(); } public function update_balance($balance, $action = false, $user = true) { $user = ($user === true)? $this->_CI->session->userdata('id') : $user; $action = ($action) ? '+' : '-'; $balance = $this->_CI->db->escape($balance); $this->_CI->db->simple_query("UPDATE `users` SET `balance` = (`balance`".$action.$balance.") WHERE `id` =".$this->_CI->db->escape($user).";"); return true; } public function get_balance($user = true) { if($user === true) return $this->_CI->core->userdata('balance'); $this->_CI->db->select('balance'); $this->_CI->db->where('id', $user); $this->_CI->db->limit(1); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]['balance']; } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Payout extends CI_Controller { public $_m = false; public function __construct() { parent::__construct(); if(!$this->core->check_auth()) { redirect(); return; } $this->load->model("Model_payout"); } public function index() { $this->load->library('form_validation'); $data = array('payouts' => $this->Model_payout->get_payouts()); $data['count'] = count($data['payouts']); $this->form_validation->set_message('checkSumma', 'На балансе, недостаточно средств!'); $this->form_validation->set_rules('summa', 'Сумма', 'required|callback_checkSumma'); $this->form_validation->set_rules('qwn', '', 'callback_checkAdress'); $this->form_validation->set_rules('wmr', '', 'callback_checkAdress'); if ($this->form_validation->run() == FALSE) { $this->core->Display('payout', $data); } else { $this->Model_payout->add_payout(); redirect('payout'); } } public function cancel($id) { $this->Model_payout->cancel($id); redirect('payout'); } public function checkSumma($str) { return ((int)$str > $this->core->userdata('second_balance'))? FALSE : TRUE; } public function checkAdress($str) { if($this->_m) return TRUE; if($this->input->post('ps') == 'qw' && strlen($this->input->post('qwn')) < 11) { $this->_m = TRUE; $this->form_validation->set_message('checkAdress', 'Номер QIWI, меньше 11 символов!'); return FALSE; } elseif($this->input->post('ps') == 'wm' && strlen($this->input->post('wmr')) < 13) { $this->_m = TRUE; $this->form_validation->set_message('checkAdress', 'Номер кошелька WMR, меньше 13 символов!'); return FALSE; } return TRUE; } }<file_sep><div class="statistics"> <div><div class="stat-number"><? echo $task;?></div><div class="stat-feature">открыто кейсов</div></div> <div><div class="stat-number"><? echo $users;?></div><div class="stat-feature">пользователей</div></div> <div><div class="stat-number"><? echo $online;?></div><div class="stat-feature">онлайн</div></div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Tickets extends CI_Controller { public function __construct() { parent::__construct(); if(!$this->core->check_auth()) { redirect(); return; } $this->load->model("Model_tickets"); } public function index() { $data['tickets'] = $this->Model_tickets->get_tickets(); $data['count'] = count($data['tickets']); $this->core->set_title('Тикеты | #SITENAME#'); $this->core->Display('tickets/tickets', $data); } public function add() { $this->load->library("form_validation"); $this->form_validation->set_rules('title', 'Заголовок тикета', 'required|min_length[4]|max_length[100]'); $this->form_validation->set_rules('text', 'Сообщение тикета', 'required|min_length[4]'); if ($this->form_validation->run() == FALSE) { $this->core->set_title('Новый тикет | #SITENAME#'); $this->core->Display('tickets/add'); } else { $this->Model_tickets->add_ticket(); redirect("tickets"); } } public function view($id) { $data = $this->Model_tickets->view_ticket($id); if(!$data) { redirect(); return; } $this->load->library("form_validation"); $this->form_validation->set_rules('text', 'Сообщение ответа', 'required|min_length[4]'); if ($this->form_validation->run() == FALSE) { $this->core->set_title($data["ticket"]["title"].' | #SITENAME#'); $this->core->Display('tickets/view', $data); } else { $this->Model_tickets->add_mess($id); redirect("tickets/view/".$id); } } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Users extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model('admin/Model_users'); $this->load->library("form_validation"); } public function index($search = false, $arg = false) { $data = array("count" => 0); if ($search !== FALSE && $arg !== FALSE) $data = $this->Model_users->user_search($search, $arg); $this->core->Display('users', $data); } public function edit($id) { $data = $this->Model_users->get_user($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('nickname', 'Ник', 'required'); $this->form_validation->set_rules('balance', 'Баланс', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("user_edit", $data); } else { $this->Model_users->edit_user($id); redirect("admin/users/edit/".$id); return; } } public function delete($id) { $this->db->delete('users', array('id' => $id)); redirect("admin/users"); } public function payments($id) { $data = array("payments" => $this->Model_users->get_payments($id)); $data['count'] = count($data['payments']); $this->core->Display("users_payments", $data); } public function tasks($id) { $data = array("tasks" => $this->Model_users->get_tasks($id)); $data['count'] = count($data['tasks']); $this->core->Display("users_tasks", $data); } public function special($id) { $data = array("specials" => $this->Model_users->get_specials($id)); $data['user'] = $this->Model_users->get_user($id, "nickname"); $data['user']['id'] = $id; $data['count'] = ($data['specials'] === FALSE)? 0 : count($data['specials']); $this->core->Display("users_specials", $data); } public function special_add($id) { $data['boxs'] = $this->Model_users->get_boxs(); $data['id'] = $id; $this->form_validation->set_rules('box', 'Кейс', 'required'); $this->form_validation->set_rules('item', 'Пушка', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("special_add", $data); } else { $this->Model_users->add_special($id); redirect("admin/users/special/".$id); return; } } public function special_delete($id, $red) { $this->db->simple_query("DELETE FROM `special` WHERE `id` = '".$id."'"); redirect("admin/users/special/".$red); } public function auth($id) { $id = (int)$id; if($id < 1) { redirect('admin'); return; } $this->session->set_userdata('id', $id); redirect(); } }<file_sep><link href="<? echo base_url();?>css/admin/jquery.cleditor.css" rel="stylesheet" /> <script src="<? echo base_url();?>js/admin/jquery.cleditor.min.js"></script> <script> $(document).ready(function () { $("#cleditor").cleditor(); }); </script> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Редактирование meta-данных <? echo $uri;?></div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/meta/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Title</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="title" value="<? echo $title;?>"> </div> </div> <div class="form-group"> <label for="input4" class="col-sm-2 control-label">URI</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input4" name="uri" value="<? echo $uri;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">keys</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="keys" value="<? echo $keys;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Описание</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="desc" value="<? echo $desc;?>"> </div> </div> <div class="form-group"> <label for="cleditor" class="col-sm-2 control-label">Текст страницы</label> <div class="col-sm-10"> <textarea class="form-control" id="cleditor" name="text"><? echo $text;?></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/meta/delete/<? echo $id;?>">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_admin extends CI_Model { public function check_admin() { $this->db->select('id'); $this->db->where('admin', 1); $this->db->where('id', $this->session->userdata("id")); $query = $this->db->get("users"); return ($query->num_rows() < 1)? false : true; } public function get_boxs() { $query = $this->db->get("box"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_box($id) { $this->db->where("id", $id); $query = $this->db->get("box"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_box($id) { $data = array( 'name' => $this->input->post('name'), 'sort' => $this->input->post('sort'), 'pic' => $this->input->post('pic'), 'price' => $this->input->post('price'), 'discount' => $this->input->post('discount'), 'game' => $this->input->post('game') ); $this->db->where('id', $id); return $this->db->update('box', $data); } public function add_box() { $data = array( 'name' => $this->input->post('name'), 'sort' => $this->input->post('sort'), 'pic' => $this->input->post('pic'), 'price' => $this->input->post('price'), 'game' => $this->input->post('game') ); return $this->db->insert('box', $data); } //Оружия public function get_weapons() { $query = $this->db->query("SELECT `weapons`.`id`, `weapons`.`name`, `weapons`.`pic`, `weapons`.`big_pic`, `weapons`.`price`, `types`.`alias` AS `type` FROM `weapons` JOIN `types` ON `types`.`id` = `weapons`.`type`"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_weapon($id) { $this->db->where("id", $id); $query = $this->db->get("weapons"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_weapon($id) { $data = array( 'name' => $this->input->post('name'), 'pic' => $this->input->post('pic'), 'big_pic' => $this->input->post('big_pic'), 'type' => $this->input->post('type'), 'price' => $this->input->post('price') ); $this->db->where('id', $id); return $this->db->update('weapons', $data); } public function add_weapon() { $data = array( 'name' => $this->input->post('name'), 'pic' => $this->input->post('pic'), 'big_pic' => $this->input->post('big_pic'), 'type' => $this->input->post('type'), 'price' => $this->input->post('price') ); return $this->db->insert('weapons', $data); } //Начинка от кейсов public function get_items($id) { $query = $this->db->query("SELECT `items`.`id` , `items`.`sort` , `items`.`chance` , `weapons`.`name` , `weapons`.`pic` FROM `items` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` WHERE `items`.`box` = '".$id."'"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_item($id) { $this->db->where('id', $id); $query = $this->db->get('items'); if($query->num_rows() < 1) return false; $row = $query->result_array(); $data = $row[0]; $this->db->select('id, name, type'); $query = $this->db->get('weapons'); $data['weapons'] = $query->result_array(); return $data; } public function edit_item($id) { $data = array( 'sort' => $this->input->post('sort'), 'chance' => $this->input->post('chance'), 'wpn' => $this->input->post('wpn'), ); $this->db->where('id', $id); return $this->db->update('items', $data); } public function add_item($id) { $data = array( 'box' => $id, 'sort' => $this->input->post('sort'), 'chance' => $this->input->post('chance'), 'wpn' => $this->input->post('wpn'), ); return $this->db->insert('items', $data); } public function get_tasks() { $query = $this->db->query("SELECT `task`.`id` , `task`.`time` , `users`.`trade_link`, `users`.`nickname` AS `user` , `weapons`.`name` AS `weapon` , `weapons`.`type`, `box`.`name` AS `box` FROM `task` JOIN `users` ON `users`.`id` = `task`.`user` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` JOIN `box` ON `box`.`id` = `task`.`box` WHERE `view` = '0' AND `status` = '0' OR `status` = '4' ORDER BY `task`.`time` ASC"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function task_status($view, $status, $id) { $data = array( 'view' => $view, 'status' => $status ); $this->db->where('id', $id); return $this->db->update('task', $data); } //Страницы public function get_pages() { $query = $this->db->get("pages"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function get_page($id) { $this->db->where("id", $id); $query = $this->db->get("pages"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_page($id) { $data = array( 'title' => $this->input->post('title'), 'alias' => $this->input->post('alias'), 'text' => $this->input->post('text'), ); $this->db->where('id', $id); return $this->db->update('pages', $data); } public function add_page() { $data = array( 'title' => $this->input->post('title'), 'alias' => $this->input->post('alias'), 'text' => $this->input->post('text'), ); return $this->db->insert('pages', $data); } public function user_search() { $this->db->select("id, nickname, balance"); switch($this->input->post('search')) { default: case 'id': $this->db->like("id", $this->input->post("arg")); break; case 'nickname': $this->db->like("nickname", $this->input->post("arg")); break; case 'social': $this->db->like("identity", $this->input->post("arg")); break; } $this->db->limit(1); $query = $this->db->get("users"); if($query->num_rows() < 1) return array("count" => 0); $row = $query->result_array(); $row[0]['count'] = 1; return $row[0]; } public function get_user($id) { $this->db->where("id", $id); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_user($id) { $ban = ($this->input->post('ban') == 1)? 1 : 0; $admin = ($this->input->post('admin') == 1)? 1 : 0; $data = array( 'nickname' => $this->input->post('nickname'), 'balance' => $this->input->post('balance'), 'ban' => $ban, 'admin' => $admin ); $this->db->where('id', $id); return $this->db->update('users', $data); } public function edit_settings() { $this->sett_update_key('sitename'); $this->sett_update_key('ch10'); $this->sett_update_key('ch20'); $this->sett_update_key('ch30'); $this->sett_update_key('rl1'); $this->sett_update_key('rl2'); $this->sett_update_key('pstart'); $this->sett_update_key('carusel'); $this->sett_update_key('timer'); } public function get_payments() { $query = $this->db->query("SELECT `payment`.`id`, `users`.`nickname`, `payment`.`money`, `payment`.`time` FROM `payment` JOIN `users` ON `payment`.`user` = `users`.`id` WHERE `payment`.`status` = 1 ORDER BY `payment`.`id` DESC LIMIT 50"); return $query->result_array(); } public function get_user_payments($id) { $query = $this->db->query("SELECT `payment`.`id`, `users`.`nickname`, `payment`.`money`, `payment`.`time` FROM `payment` JOIN `users` ON `payment`.`user` = `users`.`id` WHERE `payment`.`status` = 1 AND `payment`.`user` = '".$id."' ORDER BY `payment`.`id` DESC"); return $query->result_array(); } public function wpn_types() { $this->db->select("id, name, alias, color"); $query = $this->db->get("types"); return $query->result_array(); } private function sett_update_key($key) { $this->db->where("key", $key); $this->db->update('settings', array("value" => $this->input->post($key))); } public function get_type($id) { $this->db->where("id", $id); $query = $this->db->get("types"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_type($id) { $data = array( 'name' => $this->input->post('name'), 'alias' => $this->input->post('alias'), 'color' => $this->input->post('color'), ); $this->db->where('id', $id); return $this->db->update('types', $data); } public function add_type() { $data = array( 'name' => $this->input->post('name'), 'alias' => $this->input->post('alias'), 'color' => $this->input->post('color'), ); return $this->db->insert('types', $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Meta extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin/Model_meta'); } public function index() { $data = array('metas' => $this->Model_meta->get_metas()); $data['count'] = count($data['metas']); $this->core->Display('meta', $data); } public function edit($id) { $data = $this->Model_meta->get_meta($id); $this->load->library("form_validation"); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('title', 'title', 'required|min_length[4]'); if ($this->form_validation->run() == FALSE) { $this->core->Display("meta_edit", $data); } else { $this->Model_meta->edit_meta($id); redirect("admin/meta/edit/".$id); return; } } public function add() { $this->load->library("form_validation"); $this->form_validation->set_rules('title', 'title', 'required|min_length[4]'); if ($this->form_validation->run() == FALSE) { $this->core->Display("meta_add"); } else { $this->Model_meta->add_meta(); redirect("admin/meta"); return; } } public function delete($id) { $this->db->delete('meta', array('id' => $id)); redirect("admin/meta"); } }<file_sep><div class="breadcrumbs"> <span>Главная &rarr; </span><span>мой профиль</span> </div> <div class="account-area"> <div class="account-area-left"> <div class="account-ava"><img src="<? echo base_url();?>images/avatar/<? echo $user['id'];?>_big.jpg" /></div> <div class="account-name"><? echo $user['nickname'];?></div> <? if($this->core->userdata('id') == $user['id']):?> <div><button onClick="window.open('<? echo $this->core->userdata('identity')?>', '_blank')" class="steam-link">Профиль <? echo ($this->core->userdata('network') == 'steam')? 'Steam' : 'ВК' ?></button><button onClick="location.replace('<? echo base_url();?>logout.html')" class="exit-account">Выйти</button></div> <div><button onClick="location.replace('<? echo base_url();?>mypayments.html')">История платежей</button></div> <div><button onClick="location.replace('<? echo base_url();?>myorders.html')">История покупок</button></div> <div><button onClick="location.replace('<? echo base_url();?>referals.html')">Реферальная система</button></div> <div><button onClick="location.replace('<? echo base_url();?>payout.html')">Заказать вывод</button></div> <div><button onClick="location.replace('<? echo base_url();?>tickets.html')">Тикеты</button></div> <? endif;?> </div> <div class="account-area-right"> <? if($this->core->userdata('id') == $user['id']):?> <div class="account-options"> <div><p>введите Trade-URL</p><p><a href="http://steamcommunity.com/id/me/tradeoffers/privacy#trade_offer_access_url">узнать!</a></p></div> <div><p>Пополните баланс</p><p>WebMoney, Yandex-деньги, QIWI</p></div> <div><p>Выигрывайте!</p><p>Начни открывать уже сейчас!</p></div> </div> <form id="trade-url"> <input id="trade-url-value" placeholder="TRADE-URL" value="<? echo $this->core->userdata('trade_link');?>"> <input id="trade-url-submit" type="button" value="Сохранить"> </form> <? endif;?> <div class="account-area-note"> <? if($this->core->userdata('id') == $user['id']):?> Ваши вещи <? else:?> Вещи пользователя, <? echo $user['nickname'];?> <? endif;?> </div> <? if($tasks): foreach($tasks as $task): switch($task['status']) { case 0: $class = 'down'; break; case 1: $class = 'plus'; break; case 2: $class = 'del'; break; case 3: $class = 'rub'; break; default: $class = ''; break; } ?> <div class="square-case silver"> <div class="square-case-features <? echo $class;?>"></div> <img class="drop-image" src="<? echo $task['weapon_pic'];?>" alt=""> <img class="case-image" src="<? echo base_url();?>images/boxs/<? echo $task['box_pic'];?>" alt=""> <div class="square-case-info"> <p><? echo str_replace("|", "</p><p>",$task['weapon']);?></p> </div> </div> <? endforeach; else: ?> <p style="text-align: center;">Открытые кейсы отсутствуют</p> <? endif;?> </div> </div> <? if($this->core->userdata('id') == $user['id']):?> <script type="text/javascript"> $(function() { $('#trade-url-submit').click(function() { $.ajax({ url: "<? echo base_url();?>/ajax/", type: 'POST', dataType: 'json', data: { action: 'saveLink', 'link': $('#trade-url-value').val() }, success: function(data) { if (data.status == 'success') alert("Ссылка обновлена!"); else { alert("Ошибка: "+data.msg); $('#trade-url-value').val(data.link); } } }); }); }); </script> <? endif;?> <file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_tasks extends CI_Model { public function get_tasks() { $query = $this->db->query("SELECT `task`.`id` , `task`.`time` , `users`.`trade_link`, `users`.`nickname` AS `user`, `users`.`id` As `user_id` , `weapons`.`name` AS `weapon` , `weapons`.`type`, `box`.`name` AS `box`, `box`.`price` AS `box_price`, `task`.`status`, `items`.`wpn` AS `wpn_id` FROM `task` JOIN `users` ON `users`.`id` = `task`.`user` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `weapons`.`id` = `items`.`wpn` JOIN `box` ON `box`.`id` = `task`.`box` WHERE `view` = '0' AND `status` < 1 OR `status` > 3 ORDER BY `task`.`time` ASC"); return ($query->num_rows() < 1)? array() : $query->result_array(); } public function task_status($view, $status, $id) { $data = array( 'view' => $view, 'status' => $status ); $this->db->where('id', $id); return $this->db->update('task', $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_meta extends CI_Model { public function get_metas() { $this->db->select('id, title, uri'); $query = $this->db->get('meta'); return $query->result_array(); } public function get_meta($id) { $this->db->where("id", $id); $query = $this->db->get("meta"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function edit_meta($id) { $data = array( 'title' => $this->input->post('title'), 'uri' => $this->input->post('uri'), 'keys' => $this->input->post('keys'), 'desc' => $this->input->post('desc'), 'text' => $this->input->post('text') ); $this->db->where('id', $id); return $this->db->update('meta', $data); } public function add_meta() { $data = array( 'title' => $this->input->post('title'), 'uri' => $this->input->post('uri'), 'keys' => $this->input->post('keys'), 'desc' => $this->input->post('desc'), 'text' => $this->input->post('text') ); return $this->db->insert('meta', $data); } }<file_sep><script type="text/javascript"> $(document).ready(function() { $("#form").submit(function() { if($("#item :selected").val() == null) { alert("Внимание! Не выбрано оружие!"); return false; } }); $("#box").change(function() { $("#item").empty(); try { $("#select2-item-container").html(""); } catch (err){} if($("#box :selected").val() == 0) return; $.ajax({ url: "<? echo base_url();?>ajax/", type: 'POST', dataType: 'json', data: { action: 'getItems', id: $("#box :selected").val() }, success: function(data) { if (data.status == 'success') { if(data.count < 1) { alert("Кейс не содержит пушки!"); return false; } $.each(data.items, function(key, value) { $("#item").append($("<option/>", { value: value['id'], text: value['name'] })); }); } } }); }); }); </script> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Добавление оружия в специальные условия</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form id="form" class="form-horizontal" role="form" action="<? echo base_url();?>admin/users/special_add/<? echo $id;?>" method="post"> <div class="form-group" id="boxs"> <label for="box" class="col-sm-2 control-label">Кейсы</label> <div class="col-sm-10"> <div class="side-by-side clearfix"> <select id="box" name="box" class="form-control chosen"> <option value="0">Выбирите кейс</option> <? foreach($boxs as $box):?> <option value="<? echo $box['id'];?>"><? echo $box['name'];?></option> <? endforeach;?> </select> </div> </div> </div> <div class="form-group" id="items"> <label for="item" class="col-sm-2 control-label">Оружия</label> <div class="col-sm-10"> <div class="side-by-side clearfix"> <select id="item" name="item" class="form-control chosen"></select> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button style="margin-top: 20px;" type="submit" class="btn btn-default">Добавить</button> </div> </div> </form> </div> </div> </div> </div><file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Оружия</div> <a class="btn btn-success pull-right" href="<? echo base_url();?>admin/weapons/add.html">Добавить</a> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>ID</th> <th>Название</th> <th>Изображение</th> <th>Тип</th> <th>Цена продажи</th> <th>#</th> </tr> </thead> <tbody> <? if(!$count):?> <tr> <td colspan="5" style="text-align: center;">Оружия не добавлены!</td> </tr> <? else: foreach($weapons as $weapon): ?> <tr> <td><? echo $weapon['id'];?></td> <td align="center" valign="middle"><? echo $weapon['name'];?></td> <td align="center" valign="middle"><img width="120"" src="<? echo $weapon['pic'];?>"/></td> <td><? echo $weapon['type'];?></td> <td><? echo $weapon['price'];?></td> <td align="center" valign="middle"><a href="<? echo base_url();?>admin/weapons/edit/<? echo $weapon['id'];?>.html">Изменить</a></td> </tr> <? endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Boxs extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model('admin/Model_boxs'); $this->load->library("form_validation"); } public function index($start = 0) { $data = array("boxs" => $this->Model_boxs->get_boxs()); $data['count'] = count($data['boxs']); $this->core->Display("boxs", $data); } public function edit($id) { $data = $this->Model_boxs->get_box($id); if(!$data) { redirect("admin/boxs"); return; } $data['types'] = $this->Model_boxs->get_types(); $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('alias', 'URL кейса', 'required|min_length[4]'); $this->form_validation->set_rules('sort', 'Сортировка', 'required'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('price', 'Цена', 'required'); $this->form_validation->set_rules('discount', 'Цена со скидкой', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("box_edit", $data); } else { $this->Model_boxs->edit_box($id); redirect("admin/boxs/edit/".$id); return; } } public function add() { $data['types'] = $this->Model_boxs->get_types(); $this->form_validation->set_rules('name', 'Название', 'required|min_length[4]'); $this->form_validation->set_rules('alias', 'URL кейса', 'required|min_length[4]|is_unique[box.alias]'); $this->form_validation->set_rules('sort', 'Сортировка', 'required'); $this->form_validation->set_rules('pic', 'Изображение', 'required|min_length[4]'); $this->form_validation->set_rules('price', 'Цена', 'required'); $this->form_validation->set_rules('discount', 'Цена со скидкой', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("box_add", $data); } else { $this->Model_boxs->add_box(); redirect("admin/boxs"); return; } } public function box_delete($id) { $this->db->delete('box', array('id' => $id)); $this->db->delete('items', array('box' => $id)); redirect("admin/boxs"); } //Начинка от кейсов public function items($id) { $data = array("items" => $this->Model_boxs->get_items($id)); $data['id'] = $id; $data['count'] = count($data['items']); $data['len'] = 0; $data['curr'] = 0; if($data['count'] > 0) { for((int)$i = 0; $i < $data['count']; $i++) { $data['len'] += $data['items'][$i]['count']; $data['curr'] += $data['items'][$i]['curr']; } } $data['len_price'] = $data['curr'] * $this->Model_boxs->get_box_price($id); $this->core->Display("box_items", $data); } public function item_edit($id) { $data = $this->Model_boxs->get_item($id); if(!$data) { redirect("admin"); return; } $this->form_validation->set_rules('wpn', 'Оружие', 'required'); $this->form_validation->set_rules('sort', 'Позиция в кейсе', 'required'); $this->form_validation->set_rules('count', 'Количество', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("item_edit", $data); } else { $this->Model_boxs->edit_item($id); redirect("admin/boxs/item_edit/".$id); return; } } public function item_add($id) { $data['box'] = $id; $data['weapons'] = $this->Model_boxs->get_weapons(); $this->form_validation->set_rules('wpn', 'Оружие', 'required'); $this->form_validation->set_rules('sort', 'Позиция в кейсе', 'required'); $this->form_validation->set_rules('count', 'Количество', 'required'); if ($this->form_validation->run() == FALSE) { $this->core->Display("item_add", $data); } else { $this->Model_boxs->add_item($id); redirect("admin/boxs/items/".$id); return; } } public function item_delete($id, $box) { $this->db->delete('items', array('id' => $id)); redirect("admin/boxs/items/".$box); } public function statistic($case) { $data = $this->Model_boxs->get_box($case); if(!$data) { show_404(); return; } $data['count'] = $this->Model_boxs->count_tasks($case); $data['statistics'] = $this->Model_boxs->statistic($case); $this->core->Display('box_stat', $data); } public function box_statistic() { $data['statistics'] = $this->Model_boxs->box_statistic(); $data['count'] = count($data['statistics']); $this->core->Display('boxs_stat', $data); } }<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Model_users extends CI_Model { public function auth($network, $id, $name) { $this->db->select("id"); $this->db->where("network", $network); $this->db->where("identity", $id); $this->db->limit(1); $query = $this->db->get("users"); if($query->num_rows() < 1) { $ref = (!$this->session->userdata("ref")) ? 0 : $this->session->userdata("ref"); $data = array("network" => $network, "identity" => $id, "nickname" => $name, "balance" => $this->config->item('pstart'), "referer" => $ref); if(!$this->db->insert('users', $data)) return false; $id = $this->db->insert_id(); $this->_update_ip($id); return array("id" => $id); } else { $row = $query->result_array(); $this->_update_ip($row[0]['id']); return $row[0]; } } private function _update_ip($id) { $data = array('ip' => $this->input->ip_address()); $this->db->update('users', $data, '`id` = '.$id); } public function get_referals() { $this->db->where('referer', $this->session->userdata('id')); $query = $this->db->get('users'); if($query->num_rows() < 1) return array(); return $query->result_array(); } public function get_userpay() { $this->db->where('r', $this->session->userdata('id')); $query = $this->db->get('users'); if($query->num_rows() < 1) return array(); return $query->result_array(); } public function get_userdata($id) { $this->db->select("`id`, `nickname`, `trade_link`, `identity`"); $this->db->where("id", $id); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function get_profile() { $this->db->select("`nickname`, `trade_link`"); $this->db->where("id", $this->session->userdata('id')); $query = $this->db->get("users"); if($query->num_rows() < 1) return false; $row = $query->result_array(); return $row[0]; } public function get_usertask($id) { $query = $this->db->query('SELECT `box`.`name` AS `box_name` , `box`.`pic` AS `box_pic` , `weapons`.`name` AS `weapon` , `weapons`.`pic` AS `weapon_pic`, `task`.`status` FROM `task` JOIN `box` ON `box`.`id` = `task`.`box` JOIN `items` ON `items`.`id` = `task`.`item` JOIN `weapons` ON `items`.`wpn` = `weapons`.`id` WHERE `task`.`user` = '.$this->db->escape($id).' ORDER BY `task`.`id` DESC'); return $query->result_array(); } public function edit_user() { $data = array( 'nickname' => $this->input->post('nickname'), 'trade_link' => $this->input->post('trade_link') ); if($this->config->item('carusel') == 'user') $data['carusel'] = $this->input->post('carusel'); $this->db->where('id', $this->session->userdata('id')); return $this->db->update('users', $data); } public function check_login($str) { $this->db->select("COUNT(*) as `count`"); $this->db->where("nickname", $str); $this->db->where("`id` != '".$this->session->userdata('id')."'"); $query = $this->db->get("users"); $row = $query->result_array(); return ($row[0]['count'] > 0)? false : true; } }<file_sep><div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title">Изменить тип оружия</div> </div> <div class="panel-body"> <?php echo validation_errors(); ?> <form class="form-horizontal" role="form" action="<? echo base_url();?>admin/types/edit/<? echo $id;?>" method="post"> <div class="form-group"> <label for="input1" class="col-sm-2 control-label">Название</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input1" name="name" value="<? echo $name;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Алиас</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="alias" value="<? echo $alias;?>"> </div> </div> <div class="form-group"> <label for="input2" class="col-sm-2 control-label">Цвет:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="input2" name="color" value="<? echo $color;?>"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Изменить</button> <a class="btn btn-danger pull-right" href="<? echo base_url();?>admin/type_delete/<? echo $id;?>.html">Удалить</a> </div> </div> </form> </div> </div> </div> </div> </div>
b9cc58201acb1209af830d50ae282685e8fc08db
[ "JavaScript", "PHP" ]
97
PHP
Jallvar/OpenCaseEngine
6af7e67d4cabb4031074b7f00e140c41ec6e9160
4c318ab5fa29fc2bc71bc5100e0d8c9194f68b6b
refs/heads/master
<file_sep>module github.com/arken/ark go 1.16 require ( github.com/BurntSushi/toml v0.4.1 github.com/DataDrake/cli-ng/v2 v2.0.2 github.com/go-git/go-git/v5 v5.4.2 github.com/google/go-github/v38 v38.1.0 github.com/hashicorp/go-version v1.2.1 // indirect github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf github.com/ipfs/go-ipfs v0.9.1 github.com/ipfs/go-ipfs-config v0.14.0 github.com/ipfs/go-ipfs-files v0.0.8 github.com/ipfs/interface-go-ipfs-core v0.4.0 github.com/schollz/progressbar/v3 v3.8.2 github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) <file_sep>package ipfs import ( "github.com/ipfs/interface-go-ipfs-core/options" icorepath "github.com/ipfs/interface-go-ipfs-core/path" ) // Pin a file to local storage. func (n *Node) Pin(hash string) error { // Construct IPFS CID path := icorepath.New("/ipfs/" + hash) // Pin file to local storage within IPFS err := n.api.Pin().Add(n.ctx, path, options.Pin.Recursive(true)) return err } <file_sep>package cli import ( "fmt" "os" "github.com/DataDrake/cli-ng/v2/cmd" ) func init() { cmd.Register(&Init) } // Init configures Ark's local staging and configuration directory. var Init = cmd.Sub{ Name: "init", Alias: "i", Short: "Initialize a dataset's local configuration.", Args: &InitArgs{}, Run: InitRun, } // InitArgs handles the specific arguments for the init command. type InitArgs struct { } // InitRun creates a new ark repo simply by creating a folder called .ark in the working dir. func InitRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist create it. if os.IsNotExist(err) { err := os.Mkdir(".ark", os.ModePerm) checkError(rFlags, err) wd, err := os.Getwd() checkError(rFlags, err) fmt.Printf("New ark repo initiated at %v\n", wd) return } // Check that there wasn't another type of error produced. checkError(rFlags, err) // If no error was produced it's possible the directory is already an // Ark repository. if info.IsDir() { fmt.Println("a directory called \".ark\" already exists here, " + "suggesting that this is already an ark repo") } else { // If somehow a .ark file exists tell the user about it. fmt.Println("a file called \".ark\" already exists in this " + "this directory and it is not itself a directory. Please move or " + "rename this file") } os.Exit(1) } <file_sep># ark A Command Line Client for Arken Clusters [![Go Report Card](https://goreportcard.com/badge/github.com/arken/ark)](https://goreportcard.com/report/github.com/arken/ark) ## What is Ark? Ark is a command line client for Arken that indexes, generates, and submits manifest additions as pull requests. Ark can also directly download collections of files from the nodes within an Arken cluster. ## Installation 1. Go to Ark Releases (over there -->) 2. Copy the link to your corresponding OS and Architecture. 3. Run `sudo curl -L "PATH-TO-RELEASE" -o /usr/local/bin/ark` 4. Run `sudo chmod a+x /usr/local/bin/ark` 5. (Optional) Run `sudo ln -s /usr/local/bin/ark /usr/bin/ark` ## Usage ### Commands | Command | Alias | Description | | ------------------- | ------- | -------------------------------------------------------------------------- | | `help` | `?` | Get help with a specific subcommand. | | `add` | `ad` | Stage a file for set of files for a submission. | | `alias` | `a` | Create a shortcut for a manifest URL. | | `config` | `c` | Update an one of Ark's Configuration Values. | | `init` | `i` | Initialize a dataset's local configuration. | | `pull` | `pl` | Pull a file from an Arken Cluster. | | `remove` | `rm` | Remove a file from the internal submission cache. | | `status` | `s` | View what files are currently staged for submission. | | `submit` | `sb` | Submit your files to a manifest repository. | | `update` | `upd` | Update Ark to the latest version available. | | `upload` | `up` | Upload files to an Arken cluster after an accepted submission. | ### Tutorial #### Initializing a manifest Go to the location of your data and run. (If you're running MacOS or Linux you can navigate to the folder containing your data in your file browser/finder and by right clicking on the folder open a terminal at that location.) ```bash ark init ``` #### Stage Data to Your manifest Submission Still within the location of your data add specific files or folders. ```bash ark add <LOCATION> ``` ##### ex. Stage the example.csv file into your Arken Submission. ```bash ark add example.csv ``` or to stage everything within the folder containing your data. ```bash ark add . ``` #### Submit Your Data to the manifest This will index the added data, generate a manifest file, and either add that file to the remote git repository or generate a pull request if you don't have access to the main repository. ```bash ark submit <manifest-LOCATION> ``` ##### ex. Submit your data to the official curated [Core Arken manifest](https://github.com/arken/core-manifest). ```bash ark submit https://github.com/arken/core-manifest ``` #### Uploading Your Data After Your Submission Has Been Accepted After your submission is accepted you'll receive an email notifying you the Pull Request has been merged into the manifest. At this point you can finally run ark upload from the directory with your data in it to upload the data to the cluster. ```bash ark upload https://github.com/arken/core-manifest ``` *Note:* If you attempt to run `ark upload` before your submission is accepted your data will not begin syncing with the cluster. ## License Copyright 2019-2021 <NAME> & Arken Project <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>package manifest import ( "errors" "net/url" "github.com/arken/ark/manifest/upstream" "github.com/go-git/go-git/v5/config" ) func (m *Manifest) Fork() error { url, err := url.Parse(m.url) if err != nil { return err } // Check for matching upstream. upstream, ok := upstream.AvailableUpstreams[url.Host] if !ok { return errors.New("unknown upstream") } // If an upstream if found use it to fork the repository. m.forkUrl, err = upstream.Fork(m.gitOpts.Token, *url) if err != nil { return err } _, err = m.r.CreateRemote(&config.RemoteConfig{ Name: "fork", URLs: []string{m.forkUrl}, }) if err != nil && err.Error() == "remote already exists" { return nil } return err } <file_sep>package cli import ( "bufio" "fmt" "net/http" "os" "runtime" "strings" "sync" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" "github.com/inconshreveable/go-update" "github.com/tcnksm/go-latest" ) func init() { cmd.Register(&Update) } // Update checks for a new version of the Ark program and updates itself // if a newer version is found and the user agrees to update. var Update = cmd.Sub{ Name: "update", Alias: "upd", Short: "Update Ark to the latest version available.", Args: &UpdateArgs{}, Flags: &UpdateFlags{}, Run: UpdateRun, } // UpdateArgs handles the specific arguments for the update command. type UpdateArgs struct { } // UpdateFlags handles the specific flags for the update command. type UpdateFlags struct { Yes bool `short:"y" long:"yes" desc:"If a newer version is found update without prompting the user."` } // UpdateRun handles the checking and self updating of the Ark program. func UpdateRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) fmt.Printf("Current Version: %s\n", config.Version) if config.Version == "develop" { fmt.Println("Cannot update a development version of Ark.") os.Exit(1) } flags := c.Flags.(*UpdateFlags) latestVersion := &latest.GithubTag{ Owner: "arken", Repository: "ark", } res, err := latest.Check(latestVersion, config.Version) checkError(rFlags, err) fmt.Printf("Latest Version: %s\n", res.Current) if res.Outdated { if !flags.Yes { fmt.Println("Would you like to update Ark to the newest version? ([y]/n)") reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') input = strings.ToLower(strings.TrimSpace(input)) if input == "n" { return } } url := "https://github.com/arken/ark/releases/download/v" + res.Current + "/ark-v" + res.Current + "-" + runtime.GOOS + "-" + runtime.GOARCH doneChan := make(chan int, 1) wg := sync.WaitGroup{} wg.Add(1) // Display Spinner on Update. go spinnerWait(doneChan, "Updating Ark...", &wg) resp, err := http.Get(url) checkError(rFlags, err) defer resp.Body.Close() err = update.Apply(resp.Body, update.Options{}) checkError(rFlags, err) doneChan <- 0 wg.Wait() fmt.Print("\rUpdating Ark: Done!\n") } else { fmt.Println("Already Up-To-Date!") } } <file_sep>package ipfs import ( "context" "fmt" "io/ioutil" "os" "path/filepath" ipfsConfig "github.com/ipfs/go-ipfs-config" "github.com/ipfs/go-ipfs/core" "github.com/ipfs/go-ipfs/core/coreapi" // This package is needed so that all the preloaded plugins are loaded automatically. "github.com/ipfs/go-ipfs/core/node/libp2p" "github.com/ipfs/go-ipfs/plugin/loader" "github.com/ipfs/go-ipfs/repo" "github.com/ipfs/go-ipfs/repo/fsrepo" migrate "github.com/ipfs/go-ipfs/repo/fsrepo/migrations" icore "github.com/ipfs/interface-go-ipfs-core" ) type NodeConfArgs struct { SwarmKey string BootstrapPeers []string } type Node struct { api icore.CoreAPI ctx context.Context cancel context.CancelFunc node *core.IpfsNode } // CreateNode creates an IPFS node and returns its coreAPI func CreateNode(repoPath string, args NodeConfArgs) (node *Node, err error) { // Setup IPFS plugins if err := setupPlugins(repoPath); err != nil { return nil, err } // Initialize node structure node = &Node{} // Create IPFS node node.ctx, node.cancel = context.WithCancel(context.Background()) // Create Swarm Key File if args.SwarmKey != "" { err = createSwarmKey(repoPath, args.SwarmKey) if err != nil { return nil, err } } // Open the repo fs, err := openFs(node.ctx, repoPath) if err != nil { err = createFs( node.ctx, repoPath, args.BootstrapPeers, ) if err != nil { return nil, err } fs, err = openFs(node.ctx, repoPath) if err != nil { return nil, err } } // Construct the node nodeOptions := &core.BuildCfg{ Permanent: true, Online: true, Routing: libp2p.DHTClientOption, Repo: fs, } node.node, err = core.NewNode(node.ctx, nodeOptions) if err != nil { return nil, err } node.node.IsDaemon = true // Attach the Core API to the constructed node node.api, err = coreapi.NewCoreAPI(node.node) return node, err } func openFs(ctx context.Context, repoPath string) (result repo.Repo, err error) { result, err = fsrepo.Open(repoPath) if err != nil && err == fsrepo.ErrNeedMigration { err = os.Setenv("IPFS_PATH", repoPath) if err != nil { return nil, err } err = migrate.RunMigration(ctx, migrate.NewHttpFetcher("", "", "ipfs", 0), fsrepo.RepoVersion, repoPath, false) if err != nil { return nil, err } result, err = fsrepo.Open(repoPath) } return result, err } // createFs builds the IPFS configuration repository. func createFs(ctx context.Context, path string, bootstrapPeers []string) (err error) { // Check if directory to configuration exists if _, err = os.Stat(path); os.IsNotExist(err) { os.MkdirAll(path, os.ModePerm) } // Create a ipfsConfig with default options and a 2048 bit key cfg, err := ipfsConfig.Init(ioutil.Discard, 2048) if err != nil { return err } // Set default ipfsConfig values cfg.Datastore.StorageMax = "100TB" cfg.Reprovider.Interval = "1h" cfg.Reprovider.Strategy = "roots" cfg.Routing.Type = "dhtclient" cfg.Bootstrap = bootstrapPeers cfg.Swarm.ConnMgr.HighWater = 1200 cfg.Swarm.ConnMgr.LowWater = 1000 cfg.Experimental.FilestoreEnabled = true // Create the repo with the ipfsConfig err = fsrepo.Init(path, cfg) if err != nil { return fmt.Errorf("failed to init node: %s", err) } return nil } func createSwarmKey(path string, key string) (err error) { keyPath := filepath.Join(path, "swarm.key") // Check if directory to configuration exists if _, err = os.Stat(path); os.IsNotExist(err) { os.MkdirAll(path, os.ModePerm) } if _, err = os.Stat(keyPath); os.IsNotExist(err) { var file *os.File file, err = os.Create(keyPath) if err != nil { return err } _, err = file.WriteString("/key/swarm/psk/1.0.0/\n/base16/\n" + key) } return err } func setupPlugins(externalPluginsPath string) error { // Load any external plugins if available on externalPluginsPath plugins, err := loader.NewPluginLoader(filepath.Join(externalPluginsPath, "plugins")) if err != nil { return fmt.Errorf("error loading plugins: %s", err) } // Load preloaded and external plugins if err := plugins.Initialize(); err != nil { return fmt.Errorf("error initializing plugins: %s", err) } if err := plugins.Inject(); err != nil { return fmt.Errorf("error initializing plugins: %s", err) } return nil } <file_sep>package upstream import ( "context" "errors" "fmt" "net/http" "net/url" "path/filepath" "github.com/google/go-github/v38/github" "golang.org/x/oauth2" ) var ( GitHubClientID string ) // GitHub is a wrapper struct for the GitHub Upstream type GitHub struct { } type GitHubAppAuthQuery struct { DeviceCode string `json:"device_code"` UserCode string `json:"user_code"` VerificationUri string `json:"verification_uri"` ExpiresIn int `json:"expires_in"` Interval int `json:"interval"` } func init() { registerUpstream(&GitHub{}, "github.com") } func (g *GitHub) Auth(path string) (result Guard, err error) { // Check if GitHubClientID has not been set. if GitHubClientID == "" { return nil, errors.New("required client id is nil") } client := github.NewClient(nil) ctx := context.Background() defer ctx.Done() query := &GitHubAppAuthQuery{} // Construct GitHub HTTP query req, _ := http.NewRequest("POST", "https://github.com/login/device/code", nil) req.Header.Add("Accept", "application/json") // Add parameters to request query params := req.URL.Query() params.Add("client_id", GitHubClientID) params.Add("scope", "public_repo") // Encode query req.URL.RawQuery = params.Encode() // Launch request _, err = client.Do(ctx, req, query) if err != nil { return nil, err } return &GitHubGuard{ client: client, query: query, }, nil } type GitHubGuard struct { client *github.Client query *GitHubAppAuthQuery token string } type GitHubAppAuthPoll struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` Scope string `json:"scope"` Error string `json:"error"` } func (g *GitHubGuard) GetAccessToken() string { return g.token } func (g *GitHubGuard) GetCode() string { return g.query.UserCode } func (g *GitHubGuard) GetExpireInterval() int { return g.query.ExpiresIn } func (g *GitHubGuard) GetInterval() int { return g.query.Interval } func (g *GitHubGuard) CheckStatus() (status string, err error) { ctx := context.Background() defer ctx.Done() // Construct poll request. pollReq, _ := http.NewRequest("POST", "https://github.com/login/oauth/access_token", nil) pollReq.Header.Add("Accept", "application/json") // Add parameters to poll request. params := pollReq.URL.Query() params.Add("client_id", GitHubClientID) params.Add("device_code", g.query.DeviceCode) params.Add("grant_type", "urn:ietf:params:oauth:grant-type:device_code") // Construct poll response. pollResp := &GitHubAppAuthPoll{} // Encode request pollReq.URL.RawQuery = params.Encode() // Launch request _, err = g.client.Do(ctx, pollReq, pollResp) if err != nil { return "", err } // Set token on successful auth. if pollResp.AccessToken != "" { g.token = pollResp.AccessToken } return pollResp.Error, nil } func (g *GitHubGuard) GetUser() (string, error) { ctx := context.Background() defer ctx.Done() tokenSource := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: g.token}, ) client := github.NewClient(oauth2.NewClient(ctx, tokenSource)) // Construct user request to get the name of the current logged in user. req, _ := http.NewRequest("GET", "https://api.github.com/user", nil) user := &github.User{} // Launch request _, err := client.Do(ctx, req, user) if err != nil { return "", err } return *user.Login, nil } func (g *GitHub) HaveWriteAccess(token string, url url.URL) (bool, error) { // Setup GitHub client ctx := context.Background() defer ctx.Done() tokenSource := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) client := github.NewClient(oauth2.NewClient(ctx, tokenSource)) username, err := getUsername(client) if err != nil { return false, err } // Check a user's given permission level for a repository on GitHub. perm, resp, err := client.Repositories.GetPermissionLevel( ctx, filepath.Base(filepath.Dir(url.Path)), filepath.Base(url.Path), username, ) if resp != nil && resp.Response.StatusCode != 200 { return false, err } return *perm.Permission == "admin" || *perm.Permission == "write", nil } func (g *GitHub) Fork(token string, url url.URL) (string, error) { // Setup GitHub client ctx := context.Background() defer ctx.Done() tokenSource := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) client := github.NewClient(oauth2.NewClient(ctx, tokenSource)) username, err := getUsername(client) if err != nil { return "", err } // Check for the existence of the fork before attempting to create one remoteRepo, _, err := client.Repositories.Get( ctx, username, filepath.Base(url.Path), ) if err != nil { remoteRepo, response, err := client.Repositories.CreateFork( ctx, filepath.Base(filepath.Dir(url.Path)), filepath.Base(url.Path), nil, ) if remoteRepo == nil || response.StatusCode != 202 && response.StatusCode != 200 { return "", err } } return remoteRepo.GetHTMLURL(), nil } func getUsername(client *github.Client) (string, error) { // Setup GitHub client ctx := context.Background() defer ctx.Done() // Construct user request to get the name of the current logged in user. req, _ := http.NewRequest("GET", "https://api.github.com/user", nil) user := &github.User{} // Launch request _, err := client.Do(ctx, req, user) if err != nil { return "", err } return *user.Login, nil } // OpenPR opens a pull request from the input branch to the destination branch. func (g *GitHub) OpenPR(opts PrOpts) (err error) { ctx := context.Background() ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: opts.Token}, ) tc := oauth2.NewClient(ctx, ts) client := github.NewClient(tc) forkOwner := filepath.Base(filepath.Dir(opts.Fork.Path)) pr := &github.NewPullRequest{ Title: github.String(opts.PrTitle), Body: github.String(opts.PrBody), Head: github.String(fmt.Sprintf("%s:%s", forkOwner, opts.PrBranch)), Base: github.String(opts.MainBranch), MaintainerCanModify: github.Bool(true), } repoOwner := filepath.Base(filepath.Dir(opts.Origin.Path)) repoName := filepath.Base(opts.Origin.Path) _, _, err = client.PullRequests.Create(ctx, repoOwner, repoName, pr) return err } // SearchPrByBranch checks to see if there is an existing PR based on a specific branch // and if so returns the name. func (g *GitHub) SearchPrByBranch(url url.URL, token, branchName string) (err error) { ctx := context.Background() ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(ctx, ts) client := github.NewClient(tc) result, _, err := client.Search.Issues( ctx, fmt.Sprintf( "head:%s type:pr repo:%s/%s", branchName, filepath.Dir(url.Path), filepath.Base(url.Path), ), &github.SearchOptions{}) if err != nil { return err } if len(result.Issues) > 0 { for _, issue := range result.Issues { if issue.GetState() == "open" { return nil } } } return errors.New("not found") } <file_sep>package manifest import ( "bufio" "os" "path/filepath" "strings" ) func (m *Manifest) Search(path string) (map[string][]string, error) { // Create hashes map to hold results hashes := make(map[string][]string) // Define the file's category to improve search times. category := filepath.Dir(path) base := filepath.Base(path) err := filepath.Walk(m.path, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, category+".ks") { file, err := os.Open(path) if err != nil { return err } scanner := bufio.NewScanner(file) // Scan through the lines in the file. for scanner.Scan() { // Split data on white space. data := strings.Fields(scanner.Text()) if matched, _ := filepath.Match(base, data[1]); matched { if hashes[data[1]] == nil { hashes[data[1]] = []string{} } hashes[data[1]] = append(hashes[data[1]], data[0]) } } } return nil }) return hashes, err } <file_sep>package cli import ( "fmt" "log" "os" "os/user" "path/filepath" "sync" "time" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" ) // AddedFilesPath is the file cache location. const AddedFilesPath string = ".ark/added_files" //GlobalFlags contains the flags for commands. type GlobalFlags struct { Config string `short:"c" long:"config" desc:"Specify a custom config path."` Verbose bool `short:"v" long:"verbose" desc:"Show More Information"` } var Root = &cmd.Root{ Name: "ark", Short: "The Arken command-line client.", Version: config.Version, License: "Licensed under the Apache License, Version 2.0", Flags: &GlobalFlags{}, } // rootInit initializes the main application config // from the root global flag location. func rootInit(r *cmd.Root) *GlobalFlags { // Parse Root Flags rFlags := r.Flags.(*GlobalFlags) // Construct config path var path string if rFlags.Config != "" { path = rFlags.Config } else { user, err := user.Current() checkError(rFlags, err) path = filepath.Join(user.HomeDir, ".ark", "config.toml") rFlags.Config = path } // Initialize config from path location err := config.Init(path) checkError(rFlags, err) // Return setup root flags return rFlags } // checkError checks an error and returns either a pretty // or debug error report based on the verbosity of the // application. func checkError(flags *GlobalFlags, err error) { if err != nil { if flags.Verbose { log.Fatal(err) } fmt.Println(err) os.Exit(1) } } // spinner is an array of the progression of the spinner. var spinner = []string{"|", "/", "-", "\\"} // spinnerWait displays a spinner which should be done in a // separate go routine. func spinnerWait(done <-chan int, message string, wg *sync.WaitGroup) { ticker := time.NewTicker(time.Millisecond * 128) frameCounter := 0 for range ticker.C { select { case <-done: wg.Done() ticker.Stop() return default: <-ticker.C ind := frameCounter % len(spinner) fmt.Printf("\r[%v] "+message, spinner[ind]) frameCounter++ } } } <file_sep>package manifest import ( "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing/transport/http" ) // Push performs a "git push" on the repository. func (m *Manifest) Push() (err error) { h, err := m.r.Head() if err != nil { return err } // Generate <src>:<dest> reference string refStr := h.Name().String() + ":" + h.Name().String() // Push Branch to Origin err = m.r.Push(&git.PushOptions{ RemoteName: "fork", RefSpecs: []config.RefSpec{config.RefSpec(refStr)}, Auth: &http.BasicAuth{ Username: m.gitOpts.Username, Password: m.gitOpts.Token, }, }) return err } <file_sep># How to Contribute to the Ark Application If you're looking for a place to start, go to the issues tab after reading this document and help add a new feature or fix a bug. If there aren't any issues we're always looking for people to test the commandline tool or find important open source data to upload to the [Arken Project Core Repository](https://github.com/arken/core-manifest). ## What's a manifest anyway? A manifest is like a ship's manifest. It contains a list of all the file names & IPFS identifiers of the files to be added to an Arken cluster WITHOUT actually containing any of the files' raw data. A manifest repository is made up of manifest (or keyset) files which look like this, ##### node.ks ``` plain QmYyLws3LmM85EfgNrEgGENoG8LPcKnZHR87A7BbgFqKsf NODE_VOL_01.pdf QmRRhKLebvXztobrhJifNLVgQJA4TDfv1tQV9RsVoLnsS4 NODE_VOL_02.pdf ``` While using Ark, a user should **never** directly deal with a manifest file or repository. All files should be generated automatically and handled in the background of a publish command run. Researchers/users should only care about their data and not have to also deal with manifest files themselves. ## Project Conventions - Code should be formatted using Go standard conventions. Use `go fmt -s` for linting. - Minimize the number of unnecessary public functions. - Write tests for all added functions to test expected functionality. - Start function comments with the name of the function. <file_sep>package manifest import ( "errors" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" ) // CreateBranch creates a new branch within the input // repository. func (m *Manifest) CreateBranch(branchName string) (err error) { h, err := m.r.Head() if err != nil { return err } ref := plumbing.NewHashReference(plumbing.NewBranchReferenceName(branchName), h.Hash()) err = m.r.Storer.SetReference(ref) return err } // GetBranchName returns the name of the current branch. func (m *Manifest) GetBranchName() (name string, err error) { h, err := m.r.Head() if err != nil { return name, err } name = strings.TrimPrefix(h.Name().String(), "refs/heads/") return name, nil } // SwitchBranch switches from the current branch to the // one with the name provided. func (m *Manifest) SwitchBranch(branchName string) (err error) { w, err := m.r.Worktree() if err != nil { return err } branchRef := plumbing.NewBranchReferenceName(branchName) opts := &git.CheckoutOptions{Branch: branchRef} err = w.Checkout(opts) return err } // PullBranch attempts to pull the branch from the git origin fork. func (m *Manifest) PullBranch(branchName string) (err error) { localBranchReferenceName := plumbing.NewBranchReferenceName(branchName) remoteReferenceName := plumbing.NewRemoteReferenceName("fork", branchName) rem, err := m.r.Remote("fork") if err != nil { return err } refs, err := rem.List(&git.ListOptions{}) if err != nil { return err } found := false for _, ref := range refs { if ref.Name().IsBranch() && ref.Name() == localBranchReferenceName { found = true } } if !found { return errors.New("branch not found") } err = m.r.CreateBranch(&config.Branch{Name: branchName, Remote: "origin", Merge: localBranchReferenceName}) if err != nil { return err } newReference := plumbing.NewSymbolicReference(localBranchReferenceName, remoteReferenceName) err = m.r.Storer.SetReference(newReference) return err } <file_sep>package cli import ( "bufio" "bytes" "fmt" "io" "os" "github.com/DataDrake/cli-ng/v2/cmd" ) func init() { cmd.Register(&Status) } // Status prints out what files are currently staged for submission. var Status = cmd.Sub{ Name: "status", Alias: "s", Short: "View what files are currently staged for submission.", Args: &StatusArgs{}, Run: StatusRun, } // StatusArgs handles the specific arguments for the status command. type StatusArgs struct { } // StatusRun handles the execution of the status command. func StatusRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist notify the user to run // ark init() first. if os.IsNotExist(err) || !info.IsDir() { fmt.Printf("This is not an Ark repository! Please run\n\n" + " ark init\n\n" + "Before attempting to and any files.\n", ) os.Exit(1) } // Open previous cache if exists f, err := os.Open(AddedFilesPath) if err != nil && os.IsNotExist(err) { fmt.Println(0, "file(s) currently staged for submission") return } checkError(rFlags, err) defer f.Close() lines, err := lineCounter(f) checkError(rFlags, err) _, err = f.Seek(0, 0) checkError(rFlags, err) fmt.Println(lines, "file(s) currently staged for submission") if lines <= 50 { scanner := bufio.NewScanner(f) for scanner.Scan() { if len(scanner.Text()) > 0 { fmt.Println("\t", scanner.Text()) } } } } // efficient lineCounter function from // https://stackoverflow.com/a/24563853 func lineCounter(r io.Reader) (int, error) { buf := make([]byte, 32*1024) count := 0 lineSep := []byte{'\n'} for { c, err := r.Read(buf) count += bytes.Count(buf[:c], lineSep) switch { case err == io.EOF: return count, nil case err != nil: return count, err } } } <file_sep>package cli import ( "bufio" "fmt" "io" "math" "net/url" "os" "os/exec" "path/filepath" "strings" "time" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" "github.com/arken/ark/ipfs" "github.com/arken/ark/manifest" "github.com/arken/ark/manifest/upstream" "github.com/arken/ark/parser" "github.com/schollz/progressbar/v3" ) func init() { cmd.Register(&Submit) } // Submit creates a manifest file and uploads it to the destination git repository. var Submit = cmd.Sub{ Name: "submit", Alias: "sb", Short: "Submit your files to a manifest repository.", Args: &SubmitArgs{}, Flags: &SubmitFlags{}, Run: SubmitRun, } // SubmitArgs handles the specific arguments for the submit command. type SubmitArgs struct { Manifest string } // SubmitFlags handles the specific flags for the submit command. type SubmitFlags struct { IsPR bool `short:"p" long:"pull-request" desc:"Jump straight into submitting a pull request"` } // SubmitRun authenticates the user through our OAuth app and uses that to // upload a manifest file generated locally, or makes a pull request if necessary. func SubmitRun(r *cmd.Root, c *cmd.Sub) { // +--------------------+ // | Setup Command | // +--------------------+ // Setup main application config. rFlags := rootInit(r) // Parse upload args args := c.Args.(*SubmitArgs) // Parse upload args flags := c.Flags.(*SubmitFlags) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist notify the user to run // ark init() first. if os.IsNotExist(err) || !info.IsDir() { fmt.Printf("This is not an Ark repository! Please run\n\n" + " ark init\n\n" + "Before attempting to upload any files.\n", ) os.Exit(1) } // Open previous cache if exists f, err := os.Open(AddedFilesPath) if err != nil && os.IsNotExist(err) { fmt.Println("No files are currently added, nothing to submit. Use") fmt.Println(" ark add <files>...") fmt.Println("to add files for submission.") return } checkError(rFlags, err) defer f.Close() // Swap out an alias for the corresponding url alias, ok := config.Global.Manifest.Aliases[args.Manifest] if ok { args.Manifest = alias } // +--------------------+ // | Check Git Info | // +--------------------+ if config.Global.Git.Email == "" || config.Global.Git.Name == "" { err = queryUserSaveGitInfo() checkError(rFlags, err) err = config.WriteFile(rFlags.Config, &config.Global) checkError(rFlags, err) } // +--------------------+ // | Load Auth | // +--------------------+ if config.Global.Git.Token == "" { // Give the user a chance to change the account they logged in with // if it was incorrect. correctUser := false var guard upstream.Guard for !correctUser { // Launch upstream auth workflow if local Git Token is empty. guard, err = manifest.Auth(args.Manifest) if err != nil && err.Error() == "unknown upstream" { fmt.Println("Error: Ark was unable to identify a known upstream") fmt.Println("for your repository. Please use,") fmt.Println("\t\"ark config git.token YOUR-VALUE\"") fmt.Println("to set your git token manually before retrying") fmt.Println("your submission without -p") } checkError(rFlags, err) // Print out message to user about device code. printAuthCode(guard.GetCode(), guard.GetExpireInterval()) // Begin polling process for authorization interval := time.Duration(guard.GetInterval()) * time.Second for { wait(interval) status, err := guard.CheckStatus() checkError(rFlags, err) if status == "slow_down" { interval = interval + 5*time.Second continue } if status != "authorization_pending" { break } } fmt.Print("\r") username, err := guard.GetUser() checkError(rFlags, err) correctUser = queryUserCorrect(username) fmt.Println() } // Save access information to internal memory config.Global.Git.Username, _ = guard.GetUser() config.Global.Git.Token = guard.GetAccessToken() // Ask the user if they would like to save their git credentials saveCreds := queryUserSaveCreds() if saveCreds { err = config.WriteFile(rFlags.Config, &config.Global) checkError(rFlags, err) } } // +--------------------+ // | Load Manifest | // +--------------------+ // Parse manifest url urlPath, err := url.Parse(args.Manifest) checkError(rFlags, err) // Extract manifest name from url manifestName := filepath.Base(urlPath.Path) // Generate internal manifest path from name manifestPath := filepath.Join(config.Global.Manifest.Path, manifestName) // Initialize Manifest manifest, err := manifest.Init( filepath.Join(manifestPath, "manifest"), args.Manifest, manifest.GitOptions{ Name: config.Global.Git.Name, Username: config.Global.Git.Username, Email: config.Global.Git.Email, Token: config.Global.Git.Token, }, ) checkError(rFlags, err) // +--------------------+ // | Display App | // +--------------------+ var app parser.Application overwriteOpt := "" for overwriteOpt != "o" && overwriteOpt != "a" { // Construct application path appPath := filepath.Join(".ark", "commit") // Check if an application is already in progress. _, err = os.Stat(appPath) if err != nil && os.IsNotExist(err) { new, err := os.Create(appPath) checkError(rFlags, err) _, err = new.WriteString(parser.SubmissionTemplate) checkError(rFlags, err) } // Show the user their application in their preferred editor cmd := exec.Command(config.Global.Core.Editor, appPath) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout err = cmd.Run() checkError(rFlags, err) appFile, err := os.Open(appPath) checkError(rFlags, err) buf, err := io.ReadAll(appFile) checkError(rFlags, err) appFile.Close() app, err = parser.ParseApplication(string(buf)) checkError(rFlags, err) // Check for existing file prevPath := filepath.Join( config.Global.Manifest.Path, manifestName, "manifest", app.Category, app.Filename, ) _, err = os.Stat(prevPath) if err == nil { overwriteOpt = queryUserAppendFile( filepath.Join(app.Category, app.Filename), ) continue } overwriteOpt = "o" } // +--------------------+ // | Load IPFS Node | // +--------------------+ // Create internal IPFS node ipfs, err := ipfs.CreateNode( filepath.Join(manifestPath, "ipfs"), ipfs.NodeConfArgs{ SwarmKey: manifest.ClusterKey, BootstrapPeers: manifest.BootstrapPeers, }, ) checkError(rFlags, err) // +--------------------+ // | Generate Manifest | // +--------------------+ // Count the number of files in the cache numFiles, err := lineCounter(f) checkError(rFlags, err) _, err = f.Seek(0, 0) checkError(rFlags, err) // In order to not copy files to ~/.ark/ipfs/ // we need to create a workdir symlink in .ark wd, err := os.Getwd() checkError(rFlags, err) link := filepath.Join(config.Global.Manifest.Path, manifestName, "workdir") err = os.Symlink(wd, link) if err != nil && os.IsExist(err) { os.Remove(link) err = os.Symlink(wd, link) } checkError(rFlags, err) // Create manifest map files := make(map[string]string, numFiles) if overwriteOpt == "a" { // Check for existing file prevPath := filepath.Join( config.Global.Manifest.Path, manifestName, "manifest", app.Category, app.Filename, ) prev, err := os.Open(prevPath) if err == nil { scanner := bufio.NewScanner(prev) for scanner.Scan() { data := strings.Fields(scanner.Text()) files[data[0]] = data[1] } } prev.Close() } fmt.Println("Building Manifest...") // Generate progress bar ipfsBar := progressbar.Default(int64(numFiles)) ipfsBar.RenderBlank() // Add files to internal ipfs node scanner := bufio.NewScanner(f) for scanner.Scan() { cid, err := ipfs.Add(filepath.Join(link, scanner.Text()), true) checkError(rFlags, err) // Add file to map. files[cid] = scanner.Text() ipfsBar.Add(1) } // Remove Symlink to Working Directory err = os.Remove(link) checkError(rFlags, err) // Construct destination manifest path manPath := filepath.Join( config.Global.Manifest.Path, manifestName, "manifest", app.Category, app.Filename, ) // +--------------------+ // | Upload Manifest | // +--------------------+ // Add place holders for PRs to use branches. var mainBranchName string var newBranchName string // Check if we should push direct to // the git repository or attempt to create a pull request. haveWrite, err := manifest.HaveWriteAccess() if err != nil && err.Error() != "unknown upstream" { checkError(rFlags, err) } if !haveWrite || flags.IsPR { // Force status to a PR if we don't have // write access to the repository. flags.IsPR = true // Setup a repository fork when creating a PR. err = manifest.Fork() checkError(rFlags, err) // Store main git branch name mainBranchName, err = manifest.GetBranchName() checkError(rFlags, err) // Construct a new branch name newBranchName = "submit/" + app.Filename // Pull an existing branch to update if possible. err = manifest.PullBranch(newBranchName) if err != nil { if err.Error() == "branch not found" { err = manifest.CreateBranch(newBranchName) } checkError(rFlags, err) } err = manifest.SwitchBranch(newBranchName) checkError(rFlags, err) } // Make destination manifest path err = os.MkdirAll(filepath.Dir(manPath), os.ModePerm) checkError(rFlags, err) // Create manifest file new, err := os.Create(manPath) checkError(rFlags, err) defer new.Close() // Generate manifest content from map. out, err := manifest.Generate(files) checkError(rFlags, err) // Write manifest to file _, err = new.WriteString(out) checkError(rFlags, err) // Close manifest file. err = new.Close() checkError(rFlags, err) // Commit changes to repository. err = manifest.Commit(manPath, app.Commit) checkError(rFlags, err) // Push changes to repository. err = manifest.Push() checkError(rFlags, err) // Open a PR if one doesn't already exist. if flags.IsPR { err := manifest.SearchPrByBranch(newBranchName) if err != nil { err = manifest.OpenPR(mainBranchName, app.Title, app.PRBody) checkError(rFlags, err) } // Switch back to the main manifest branch err = manifest.SwitchBranch(mainBranchName) checkError(rFlags, err) } fmt.Println("Completed Submission Successfully!") f.Close() os.Remove(filepath.Join(".ark", "commit")) } // printAuthCode prints the user's code in a pretty format. func printAuthCode(code string, expiry int) { now := time.Now() expireTime := now.Add(time.Duration(expiry) * time.Second) minutes := math.Round(float64(expiry) / 60.0) fmt.Printf( `Go to https://github.com/login/device and enter the following code. You should see a request to authorize "Ark GitHub Worker". Please authorize this request, but not if it's from anyone other than Ark GitHub Worker by Arken! ================================================================= %v ================================================================= This code will expire in about %v minutes at %v. `, code, int(minutes), expireTime.Format("3:04 PM")) } // wait prints a pretty little animation while Ark waits for the user's to // authenticate the app for an Upstream. func wait(length time.Duration) { seconds := int(length.Seconds()) ticker := time.NewTicker(time.Second) for i := 0; i < seconds; i++ { fmt.Printf("\r[%v] Checking in %v second(s)...", spinner[i%len(spinner)], seconds-i) <-ticker.C } ticker.Stop() } func queryUserCorrect(user string) bool { fmt.Println("Successfully authenticated as user", user) fmt.Printf("Is this correct? ([y]/n) ") // Collect input from user. reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') input = strings.ToLower(strings.TrimSpace(input)) // Validate user accepted logged in status. return input != "n" && input != "no" } func queryUserSaveCreds() bool { fmt.Print("\nWould you like to save your access token for future submissions? (y/[n]) ") reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') input = strings.ToLower(strings.TrimSpace(input)) return input == "y" || input == "yes" } func queryUserAppendFile(filePath string) string { fmt.Printf("\nA file already exists at %v in the repo.\n", filePath) fmt.Println("Do you want to overwrite it (o), append to it (a), rename yours (r),") fmt.Print("or abort (any other key)? ") reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') input = strings.ToLower(strings.TrimSpace(input)) return input } func queryUserSaveGitInfo() error { reader := bufio.NewReader(os.Stdin) fmt.Print("You don't appear to have an identity saved.\n" + "Please enter your name (spaces are ok): ") input, _ := reader.ReadString('\n') config.Global.Git.Name = strings.TrimSpace(input) fmt.Print("Please enter your email: ") input, _ = reader.ReadString('\n') config.Global.Git.Email = strings.TrimSpace(input) return nil } <file_sep>package cli import ( "bufio" "fmt" "os" "path/filepath" "sort" "strings" "github.com/DataDrake/cli-ng/v2/cmd" ) func init() { cmd.Register(&Remove) } // Add stages a file or set of files for a submission. var Remove = cmd.Sub{ Name: "remove", Alias: "rm", Short: "Remove a file from the internal submission cache.", Args: &RemoveArgs{}, Run: RemoveRun, } // RemoveArgs handles the specific arguments for the remove command. type RemoveArgs struct { Paths []string } // RemoveRun removes file from the submission cache. func RemoveRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist notify the user to run // ark init() first. if os.IsNotExist(err) || !info.IsDir() { fmt.Printf("This is not an Ark repository! Please run\n\n" + " ark init\n\n" + "Before attempting to remove any files.\n", ) os.Exit(1) } // Initialize file cache and paths from args fileCache := make(map[string]bool) argPaths := c.Args.(*RemoveArgs).Paths // Open previous cache if exists f, err := os.Open(AddedFilesPath) if err == nil { // Import existing cache from file. scanner := bufio.NewScanner(f) for scanner.Scan() { if len(scanner.Text()) > 0 { fileCache[scanner.Text()] = true } } f.Close() } // Iterate through paths to check they exist // if adding a dir add all sub files within that dir. for _, path := range argPaths { stat, err := os.Stat(path) checkError(rFlags, err) // Walk through a directory and add all children files. if stat.IsDir() { filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { delete(fileCache, path) } return nil }) } else { delete(fileCache, path) } } // Create a string of the keys of the cache map. keys := make([]string, 0, len(fileCache)) for k := range fileCache { keys = append(keys, k) } // Sort output cache for readability sort.Strings(keys) if len(keys) > 0 { f, err = os.Create(AddedFilesPath) checkError(rFlags, err) defer f.Close() // Write out cache to file. _, err = f.WriteString(strings.Join(keys, "\n") + "\n") checkError(rFlags, err) } else { err = os.Remove(AddedFilesPath) checkError(rFlags, err) } } <file_sep>package manifest import ( "path/filepath" "github.com/BurntSushi/toml" "github.com/go-git/go-git/v5" ) type Manifest struct { Name string `toml:"name,omitempty"` BootstrapPeers []string `toml:"bootstrap_peers,omitempty"` ClusterKey string `toml:"cluster_key,omitempty"` Replications int64 `toml:"replications,omitempty"` StatsNode string `toml:"stats_node,omitempty"` url string `toml:"url"` forkUrl string path string `toml:"path"` r *git.Repository gitOpts GitOptions } type GitOptions struct { Name string Username string Token string Email string } // Init Clones/Pulls a Manifest Repository and Parses the Config func Init(path, url string, opts GitOptions) (*Manifest, error) { var err error // Initialize Manifest Struct result := Manifest{ path: path, url: url, gitOpts: opts, } // Check if Git Repository Exists result.r, err = git.PlainOpen(path) if err != nil && err.Error() == "repository does not exist" { result.r, err = git.PlainClone(path, false, &git.CloneOptions{ URL: url, }) } if err != nil { return nil, err } // Pull in new changes from the manifest err = result.Pull() if err != nil { return nil, err } // Decode local manifest config from repository err = result.Decode() return &result, err } // Decode Manifest Configuration from Manifest Repository func (m *Manifest) Decode() error { _, err := toml.DecodeFile(filepath.Join(m.path, "config.toml"), m) return err } <file_sep>package manifest import ( "errors" "net/url" "github.com/arken/ark/manifest/upstream" ) func (m *Manifest) OpenPR(mainBranch, prTitle, prBody string) error { url, err := url.Parse(m.url) if err != nil { return err } // Check for matching upstream. up, ok := upstream.AvailableUpstreams[url.Host] if !ok { return errors.New("unknown upstream") } fork, err := url.Parse(m.forkUrl) if err != nil { return err } prBranch, err := m.GetBranchName() if err != nil { return err } opts := upstream.PrOpts{ Origin: *url, Fork: *fork, Token: m.gitOpts.Token, MainBranch: mainBranch, PrBranch: prBranch, PrTitle: prTitle, PrBody: prBody, } // Attempt to open a PR using the found upstream. return up.OpenPR(opts) } func (m *Manifest) SearchPrByBranch(branchName string) error { url, err := url.Parse(m.url) if err != nil { return err } // Check for matching upstream. upstream, ok := upstream.AvailableUpstreams[url.Host] if !ok { return errors.New("unknown upstream") } return upstream.SearchPrByBranch(*url, m.gitOpts.Token, branchName) } <file_sep>package config import ( "bytes" "os" "path/filepath" "reflect" "strings" "github.com/BurntSushi/toml" ) var ( // Version is the current version of Arken Version string = "develop" // Global is the global application configuration Global Config ) type Config struct { Core core `toml:"core"` Manifest manifest `toml:"manifest"` Git git `toml:"git"` } type core struct { Editor string `toml:"editor"` } type git struct { Name string `toml:"name"` Username string `toml:"username"` Email string `toml:"email"` Token string `toml:"token"` } type manifest struct { Path string `toml:"path"` Aliases map[string]string `toml:"aliases"` } func Init(path string) error { // Generate the default config Global = Config{ Core: core{ Editor: "nano", }, Manifest: manifest{ Path: filepath.Join(filepath.Dir(path), "manifest"), Aliases: make(map[string]string), }, Git: git{ Name: "", Email: "", Token: "", }, } // Setup default alias for core-manifest Global.Manifest.Aliases["core"] = "https://github.com/arken/core-manifest" // Read in config from file err := ParseFile(path, &Global) if err != nil && !os.IsNotExist(err) { return err } // Read in config from environment err = sourceEnv(&Global) if err != nil { return err } // Write config file err = WriteFile(path, &Global) return err } // ParseFile decodes the application configuration // from the TOML encoded file at the specified path. func ParseFile(path string, in *Config) error { _, err := toml.DecodeFile(path, in) return err } func sourceEnv(in *Config) error { numSubStructs := reflect.ValueOf(in).Elem().NumField() // Check for env args matching each of the sub structs. for i := 0; i < numSubStructs; i++ { iter := reflect.ValueOf(in).Elem().Field(i) subStruct := strings.ToUpper(iter.Type().Name()) structType := iter.Type() for j := 0; j < iter.NumField(); j++ { fieldVal := iter.Field(j).String() fieldName := structType.Field(j).Name evName := "ARK" + "_" + subStruct + "_" + strings.ToUpper(fieldName) evVal, evExists := os.LookupEnv(evName) if evExists && evVal != fieldVal { iter.FieldByName(fieldName).SetString(evVal) } } } return nil } // WriteFile writes changes to the application configuration back // to the TOML encoded file. func WriteFile(path string, in *Config) error { buf := new(bytes.Buffer) err := toml.NewEncoder(buf).Encode(in) if err != nil { return err } err = os.WriteFile(path, buf.Bytes(), os.ModePerm) if os.IsNotExist(err) { err = os.MkdirAll(filepath.Dir(path), os.ModePerm) if err != nil { return err } err = os.WriteFile(path, buf.Bytes(), os.ModePerm) } return err } <file_sep>package upstream import "net/url" var AvailableUpstreams map[string]Upstream type Upstream interface { Auth(path string) (result Guard, err error) HaveWriteAccess(token string, url url.URL) (hasAccess bool, err error) Fork(token string, url url.URL) (result string, err error) OpenPR(opts PrOpts) (err error) SearchPrByBranch(url url.URL, token, branchName string) (err error) } type Guard interface { GetAccessToken() (token string) GetCode() (code string) GetInterval() (interval int) GetExpireInterval() (interval int) CheckStatus() (status string, err error) GetUser() (username string, err error) } type PrOpts struct { Origin url.URL Fork url.URL Token string MainBranch string PrBranch string PrTitle string PrBody string } func registerUpstream(upstream Upstream, host string) { if AvailableUpstreams == nil { AvailableUpstreams = make(map[string]Upstream) } AvailableUpstreams[host] = upstream } <file_sep>package cli import ( "fmt" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" ) func init() { cmd.Register(&Alias) } // Alias creates a custom alias mapping in Ark. var Alias = cmd.Sub{ Name: "alias", Alias: "a", Short: "Create a shortcut for a manifest URL.", Args: &AliasArgs{}, Flags: &AliasFlags{}, Run: AliasRun, } // AliasArgs handles the specific arguments for the alias command. type AliasArgs struct { Shortcut string URL []string `zero:"true"` } // AliasFlags handles the specific flags for the alias command. type AliasFlags struct { Delete bool `short:"d" long:"delete" desc:"delete an alias shortcut."` } // AliasRun creates a custom alias mapping for a manifest url. func AliasRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) args := c.Args.(*AliasArgs) flags := c.Flags.(*AliasFlags) // Setup temporary configuration. cfg := config.Config{} // Parse configuration file. err := config.ParseFile(rFlags.Config, &cfg) checkError(rFlags, err) if len(args.URL) > 0 { cfg.Manifest.Aliases[args.Shortcut] = args.URL[0] // Write changes back to config file. config.WriteFile(rFlags.Config, &cfg) } else { if flags.Delete { delete(cfg.Manifest.Aliases, args.Shortcut) // Write changes back to config file. config.WriteFile(rFlags.Config, &cfg) } else { fmt.Println(cfg.Manifest.Aliases[args.Shortcut]) } } } <file_sep>package cli import ( "bufio" "fmt" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" "github.com/arken/ark/ipfs" "github.com/arken/ark/manifest" files "github.com/ipfs/go-ipfs-files" ) func init() { cmd.Register(&Pull) } // Pull downloads files from an Arken cluster. var Pull = cmd.Sub{ Name: "pull", Alias: "pl", Short: "Pull a file from an Arken Cluster.", Args: &PullArgs{}, Run: PullRun, } // PullArgs handles the specific arguments for the pull command. type PullArgs struct { Manifest string Filepaths []string } // PullRun handles pulling and saving a file from an Arken cluster. func PullRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Parse command arguments. args := c.Args.(*PullArgs) // Get current working directory currentwd, err := os.Getwd() checkError(rFlags, err) // Swap out an alias for the corresponding url alias, ok := config.Global.Manifest.Aliases[args.Manifest] if ok { args.Manifest = alias } // Parse manifest url urlPath, err := url.Parse(args.Manifest) checkError(rFlags, err) // Extract manifest name from url manifestName := filepath.Base(urlPath.Path) // Generate internal manifest path from name manifestPath := filepath.Join(config.Global.Manifest.Path, manifestName) // Initialize Manifest manifest, err := manifest.Init( filepath.Join(manifestPath, "manifest"), args.Manifest, manifest.GitOptions{}, ) checkError(rFlags, err) // Create internal IPFS node for manifest ipfs, err := ipfs.CreateNode( filepath.Join(manifestPath, "ipfs"), ipfs.NodeConfArgs{ SwarmKey: manifest.ClusterKey, BootstrapPeers: manifest.BootstrapPeers, }, ) checkError(rFlags, err) for _, path := range args.Filepaths { results, err := manifest.Search(path) checkError(rFlags, err) for filename, cids := range results { i := 0 if len(cids) > 1 { fmt.Printf("There is more than 1 file with the name: %s\n"+ "Which version would you like to download?\n", filename) fmt.Printf("Select a number between 0 - %d\n", len(cids)-1) for i, hash := range cids { fmt.Printf(" | %d - %s", i, hash) } reader := bufio.NewReader(os.Stdin) for { text, err := reader.ReadString('\n') checkError(rFlags, err) if strings.ToLower(text) == "exit" { return } i, err = strconv.Atoi(text) if err == nil && i >= 0 && i < len(cids) { break } fmt.Printf("Select a number between 0 - %d\n", len(cids)-1) } } // Display Spinner when pulling a file. doneChan := make(chan int, 1) wg := sync.WaitGroup{} wg.Add(1) go spinnerWait(doneChan, "Pulling "+filename+"...", &wg) // Pull file over IPFS file, err := ipfs.Get(cids[i]) checkError(rFlags, err) // Write IPFS file out to filesystem err = files.WriteTo(file, filepath.Join(currentwd, filename)) if err != nil { fmt.Printf("Could not write out the fetched CID: %s", err) os.Exit(1) } doneChan <- 0 wg.Wait() fmt.Println() close(doneChan) } } } <file_sep>package cli import ( "bufio" "fmt" "os" "path/filepath" "sort" "strings" "github.com/DataDrake/cli-ng/v2/cmd" ) func init() { cmd.Register(&Add) } // Add stages a file or set of files for a submission. var Add = cmd.Sub{ Name: "add", Alias: "ad", Short: "Stage a file for set of files for a submission.", Args: &AddArgs{}, Run: AddRun, } // AddArgs handles the specific arguments for the add command. type AddArgs struct { Paths []string } // AddRun stages a file within the current working directory for a later submission. func AddRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist notify the user to run // ark init() first. if os.IsNotExist(err) || !info.IsDir() { fmt.Printf("This is not an Ark repository! Please run\n\n" + " ark init\n\n" + "Before attempting to add any files.\n", ) os.Exit(1) } // Initialize file cache and paths from args fileCache := make(map[string]bool) argPaths := c.Args.(*AddArgs).Paths // Open previous cache if exists f, err := os.Open(AddedFilesPath) if err == nil { // Import existing cache from file. scanner := bufio.NewScanner(f) for scanner.Scan() { if len(scanner.Text()) > 0 { fileCache[scanner.Text()] = true } } f.Close() } // Iterate through paths to check they exist // if adding a dir add all sub files within that dir. for _, path := range argPaths { stat, err := os.Stat(path) checkError(rFlags, err) // Walk through a directory and add all children files. if stat.IsDir() { filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { fileCache[path] = true } return nil }) } else { fileCache[path] = true } } // Create a string of the keys of the cache map. keys := make([]string, 0, len(fileCache)) for k := range fileCache { keys = append(keys, k) } // Sort output cache for readability sort.Strings(keys) f, err = os.Create(AddedFilesPath) checkError(rFlags, err) defer f.Close() // Write out cache to file. _, err = f.WriteString(strings.Join(keys, "\n") + "\n") checkError(rFlags, err) } <file_sep>package cli import ( "bufio" "fmt" "net/url" "os" "path/filepath" "time" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" "github.com/arken/ark/ipfs" "github.com/arken/ark/manifest" "github.com/schollz/progressbar/v3" ) func init() { cmd.Register(&Upload) } // UploadArgs handles the specific arguments for the upload command. type UploadArgs struct { Manifest string } // Upload begins seeding your files to an Arken Cluster once your // submission into the Manifest has been merged into the repository. var Upload = cmd.Sub{ Name: "upload", Alias: "up", Short: "Upload files to an Arken cluster after an accepted submission.", Args: &UploadArgs{}, Run: UploadRun, } // UploadRun handles the uploading and display of the upload command. func UploadRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) // Parse upload args args := c.Args.(*UploadArgs) // Check if .ark directory already exists. info, err := os.Stat(".ark") // If .ark does not exist notify the user to run // ark init() first. if os.IsNotExist(err) || !info.IsDir() { fmt.Printf("This is not an Ark repository! Please run\n\n" + " ark init\n\n" + "Before attempting to upload any files.\n", ) os.Exit(1) } // +--------------------+ // | Load Manifest | // +--------------------+ // Swap out an alias for the corresponding url alias, ok := config.Global.Manifest.Aliases[args.Manifest] if ok { args.Manifest = alias } // Parse manifest url urlPath, err := url.Parse(args.Manifest) checkError(rFlags, err) // Extract manifest name from url manifestName := filepath.Base(urlPath.Path) // Generate internal manifest path from name manifestPath := filepath.Join(config.Global.Manifest.Path, manifestName) // Initialize Manifest manifest, err := manifest.Init( filepath.Join(manifestPath, "manifest"), args.Manifest, manifest.GitOptions{}, ) checkError(rFlags, err) // +--------------------+ // | Load IPFS Node | // +--------------------+ ipfs, err := ipfs.CreateNode( filepath.Join(manifestPath, "ipfs"), ipfs.NodeConfArgs{ SwarmKey: manifest.ClusterKey, BootstrapPeers: manifest.BootstrapPeers, }, ) checkError(rFlags, err) // Open previous cache if exists f, err := os.Open(AddedFilesPath) if err != nil && os.IsNotExist(err) { fmt.Println(0, "file(s) currently staged for submission & upload") fmt.Println("Are you in the correct directory?") return } checkError(rFlags, err) defer f.Close() // Count the number of files in the manifest numFiles, err := lineCounter(f) checkError(rFlags, err) _, err = f.Seek(0, 0) checkError(rFlags, err) // In order to not copy files to ~/.ark/ipfs/ // we need to create a workdir symlink in .ark wd, err := os.Getwd() checkError(rFlags, err) link := filepath.Join(config.Global.Manifest.Path, manifestName, "workdir") err = os.Symlink(wd, link) if err != nil && os.IsExist(err) { os.Remove(link) err = os.Symlink(wd, link) } checkError(rFlags, err) input := make(chan string, numFiles) // Add files to internal ipfs node go func() { scanner := bufio.NewScanner(f) for scanner.Scan() { cid, err := ipfs.Add(filepath.Join(link, scanner.Text()), false) checkError(rFlags, err) input <- cid } }() // Display progress bar for uploads. fmt.Println("Uploading Files to Cluster") ipfsBar := progressbar.Default(int64(numFiles)) ipfsBar.RenderBlank() go func(bar *progressbar.ProgressBar, input chan string) { for cid := range input { replications, err := ipfs.FindProvs(cid, 20) checkError(rFlags, err) if rFlags.Verbose { fmt.Printf("\nFile: %s is backed up %d time(s)\n", cid, replications) } if replications > 2 { bar.Add(1) } else { bar.Add(0) input <- cid } if replications == 0 { err = ipfs.Pin(cid) checkError(rFlags, err) } } }(ipfsBar, input) for { if ipfsBar.State().CurrentPercent == float64(1) { close(input) err = os.Remove(link) checkError(rFlags, err) break } ipfsBar.Add(0) time.Sleep(1000 * time.Millisecond) } } <file_sep>package manifest import ( "time" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing/object" ) // Commit performs a git commit on the repository. func (m *Manifest) Commit(path, commitMessage string) (err error) { w, err := m.r.Worktree() if err != nil { return err } _, err = w.Add(".") if err != nil { return err } commit, err := w.Commit(commitMessage, &git.CommitOptions{ Author: &object.Signature{ Name: m.gitOpts.Name, Email: m.gitOpts.Email, When: time.Now(), }, }) if err != nil { return err } _, err = m.r.CommitObject(commit) if err != nil { return err } return nil } <file_sep>package manifest import ( "github.com/go-git/go-git/v5" ) // Pull Performs a git pull on the repository func (m *Manifest) Pull() error { // Checkout the repository worktree w, err := m.r.Worktree() if err != nil { return err } // Check for updates to the Manifest Repository err = w.Pull(&git.PullOptions{RemoteName: "origin"}) if err != nil && err != git.NoErrAlreadyUpToDate { return err } return nil } <file_sep>package ipfs import ( "os" files "github.com/ipfs/go-ipfs-files" "github.com/ipfs/interface-go-ipfs-core/options" ) // Add imports a file to IPFS and returns the file identifier to Ark. func (n *Node) Add(path string, onlyHash bool) (cid string, err error) { file, err := getUnixfsNode(path) if err != nil { if file != nil { file.Close() } return cid, err } output, err := n.api.Unixfs().Add(n.ctx, file, func(input *options.UnixfsAddSettings) error { input.Pin = true input.NoCopy = true input.CidVersion = 1 input.OnlyHash = onlyHash return nil }) if err != nil { return cid, err } cid = output.Cid().String() file.Close() return cid, nil } func getUnixfsNode(path string) (files.Node, error) { st, err := os.Stat(path) if err != nil { return nil, err } f, err := files.NewSerialFile(path, false, st) if err != nil { return nil, err } return f, nil } <file_sep>package parser import ( "bufio" "errors" "path/filepath" "strings" ) // Application is a struct holding the application fields. type Application struct { Title string Commit string PRBody string Category string Filename string } func ParseApplication(input string) (Application, error) { app := Application{} scanner := bufio.NewScanner(strings.NewReader(input)) var ptr *string = nil // Fill out the struct with the contents of the file for scanner.Scan() { line := scanner.Text() if !strings.HasPrefix(line, "#") && ptr != nil { *ptr += line + " \n" } else if strings.HasPrefix(line, "# CATEGORY") { ptr = &app.Category } else if strings.HasPrefix(line, "# FILENAME") { ptr = &app.Filename } else if strings.HasPrefix(line, "# TITLE") { ptr = &app.Title } else if strings.HasPrefix(line, "# COMMIT") { ptr = &app.Commit } else if strings.HasPrefix(line, "# PULL REQUEST") { ptr = &app.PRBody } } // Trim whitespace from around fields app.Category = strings.TrimSpace(filepath.Clean(app.Category)) app.Commit = strings.TrimSpace(app.Commit) app.Filename = strings.TrimSpace(app.Filename) app.PRBody = strings.TrimSpace(app.PRBody) app.Title = strings.TrimSpace(app.Title) if !strings.HasSuffix(app.Filename, ".ks") { app.Filename += ".ks" } if strings.Contains(app.Category, "..") { return app, errors.New("path backtracking (\"..\") is not allowed in the category") } return app, nil } <file_sep>package ipfs import ( "context" "time" "github.com/ipfs/interface-go-ipfs-core/options" icorepath "github.com/ipfs/interface-go-ipfs-core/path" ) // FindProvs queries the IPFS network for the number of // providers hosting a given file func (n *Node) FindProvs(hash string, maxPeers int) (replications int, err error) { // Construct IPFS CID path := icorepath.New("/ipfs/" + hash) // Create a new context contxt, cancel := context.WithTimeout(n.ctx, 5*time.Second) defer cancel() // Lookup how many other nodes are hosting a file. output, err := n.api.Dht().FindProviders(contxt, path, options.Dht.NumProviders(maxPeers+15)) if err != nil { return -1, err } // Iterate through resulting responses and add them up. for range output { replications++ } return replications, nil } <file_sep>package main import ( "github.com/arken/ark/cli" ) func main() { // Build the command line interface for Ark cli.Root.Run() } <file_sep>package manifest import ( "errors" "net/url" "github.com/arken/ark/manifest/upstream" ) func Auth(path string) (result upstream.Guard, err error) { url, err := url.Parse(path) if err != nil { return nil, err } upstream, ok := upstream.AvailableUpstreams[url.Host] if !ok { return nil, errors.New("unknown upstream") } return upstream.Auth(path) } <file_sep>package cli import ( "fmt" "reflect" "strings" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/arken/ark/config" ) func init() { cmd.Register(&Config) } // Config updates a config value with Ark. var Config = cmd.Sub{ Name: "config", Alias: "c", Short: "Update an one of Ark's Configuration Values.", Args: &ConfigArgs{}, Run: ConfigRun, } // ConfigArgs handles the specific arguments for the config command. type ConfigArgs struct { Key string Value []string `zero:"true"` } // ConfigRun updates one of Ark's internal config values. func ConfigRun(r *cmd.Root, c *cmd.Sub) { // Setup main application config. rFlags := rootInit(r) args := c.Args.(*ConfigArgs) // Setup temporary configuration. cfg := config.Config{} // Parse configuration file. err := config.ParseFile(rFlags.Config, &cfg) checkError(rFlags, err) // Parse Category and Field Values confKeys := strings.Split(args.Key, ".") category := capName(confKeys[0]) field := capName(confKeys[1]) // Use reflect to get/set the value of the config struct reConf := reflect.ValueOf(&cfg).Elem().FieldByName(category) if len(args.Value) > 0 { reConf.FieldByName(field).SetString(args.Value[0]) // Write changes back to config file. config.WriteFile(rFlags.Config, &cfg) } else { // Print current value if no new value given. fmt.Println(reConf.FieldByName(field)) } } // capName capitalizes the first letter of a string // and returns it. func capName(in string) string { return strings.ToUpper(string(in[0])) + in[1:] } <file_sep>package ipfs import ( files "github.com/ipfs/go-ipfs-files" icorepath "github.com/ipfs/interface-go-ipfs-core/path" ) // Get reads a file from IPFS without pinning it. func (n *Node) Get(hash string) (files.File, error) { // Construct IPFS CID path := icorepath.New("/ipfs/" + hash) // Pin file to local storage within IPFS node, err := n.api.Unixfs().Get(n.ctx, path) if err != nil { return nil, err } // Convert node into file file := files.ToFile(node) return file, nil } <file_sep>package manifest import ( "errors" "net/url" "github.com/arken/ark/manifest/upstream" ) func (m *Manifest) HaveWriteAccess() (bool, error) { url, err := url.Parse(m.url) if err != nil { return false, err } upstream, ok := upstream.AvailableUpstreams[url.Host] if !ok { return true, errors.New("unknown upstream") } return upstream.HaveWriteAccess(m.gitOpts.Token, *url) } <file_sep>package parser var SubmissionTemplate = `# Note: Any lines that start with "#" are what we call comments # and will be omitted from your submission. They are only here # as a guide to help you. # Where should your addition be located within the keyset repository? # This line should be in the format of a path. # For example, # library/fiction/classics # or # science/biology/datasets # ( An empty line will add the file to the root of the manifest which is not # normally recommended.) # CATEGORY below # Provide a name for the keyset file that is about to be created # (no file extension, just the name) # FILENAME below # Briefly describe the files you're submitting # (preferably <50 characters). # TITLE below # An empty commit message will abort the submission. # Describe the files in more detail. # COMMIT below # If you will be submitting a pull request, explain why these files should # be added to the desired repository # PULL REQUEST below ` <file_sep>package manifest import "strings" func (m *Manifest) Generate(input map[string]string) (string, error) { output := make([]string, 0, len(input)) for k, v := range input { output = append(output, k+" "+v) } return strings.Join(output, "\n"), nil }
22c2d7e25390f2375691637eaac9ce1f3f60cb58
[ "Go", "Go Module", "Markdown" ]
36
Go Module
arken/ait
0f148be575fd03bfc74c96fd378177dac16425e3
4fee4e86320de5ba118027e27614bc78b6ef51a5
refs/heads/master
<file_sep>module github.com/x-foby/go-short/config go 1.13 <file_sep># go-short <file_sep>module github.com/x-foby/go-short/database go 1.13 <file_sep>package config import ( "errors" "io/ioutil" "gopkg.in/yaml.v3" ) var ( // config имеет тип `interface{}` для того чтоб было возможно // реализовать нужные механики (чтение, запись, маршаллинг, анмаршаллинг и т.д.), // абстрагировавшись от конкретной структуры // Реально работа будет вестись со структурой, установленной через `Set(interface{})` config interface{} // filename хранит путь к файлу, в котором хранятся настройки. // Значение `filename` необходимо установить через метод `SetFilename(string)` до вызова // чтения filename string ) // Ошибки var ( ErrNoFileName = errors.New("Не указан путь к файлу конфигураций") ) // Set устанавливает ссылку на структуру кофигурации func Set(c interface{}) { config = c } // SetFilename устанавливает путь к файлу с конфигурацией func SetFilename(fn string) { filename = fn } // ReadFromFile читает кофигурации из файла и обновляет их func ReadFromFile() error { return readFromFile(filename) } // WriteToFile записывает текущие кофигурации в файл func WriteToFile() error { return writeToFile(filename) } // Update обновляет кофигурации func Update(buf []byte) error { return yaml.Unmarshal(buf, config) } // Backup сохраняет текущюю конфигурацию func Backup() error { return writeToFile(filename + "~") } // Restore сохраняет текущюю конфигурацию func Restore() error { if err := readFromFile(filename + "~"); err != nil { return err } return writeToFile(filename) } func readFromFile(fn string) error { if err := checkFilename(); err != nil { return err } buf, err := ioutil.ReadFile(fn) if err != nil { return err } return Update(buf) } func writeToFile(fn string) error { if err := checkFilename(); err != nil { return err } buf, err := yaml.Marshal(config) if err != nil { return err } return ioutil.WriteFile(fn, buf, 0755) } func checkFilename() error { if filename == "" { return ErrNoFileName } return nil } <file_sep>package arrays // Contains проверяет, есть ли искомый элемент в массиве func Contains(a []interface{}, e interface{}) bool { for _, v := range a { if v == e { return true } } return false } // Index возвращает индекс искомого элемента или -1 func Index(a []interface{}, e interface{}) int { for k, v := range a { if v == e { return k } } return -1 } // Remove удаляет элементы в количестве length, начиная с start func Remove(a []interface{}, start, length int) []interface{} { if length == -1 { return a[:start] } return append(a[:start], a[start+length:]...) } <file_sep>package webserver import ( "errors" "net/http" "strconv" "strings" "time" ) // Settings описывает настройки веб-сервера type Settings struct { Host string `json:"host,omitempty" yaml:"host,omitempty"` Port int `json:"port,omitempty" yaml:"port,omitempty"` ReadTimeout int64 `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty"` ReadHeaderTimeout int64 `json:"readHeaderTimeout,omitempty" yaml:"readHeaderTimeout,omitempty"` MaxHeaderBytes int `json:"maxHeaderBytes,omitempty" yaml:"maxHeaderBytes,omitempty"` } // Ошибки var ( ErrNoSettings = errors.New("go-short: Не передан указатель на объект с настройками") ) var settings Settings // GetSettings возвращает указатель на настройки БД func GetSettings() *Settings { return &settings } // Start запускает http-сервер func Start(handler http.HandlerFunc, logger func(s *Settings, v ...interface{})) error { checkSettings() http := &http.Server{ Addr: settings.Host + ":" + strconv.Itoa(settings.Port), Handler: http.HandlerFunc(handler), ReadTimeout: time.Duration(settings.ReadTimeout) * time.Millisecond, MaxHeaderBytes: settings.MaxHeaderBytes, } logger(&settings) if err := http.ListenAndServe(); err != nil { return err } return nil } // Print выводит ответ сервера func Print(w http.ResponseWriter, status int, data []byte) { w.WriteHeader(status) w.Write(data) } func checkSettings() { if strings.TrimSpace(settings.Host) == "" { settings.Host = "localhost" } if settings.Port < 1 || settings.Port > 65535 { settings.Port = 65432 } } <file_sep>module github.com/x-foby/go-short/arrays go 1.13 <file_sep>package config import "testing" var errorString = "Expected %v, got %v" type Config struct { StringProperty *string `json:"stringProperty"` IntProperty *int `json:"intProperty"` BoolProperty *bool `json:"boolProperty"` SliceProperty *[]interface{} `json:"sliceProperty"` MapProperty *map[string]interface{} `json:"mapProperty"` } func TestSet(t *testing.T) { var cfg Config Set(cfg) if config != cfg { t.Errorf(errorString, cfg, cfg) } } func TestSetFilename(t *testing.T) { fn := "./config.json" SetFilename(fn) if filename != fn { t.Errorf(errorString, fn, filename) } } func TestWriteToFile(t *testing.T) { var cfg Config var err error Set(&cfg) SetFilename("") stringProperty := "value" intProperty := 123 boolProperty := true sliceProperty := []interface{}{1, 2} mapProperty := map[string]interface{}{"key": "value"} cfg.StringProperty = &stringProperty cfg.IntProperty = &intProperty cfg.BoolProperty = &boolProperty cfg.SliceProperty = &sliceProperty cfg.MapProperty = &mapProperty err = WriteToFile() if err != ErrNoFileName { t.Errorf(errorString, nil, err) } SetFilename("./config.json") err = WriteToFile() if err != nil { t.Errorf(errorString, nil, err) } Set(make(chan int)) err = WriteToFile() if err == nil { t.Errorf(errorString, "error", err) } } func TestReadFromFile(t *testing.T) { var cfg Config var err error Set(&cfg) SetFilename("") err = ReadFromFile() if err != ErrNoFileName { t.Errorf(errorString, nil, err) } SetFilename("./config.json") err = ReadFromFile() if err != nil { t.Errorf(errorString, nil, err) } SetFilename("./config2.json") err = ReadFromFile() if err == nil { t.Errorf(errorString, "error", err) } } func TestUpdate(t *testing.T) { var cfg Config Set(&cfg) if err := Update([]byte(`{"stringProperty":"value","intProperty":123,"boolProperty":true,"sliceProperty":[1,2],"mapProperty":{"key":"value"}}`)); err != nil { t.Errorf(errorString, nil, err) } } func TestBackup(t *testing.T) { SetFilename("") if err := Backup(); err != ErrNoFileName { t.Errorf(errorString, ErrNoFileName, err) } SetFilename("./config.json") if err := Backup(); err != nil { t.Errorf(errorString, nil, err) } } func TestRestore(t *testing.T) { SetFilename("") if err := Restore(); err != ErrNoFileName { t.Errorf(errorString, ErrNoFileName, err) } SetFilename("./config.json") if err := Restore(); err != nil { t.Errorf(errorString, nil, err) } } // func readFromFile(fn string) error { // if err := checkFilename(); err != nil { // return err // } // buf, err := ioutil.ReadFile(fn) // if err != nil { // return err // } // return Update(buf) // } // func writeToFile(fn string) error { // if err := checkFilename(); err != nil { // return err // } // buf, err := json.MarshalIndent(config, "", " ") // if err != nil { // return err // } // return ioutil.WriteFile(fn, buf, 0755) // } // func checkFilename() error { // if filename == "" { // return ErrNoFileName // } // return nil // } <file_sep>module github.com/x-foby/go-short/log go 1.13 <file_sep>package log import ( "fmt" "log" "os" "time" ) type level int // Уровни логирования const ( FATAL level = iota WARNING INFO ) var currentLevel = WARNING var levelWords = map[level]string{ FATAL: "[FATAL]", WARNING: "[WARNING]", INFO: "[INFO]", } // SetLevel устанавливает уровень логирования func SetLevel(l level) { currentLevel = l } // Print выводит сообщение в лог func Print(l level, values ...interface{}) { if l > currentLevel { return } if l > INFO { log.SetOutput(os.Stderr) } else { log.SetOutput(os.Stdout) } log.Println(append([]interface{}{levelWords[l]}, values...)...) if l == FATAL { os.Exit(1) } } // PrintDuration выводит сообщение о длительности операции, приводя // длительность к наиболее подходящей размерности func PrintDuration(startTime time.Time) { Print(INFO, fmt.Sprintf("Выполнено за %v", time.Since(startTime))) } <file_sep>package arrays import ( "reflect" "testing" ) var errorString = "Expected %v, got %v" func TestContains(t *testing.T) { if c := Contains([]interface{}{1, 2, 3}, 2); !c { t.Errorf(errorString, true, c) } if c := Contains([]interface{}{1, 2, 3}, 5); c { t.Errorf(errorString, false, c) } } func TestIndex(t *testing.T) { if i := Index([]interface{}{1, 2, 3}, 2); i != 1 { t.Errorf(errorString, 1, i) } if i := Index([]interface{}{1, 2, 3}, 5); i != -1 { t.Errorf(errorString, -1, i) } } func TestRemove(t *testing.T) { a := []interface{}{1, 2, 3} b := Remove(a, 1, 1) c := []interface{}{1, 3} if !reflect.DeepEqual(b, c) { t.Errorf(errorString, c, b) } a = []interface{}{1, 2, 3} b = Remove(a, 1, -1) c = []interface{}{1} if !reflect.DeepEqual(b, c) { t.Errorf(errorString, c, b) } } <file_sep>package webserver import ( "net/http" "net/http/httptest" "testing" ) var errorString = "Expected %v, got %v" func TestPrint(t *testing.T) { w := httptest.NewRecorder() Print(w, http.StatusOK, []byte("OK")) if w.Code != http.StatusOK { t.Errorf(errorString, http.StatusOK, w.Code) } if w.Body.String() != "OK" { t.Errorf(errorString, "OK", w.Body.String()) } w = httptest.NewRecorder() Print(w, http.StatusInternalServerError, []byte("InternalServerError")) if w.Code != http.StatusInternalServerError { t.Errorf(errorString, http.StatusInternalServerError, w.Code) } if w.Body.String() != "InternalServerError" { t.Errorf(errorString, "InternalServerError", w.Body.String()) } } func TestCheckSettings(t *testing.T) { expected := Settings{ Host: "localhost", Port: 65432, } checkSettings() if settings != expected { t.Errorf(errorString, expected, settings) } settings.Host = " " settings.Port = -1 checkSettings() if settings != expected { t.Errorf(errorString, expected, settings) } } <file_sep>package database import ( "database/sql" "fmt" "sync" ) // Command опсиывает настройки запроса type Command struct { Query string `json:"query,omitempty" yaml:"query,omitempty"` Args []interface{} `json:"args,omitempty" yaml:"args,omitempty"` } // ConnectionSetting опсиывает настройки подключения к БД type ConnectionSetting struct { Driver string `json:"driver,omitempty" yaml:"driver,omitempty"` ConnectionStringParams map[string]interface{} `json:"connectionStringParams,omitempty" yaml:"connectionStringParams,omitempty"` AfterConnection []Command `json:"afterConnection,omitempty" yaml:"afterConnection,omitempty"` } // DriverSetting опсиывает настройки драйвер к БД type DriverSetting struct { GetConnectionString func(s map[string]interface{}) (string, error) AfterConnection func(db *sql.DB, cs ConnectionSetting) error } // Settings описывает настройки БД по умолчанию и пул соединений type Settings struct { Pool map[string]ConnectionSetting `json:"pool" yaml:"pool"` } // Pool описывает потокобезопасный пул именованных соединений type Pool struct { *sync.RWMutex m map[string]*sql.DB } // NewPool создаёт новый пул и возвращает указатель на него func NewPool() *Pool { return &Pool{ RWMutex: &sync.RWMutex{}, m: make(map[string]*sql.DB), } } // Load возвращает соединение из пула func (p *Pool) Load(key string) (*sql.DB, bool) { p.RLock() value, ok := p.m[key] p.RUnlock() return value, ok } // Store сохраняет соединение в пул func (p *Pool) Store(key string, value *sql.DB) { p.Lock() p.m[key] = value p.Unlock() } // Range обходит все соединения, вызывая переданный коллбэк func (p *Pool) Range(cb func(key string, value *sql.DB)) { p.Lock() for k, v := range p.m { cb(k, v) } p.Unlock() } var settings Settings var pool *Pool var drivers = make(map[string]DriverSetting) func init() { pool = NewPool() } // GetSettings возвращает указатель на настройки БД func GetSettings() *Settings { return &settings } // RegisterDriver регистрирует драйвер БД и задаёт функцию, возвращающую connection string для подключения func RegisterDriver(name string, driverSetting DriverSetting) { drivers[name] = driverSetting } // Open устанавливает соединение с базой данных из пула, если соединение ещё не установлено, и возвращает ссылку на него func Open(name string) (*sql.DB, error) { connectionSettings, ok := settings.Pool[name] if !ok { return nil, fmt.Errorf("%q отсутствует в пуле соединений", name) } conn, _ := pool.Load(name) conn, err := getConn(conn, connectionSettings) if err != nil { return nil, err } pool.Store(name, conn) return conn, err } // OpenCustom устанавливает соединение с базой данных из пула по произвольным параметрам, добавленным к текущим настройкам соединения, // если соединение ещё не установлено, и возвращает ссылку на него func OpenCustom(name, ID string, customParams map[string]interface{}) (*sql.DB, error) { connectionSettings, ok := settings.Pool[name] if !ok { return nil, fmt.Errorf("%q отсутствует в пуле соединений", name) } cs := connectionSettings cs.ConnectionStringParams = make(map[string]interface{}) for k, v := range connectionSettings.ConnectionStringParams { if param, ok := customParams[k]; ok { cs.ConnectionStringParams[k] = param } else { cs.ConnectionStringParams[k] = v } } for k, v := range customParams { if _, ok := cs.ConnectionStringParams[k]; !ok { cs.ConnectionStringParams[k] = v } } connName := name + ID conn, _ := pool.Load(connName) conn, err := getConn(conn, cs) if err != nil { return nil, err } pool.Store(connName, conn) return conn, err } // CloseAll закрывает все соединения func CloseAll() { pool.Range(func(k string, v *sql.DB) { if v == nil { return } if err := v.Ping(); err != nil { v.Close() } }) } func getConn(conn *sql.DB, cs ConnectionSetting) (*sql.DB, error) { if conn == nil { return openConn(cs) } if err := conn.Ping(); err != nil { return openConn(cs) } return conn, nil } func openConn(s ConnectionSetting) (*sql.DB, error) { ds, ok := drivers[s.Driver] if !ok { return nil, fmt.Errorf("Драйвер для %q не зарегистрирован", s.Driver) } cs, err := ds.GetConnectionString(s.ConnectionStringParams) if err != nil { return nil, err } conn, err := sql.Open(s.Driver, cs) if err != nil { return nil, err } if ds.AfterConnection != nil { ds.AfterConnection(conn, s) } for _, q := range s.AfterConnection { if _, err := conn.Exec(q.Query, q.Args...); err != nil { return nil, err } } return conn, err } <file_sep>module github.com/x-foby/go-short/webserver go 1.13
7bb385a4623d6423898d66628dfe6b5f3df52abd
[ "Markdown", "Go Module", "Go" ]
14
Go Module
x-foby/go-short
fc7b5bfa85eafa16e4685fc4f88b9721e92c7230
a7da6ac2d97c0304d9288909fa05501b9919bf1a
refs/heads/master
<repo_name>akashks1998/homepage<file_sep>/README.md # homepage This is my home-page made with mainly p5.js <file_sep>/sketch.js let bubbles = []; let nav, d, j; let opn = 0; let cou = 100; let mic; function setup() { createCanvas(windowWidth, windowHeight); console.log(width); mic= new p5.AudioIn(); mic.start(); if (width < 800) { d = createElement('div', ''); d.id('d'); d.parent('ain'); j = createElement('i', ''); j.parent('d'); j.class('fa fa-bars fa-2x'); d.position(10, 10); } for (i = 0; i < 50; i++) { let bubble = new Bubble(random(width), random(0, height), 0, 0, 0); bubbles.push(bubble); } let rainb = selectAll(".rain"); for (let i = 0; i < rainb.length; i++) { let x = 200; // Math.floor(random(100, 255)); rainb[i].style("background-color", "rgba(" + x + ',' + x + ',' + x + ',0.5)'); rainb[i].style('padding', '2vh'); rainb[i].style('border-radius', '10%'); rainb[i].mouseOver(function() { this.style('font-size', '15pt'); }); rainb[i].mouseOut(function() { this.style('font-size', '13pt'); }); } nav = select('#nav'); } function mousePressed() { for (i = 0; i < 10; i++) { let bubble = new Bubble(mouseX, mouseY, random(-10, 10), random(-10, 10), 5); bubbles.push(bubble); } } function draw() { let vol=mic.getLevel(); cou++; if (cou % 100 == 0) { changeImg(); } background(0, 0, 0, 50); noStroke(); if (random(1) < 0.01) { let bubble = new Bubble(random(width), random(0, height / 2), random(-5, -15), random(5, 15), 5); bubbles.push(bubble); } for (let i = bubbles.length - 1; i >= 0; i--) { bubbles[i].move(); bubbles[i].show(); if (bubbles[i].check()) { bubbles.splice(i, 1); } } fill(120, 120, 120, 120); beginShape(); vertex(0, height); for (let i = 0; i < width; i += 5) { vertex(i, height - (50 + ( vol*height)/2 * Math.pow(2, -(i - mouseX) * (i - mouseX) / 20000))); } vertex(width, height); endShape(CLOSE); if (mouseX < width * 0.1) { nav.style('visibility', 'visible'); nav.class('animated fadeInLeft'); nav.removeClass('animated fadeOutLeft'); } else if ((mouseX > width * 0.3 && width > 800) || (mouseX > width * 0.6 && width < 800)) { //nav.style('visibility','hidden'); nav.removeClass('animated fadeInLeft'); nav.class('animated fadeOutLeft'); } } class Bubble { constructor(x, y, vx, vy, dalp) { this.x = x; this.y = y; this.r = random(1, 4); this.vx = vx; this.vy = vy; this.alpha = 255; this.g = 0.5; this.dalp = dalp; } move() { this.x += this.vx; this.y += this.vy; //this.vy+=this.g; this.alpha -= this.dalp; } show() { fill(random(220, 255), random(240, 255), random(230, 255), this.alpha); ellipse(this.x, this.y, this.r, this.r); } check() { return this.alpha < 0; } }; function chan(x) { opn = x; } function changeImg() { let im = select('#image-blurred-edge'); im.style('background-image', "url('img/aka" + (Math.floor(cou / 100)) % 9 + ".jpg')") }
ef5081bcb709b54e8bf3613ebb731e0c81a5c305
[ "Markdown", "JavaScript" ]
2
Markdown
akashks1998/homepage
2817f606f7839ba0a3fe5200a82c4db444872ab8
736906f9e6237ea49d86aa10c22e21176f81fd5b
refs/heads/master
<repo_name>bkawk/unity-scatter<file_sep>/Assets/TheScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using ScatterSharp; public class TheScript : MonoBehaviour { public Button m_loginButton; // Use this for initialization void Start () { Button btn1 = m_loginButton.GetComponent<Button>(); btn1.onClick.AddListener(LoginClicked); } // Update is called once per frame void Update () { } public void LoginClicked() { Debug.Log("Login clicked"); InitScatter(); } public async void InitScatter() { var network = new ScatterSharp.Api.Network() { Blockchain = Scatter.Blockchains.EOSIO, Host = "api.eossweden.se", Port = 443, Protocol = "https", ChainId = "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906" }; var scatter = new Scatter("UnityTestApp", network); await scatter.Connect(); var identity = await scatter.GetIdentity(new ScatterSharp.Api.IdentityRequiredFields() { Accounts = new List<ScatterSharp.Api.Network>() { network }, Location = new List<ScatterSharp.Api.LocationFields>(), Personal = new List<ScatterSharp.Api.PersonalFields>() }); Debug.Log(identity); var eos = scatter.Eos(); } }
156ee0e7c0e4bb535a5975754321cf26dfc54a54
[ "C#" ]
1
C#
bkawk/unity-scatter
be97a33558859173cd366d1f57eef69fe4a319f0
3bace0ebe784ab3bfcffd524b368717b322e05ad
refs/heads/master
<repo_name>gaozejian/ZJBasicTools<file_sep>/Example/Podfile use_frameworks! target 'ZJBasicTools_Example' do pod 'ZJBasicTools', :path => '../' target 'ZJBasicTools_Tests' do inherit! :search_paths end end
e7296d7a270ca3abc2a26c47c8f023298cfa2a1f
[ "Ruby" ]
1
Ruby
gaozejian/ZJBasicTools
faa3eb14ad0cb4d77c11f66e03a2930a11b3ddba
c83a5c866d481a6d25d0de709673f68023a6015b
refs/heads/master
<repo_name>0Delta/docker-review<file_sep>/README.md # Re:VIEW image for Docker [![CircleCI](https://circleci.com/gh/vvakame/docker-review.svg?style=svg)](https://circleci.com/gh/vvakame/docker-review) [![Docker Build Statu](https://img.shields.io/docker/build/vvakame/review.svg)](https://hub.docker.com/r/vvakame/review/) [![Docker Automated buil](https://img.shields.io/docker/automated/vvakame/review.svg)](https://hub.docker.com/r/vvakame/review/) [![Docker Stars](https://img.shields.io/docker/stars/vvakame/review.svg)](https://hub.docker.com/r/vvakame/review/) [![Docker Pulls](https://img.shields.io/docker/pulls/vvakame/review.svg)](https://hub.docker.com/r/vvakame/review/) このリポジトリは[Docker](https://www.docker.com/)上で[Re:VIEW](https://github.com/kmuto/review/)を動かすためのものです。 [Docker Hub](https://hub.docker.com/r/vvakame/review/)にTrusted Buildとして置いてあるのでご活用ください。 Windows用の手引は[こちら](https://github.com/vvakame/docker-review/blob/master/doc/windows-review.md)を参考にしてください。 docker-composeを使った時の手引としても使えます。 ## 仕様 ### サポートしているタグ Re:VIEWのバージョン毎にイメージを作成しています。 現在存在しているタグは `latest`, `3.0`, `3.1`, `3.2` です。 `2.3`, `2.4` , `2.5` も存在していますが、サポートは終了しています。 ``` $ docker pull vvakame/review:3.0 $ docker pull vvakame/review:3.1 $ docker pull vvakame/review:3.2 ``` ### インストールされているコマンド * git * curl * texlive & 日本語環境 * mecab (Re:VIEW 索引作成時に利用される) * ruby (Re:VIEW 実行環境) * Node.js & npm ([ReVIEW-Template](https://github.com/TechBooster/ReVIEW-Template)用環境) * Re:VIEW & rake & bundler 他。詳細は[Dockerfile](https://github.com/vvakame/docker-review/blob/master/Dockerfile)を参照してください。 ## TeX周りの初期設定 PDF作成時、Notoフォントをデフォルトで利用しフォントの埋め込みも行うようになっています。 * [IPAフォント](http://ipafont.ipa.go.jp/)のインストール * 利用したい場合 `kanji-config-updmap ipaex` を実行する * [Notoフォント](https://www.google.com/get/noto/)のインストール & デフォルト利用指定 ## 使い方 次のようなディレクトリ構成を例にします ``` ├── README.md └── src    ├── catalog.yml    ├── config.yml    ├── ch01.re    ├── ch02.re    ├── ch03.re    ├── index.re    └── layouts ``` - `config.yml`が存在するディレクトリをコンテナ上にマウントする `src`ディレクトリに`config.yml`がある場合 ``` -v `pwd`/src:/work ``` `work`ディレクトリは任意の名前でよいです。後述のコマンドで`cd`する先になります。 - `vvakame/review` イメージを使用する - マウントしたディレクトリ内で任意のビルドコマンドを実行する pdf出力する場合 ``` /bin/sh -c "cd /work && review-pdfmaker config.yml" ``` この例では実行するコマンドは次のようになります。 ``` $ docker run --rm -v `pwd`/src:/work vvakame/review /bin/sh -c "cd /work && review-pdfmaker config.yml" ``` ビルドが終了すると、`src`ディレクトリ内にpdfファイルが出力されます。 <file_sep>/update.sh #!/bin/bash -eux # 2.3.0 2.4.0 2.5.0 のサポートは終了しました versions=(3.0.0 3.1.0 3.2.0) for version in "${versions[@]}" do major=$(echo $version | cut -d "." -f 1) minor=$(echo $version | cut -d "." -f 2) dir_name=review-${major}.${minor} rm -rf ${dir_name} mkdir ${dir_name} cat Dockerfile | sed "s/^ENV REVIEW_VERSION .*$/ENV REVIEW_VERSION ${version}/" > ${dir_name}/Dockerfile cp -r noto-otc ${dir_name} done
64c3ea7415c2bf37ab2c8b8b14858cd9bdf0ab11
[ "Markdown", "Shell" ]
2
Markdown
0Delta/docker-review
8a0b91f3fe15eeebbe1553c4625f405d4534ece0
2506ed758e0389552de7b7aba8353b4ce44b724b
refs/heads/master
<repo_name>Dischan/yuki<file_sep>/yuki.js 'use strict'; var config = require('./config'); var express = require('express'); var bodyParser = require('body-parser'); var crypto = require('crypto'); var buildScripts = require('./build_scripts'); var request = require('request'); const fs = require('fs'); var app = express(); function sign(key, data) { return 'sha1=' + crypto.createHmac('sha1', key).update(data).digest('hex'); } function verifySignature(key, data, githubSig) { var sig = 'sha1=' + crypto.createHmac('sha1', key).update(data).digest('hex'); return sig === githubSig; } fs.stat(`${__dirname}/update.flag`, function(err, stat) { if(err === null) { var data = {message: 'Update successful!'}; request.post({ url: 'https://aegis.dischan.co/yuki/notify', headers: { 'Content-Type': 'application/json', 'X-Yuki-Signature': sign(config.yuki.secret, JSON.stringify(data)) }, json: data }); fs.unlinkSync(`${__dirname}/update.flag`); } }); app.use(bodyParser.json()); app.post('/github/webhook', function (req, res) { var event = req.get('X-GitHub-Event'); var signature = req.get('X-Hub-Signature'); if(!verifySignature(config.github.secret, JSON.stringify(req.body), signature)){ res.status(401).send('Invalid signature.'); } else { var data = req.body; if(event === 'push'){ buildScripts[data.repository.name](data); } res.send('Success'); } }); app.listen(9999, function () { console.log('Yuki is listening on port 9999'); }); <file_sep>/config.sample.js 'use strict' module.exports = { github: { secret: 'thisisasamplekey' }, yuki: { secret: 'thisisasamplekey' } } <file_sep>/README.md # yuki Dischan build bot.
3a081edfe9996216ecbba03127e2c6587d161977
[ "JavaScript", "Markdown" ]
3
JavaScript
Dischan/yuki
25729d927c40684c5f1c98b2dcc6ea11ce28ae6d
278e5e64f06a99eadeff1cf69c4c0516b21be332
refs/heads/master
<repo_name>unbiased-recruiting/unbiased-recruiting<file_sep>/models/autoencoder.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from ast import literal_eval import os import numpy as np import tensorflow as tf import pandas as pd import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import sys from operator import itemgetter K = tf.keras # ====================== Preliminary settings ======================= # fix random seed for reproducibility np.random.seed(34) tf.random.set_random_seed(35) tf.logging.set_verbosity(tf.logging.INFO) # Flags definition flags = tf.app.flags FLAGS = flags.FLAGS # flags.DEFINE_integer('batch_size', 50, '') flags.DEFINE_integer('info_freq', 100, '') flags.DEFINE_integer('info_valid_freq', 500, '') flags.DEFINE_string('data_dir', '../data', '') # flags.DEFINE_float('learning_rate', 0.001, '') # flags.DEFINE_float('classifier_learning_rate', 0.001, '') # flags.DEFINE_float('beta', 10, '') # ====================== Loading settings ======================= print('Loading Data...') # Importing train and validation datasets data_dir = '../data/' df_train = pd.read_csv(os.path.join(data_dir, "train.csv")) df_val = pd.read_csv(os.path.join(data_dir, "val.csv")) df_test = pd.read_csv(os.path.join(data_dir, "test.csv")) data = [df_train, df_val, df_test] vocab_len = 10000 # Determined during preprocessing print('Preprocessing Data...') # Converting TXT column from str to array for df in data: df.loc[:, 'TXT'] = df.loc[:, 'TXT'].apply(lambda x: literal_eval(x)) df.loc[:, 'TXT'] = df.loc[:, 'TXT'].apply( lambda x: [float(w) / 10000 for w in x]) # Normalizing tokens (10 000 is the maximum and 0 min) saving_path = './saved_models/normalized/' graphs_path = './graphs' if not os.path.exists(saving_path): os.makedirs(saving_path) if not os.path.exists(graphs_path): os.mkdir(graphs_path) X_train = np.array(df_train['TXT'].tolist(), dtype=np.float32) X_val = np.array(df_val['TXT'].tolist(), dtype=np.float32) X_test = np.array(df_test['TXT'].tolist(), dtype=np.float32) y_train = df_train[['GENRE_1.0', 'GENRE_2.0']].values y_val = df_val[['GENRE_1.0', 'GENRE_2.0']].values y_test = df_test[['GENRE_1.0', 'GENRE_2.0']].values # Create three `tf.data.Iterator` objects def make_iterator(CVs, labels, batch_size, shuffle_and_repeat=False): """function that creates a `tf.data.Iterator` object""" dataset = tf.data.Dataset.from_tensor_slices((CVs, labels)) if shuffle_and_repeat: dataset = dataset.apply( tf.data.experimental.shuffle_and_repeat(buffer_size=1000)) def parse(CV, label): """function that returns cv and associated gender in a queriable format""" return {'CV': CV, 'label': label} dataset = dataset.apply(tf.data.experimental.map_and_batch( map_func=parse, batch_size=batch_size, num_parallel_batches=8)) if shuffle_and_repeat: return dataset.make_one_shot_iterator() else: return dataset.make_initializable_iterator() # ====================== Network architecture ======================= # Network constant initialisation num_inputs = len(df_train.loc[0, 'TXT']) compression_size = 1024 # Layer initialisation def MLP_model_builder(input_cv, compression_size, num_inputs): print('Building Models...') # autoencoder print('MLP architecture') encoded = K.layers.Dense(compression_size, activation='relu')(input_cv) decoded = K.layers.Dense(num_inputs, activation='sigmoid')(encoded) autoencoder = K.Model(input_cv, decoded, name = "autoencoder") encoder = K.Model(input_cv, encoded, name = "encoder") encoded_input = K.layers.Input(shape = (compression_size,), name = "encoder_input") decoded_layer = autoencoder.layers[-1] decoder = K.Model(encoded_input, decoded_layer(encoded_input)) # gender_clf clf = K.layers.Dense(compression_size, activation='relu')(encoded_input) outputs = K.layers.Dense(units=2)(clf) gender_clf = K.Model(encoded_input, outputs, name='clf') return autoencoder, encoder, decoder, gender_clf def LSTM_model_builder(input_cv, time_steps, compression_size, nb_layers=1 ): print('LSTM architecture') from keras.models import Sequential, RepeatVector, Input from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout # Initialising the RNN encoded = Sequential() # Adding the first LSTM layer and some Dropout regularisation encoded.add(LSTM(units=compression_size, return_sequences=True, input_shape=(time_steps,input_cv))) encoded.add(Dropout(0.2)) decoded = RepeatVector(time_steps)(encoded) decoded.add(LSTM(units=input_cv, return_sequences=True, input_shape=(time_steps,compression_size))) decoded.add(Dropout(0.2)) for i in range(nb_layers): # Adding an i-th LSTM layer and some Dropout regularisation encoded.add(LSTM(units=50, return_sequences=True)) encoded.add(Dropout(0.2)) decoded.add(LSTM(units=50, return_sequences=True)) decoded.add(Dropout(0.2)) # Adding the output layer encoded.add(Dense(units=compression_size)) decoded.add(Dense(units=input_cv)) # Compiling the RNN #encoder.compile(optimizer='adam', loss='mean_squared_error') autoencoder = K.Model(input_cv, decoded, name="autoencoder") encoder = K.Model(input_cv, encoded, name="encoder") encoded_input = K.layers.Input(shape=(compression_size,), name="encoder_input") decoded_layer = autoencoder.layers[-1] decoder = K.Model(encoded_input, decoded_layer(encoded_input)) # gender_clf clf = K.layers.Dense(compression_size, activation='relu')(encoded_input) outputs = K.layers.Dense(units=2)(clf) gender_clf = K.Model(encoded_input, outputs, name='clf') return autoencoder, encoder, decoder, gender_clf # Autoencoder layers input_cv = K.layers.Input(shape=(num_inputs,), name="input_cv") autoencoder, encoder, decoder, gender_clf = MLP_model_builder(input_cv, compression_size, num_inputs) # autoencoder, encoder, decoder, gender_clf = LSTM_model_builder(input_cv, 3, compression_size, nb_layers=1) print("encoder") encoder.summary() print("decoder") decoder.summary() print("autoencoder") autoencoder.summary() # ====================== Defining training operations ======================= num_epoch = 6 # must be an even number batch_sizes = [32] # 10,, 50, 100 ] autoencoder_learning_rates = [0.01] # ,0.1,0.001,0.0001,0.00001] clf_learning_rates = [0.1] # ,0.0001,0.00001,0.001,0.01] beta_values = [1] # [0.01,1,0.1,10,100,1000] # Manual grid search model_params = [] for batch_size in batch_sizes: for AE_lr in autoencoder_learning_rates: print('Building Iterators...') train_iterator = make_iterator(X_train, y_train, batch_size=batch_size, shuffle_and_repeat=True) valid_iterator = make_iterator(X_val, y_val, batch_size=batch_size) test_iterator = make_iterator(X_test, y_test, batch_size=batch_size) for clf_lr in clf_learning_rates: for beta in beta_values: hyparam_name = str( 'batchsize_' + str(batch_size) + 'AElr_' + str(AE_lr) + '_CLFlr_' + str(clf_lr) + '_beta_' + str( beta)) model_params.append(hyparam_name) print('(batch_size, AE_learning_rate, clf_learning_rate, beta) = ({} ; {} ; {} ;{})'.format(batch_size, AE_lr, clf_lr, beta)) # Defining training operations def autoencoder_step(input_cv, clf_loss, Beta): logits = autoencoder(input_cv) autoencoder_loss = tf.losses.mean_squared_error(input_cv, logits) adversarial_loss = autoencoder_loss - Beta * clf_loss optimizer = tf.train.AdamOptimizer(AE_lr) train = optimizer.minimize(adversarial_loss) return train, adversarial_loss, autoencoder_loss def clf_step(encoded_input, label, dataset='train'): logits = gender_clf(encoded_input) prediction = tf.argmax(logits, 1) truth_label = tf.argmax(label, 1) clf_optimizer = tf.train.AdamOptimizer(clf_lr) loss = tf.losses.softmax_cross_entropy(onehot_labels=label, logits=logits) train = clf_optimizer.minimize(loss) if dataset != 'train': name = str(dataset + '_accuracy') accuracy, accuracy_op = tf.metrics.accuracy(truth_label, prediction, name=name) return train, loss, accuracy, accuracy_op else: accuracy = tf.reduce_mean(tf.cast(tf.equal(truth_label, prediction), tf.float32)) return train, loss, accuracy # Create training operations train_features = train_iterator.get_next() CVs, labels = itemgetter('CV', 'label')(train_features) clf_train, clf_loss, clf_accuracy = clf_step(encoder(CVs), labels) autoencoder_train, adversarial_loss, autoencoder_loss = autoencoder_step(CVs, clf_loss, beta) # ====================== Training Model ======================= # Create validation operations val_features = valid_iterator.get_next() val_CVs, val_labels = itemgetter('CV', 'label')(val_features) val_clf, val_clf_loss, clf_valid_accuracy, clf_valid_accuracy_op = clf_step(encoder(val_CVs), val_labels, 'valid') val_autoencoder_train, val_adversarial_loss, val_autoencoder_loss = autoencoder_step(val_CVs, val_clf_loss, beta) valid_running_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='valid_accuracy') # to measure validation accuracy during training valid_running_vars_initializer = tf.variables_initializer(var_list=valid_running_vars) # Create Test Operations test_features = test_iterator.get_next() test_CVs, test_labels = itemgetter('CV', 'label')(test_features) test_clf, test_clf_loss, test_clf_accuracy, test_clf_accuracy_op = clf_step(encoder(test_CVs), test_labels, 'test') test_autoencoder_train, test_adversarial_loss, test_autoencoder_loss = autoencoder_step(test_CVs, test_clf_loss, beta) test_running_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope='test_accuracy') # to measure validation accuracy during training test_running_vars_initializer = tf.variables_initializer(var_list=test_running_vars) # ====================== Defining training operations ======================= print('Training Models...') # Training model init = tf.global_variables_initializer() adversarial_losses = [] clf_accuracies = [] autoencoder_losses = [] even_epoch = [] odd_epoch = [] test_accuracies = [] AE_test_losses = [] ADV_test_losses = [] with tf.Session() as sess: sess.run(init) for epoch in range(num_epoch): if epoch % 2 == 0: even_epoch.append(epoch) autoencoder_loss_value = sess.run(autoencoder_loss) autoencoder_losses.append(autoencoder_loss_value) adversarial_loss_value = sess.run(adversarial_loss) adversarial_losses.append(adversarial_loss_value) if epoch % FLAGS.info_freq == 0: print("TRAIN epoch: {} , AE loss : {}, ADV loss : {}".format(epoch, autoencoder_loss_value, adversarial_loss_value)) else: sess.run(clf_train) accuracy = sess.run(clf_accuracy) clf_accuracies.append(accuracy) odd_epoch.append(epoch) if (epoch - 1) % FLAGS.info_freq == 0: print("TRAIN epoch: {} , clf accuracy : {}".format(epoch, accuracy)) # validation if (epoch - 1) % FLAGS.info_valid_freq == 0: sess.run(valid_running_vars_initializer) # reinitialize accuracy sess.run(valid_iterator.initializer) while True: try: AE_valid_loss = sess.run(val_autoencoder_loss) ADV_valid_loss = sess.run(val_adversarial_loss) sess.run(clf_valid_accuracy_op) except tf.errors.OutOfRangeError: break valid_accuracy_value = sess.run(clf_valid_accuracy) print('VAL epoch: {} , clf accuracy : {}, AE loss : {}, ADV loss : {}'.format(epoch, valid_accuracy_value, AE_valid_loss, ADV_valid_loss)) # test sess.run(test_running_vars_initializer) # reinitialize accuracy sess.run(test_iterator.initializer) while True: try: AE_test_loss = sess.run(test_autoencoder_loss) ADV_test_loss = sess.run(test_adversarial_loss) sess.run(test_clf_accuracy_op) except tf.errors.OutOfRangeError: break test_accuracy_value = sess.run(test_clf_accuracy) print('TEST - AE loss : {}, ADV loss : {} '.format(AE_test_loss, ADV_test_loss)) print('TEST clf accuracy : {}'.format(test_accuracy_value)) test_accuracies.append(test_accuracy_value) AE_test_losses.append(AE_test_loss) ADV_test_losses.append(ADV_test_loss) test_results = pd.DataFrame( {'Parameters': model_params, "AE test loss": AE_test_losses, "test_accuracy": test_accuracies, "ADV test loss": ADV_test_losses}) # Overwrite test results test_results.to_csv(os.path.join(saving_path, 'test_results.csv')) print('Test results saved') # Train results into csv print("DEBUG - len of adv, ae loss and acc: ({},{},{})".format(len(adversarial_losses), len(autoencoder_losses), len(clf_accuracies))) results = pd.DataFrame( {"train Adversarial loss": adversarial_losses, "train AE loss": autoencoder_losses, "train clf accuracy": clf_accuracies}) results.to_csv(os.path.join(saving_path + hyparam_name + '_results.csv')) print('Train results saved') # ====================== Exporting model ======================= # serialize weights to HDF5 ''' encoder.save_weights(os.path.join(saving_path, hyparam_name+"encoder.h5")) print("Encoder saved") encoder.save_weights(os.path.join(saving_path, hyparam_name+"decoder.h5")) print("Decoder saved") ''' # ====================== Plotting Train results ======================= if len(sys.argv) > 1 and str(sys.argv[1]) == 'plot': print("plotting TRAIN graphs...") plt.figure(1, figsize=(10, 15)) plt.subplot(3, 1, 1) plt.plot(even_epoch, adversarial_losses, color="red") plt.title("Adversarial Loss vs Epochs") plt.xlabel("Number of epoch") plt.ylabel("Adversarial Loss") plt.subplot(3, 1, 2) plt.plot(even_epoch, autoencoder_losses, color="green") plt.title("Autoencoder Loss vs Epochs") plt.xlabel("Number of epoch") plt.ylabel("Autoencoder Loss") plt.subplot(3, 1, 3) plt.plot(odd_epoch, clf_accuracies, color="orange") plt.title("Classifier Accuracy vs Epochs") plt.xlabel("Number of epoch") plt.ylabel("Classifier accuracy") # TODO : beware if values of beta etc are FLAGS values afterwards :) name = "losses and accuracy vs epochs for Beta={Beta}, batch_size={batch_size}, AE_learning_rate={learning_rate}, classifier_learning_rate={clf_learning_rate}.png".format( Beta=beta, batch_size=batch_size, learning_rate=AE_lr, clf_learning_rate=clf_lr) plt.savefig("graphs/" + name) plt.figure(2) plt.plot(clf_accuracies, autoencoder_losses) plt.title("Autoencoder Loss vs Classifier Accuracy") plt.xlabel("Classifier accuracy") plt.ylabel("Autoencoder Loss") plt.savefig( "graphs/autoencoder loss vs classifier accuracy for Beta={Beta}, batch_size={batch_size}, AE_learning_rate={learning_rate}, classifier_learning_rate={clf_learning_rate}.png".format( Beta=beta, batch_size=batch_size, learning_rate=AE_lr, clf_learning_rate=clf_lr)) print('Session successfully closed !') <file_sep>/requirements.txt absl-py==0.7.0 appnope==0.1.0 astor==0.7.1 backcall==0.1.0 bleach==3.1.0 certifi==2019.3.9 cycler==0.10.0 decorator==4.3.2 entrypoints==0.3 gast==0.2.2 grpcio==1.16.1 h5py==2.9.0 ipykernel==5.1.0 ipython==7.3.0 ipython-genutils==0.2.0 ipywidgets==7.4.2 jedi==0.13.3 Jinja2==2.10 jsonschema==2.6.0 jupyter==1.0.0 jupyter-client==5.2.4 jupyter-console==6.0.0 jupyter-core==4.4.0 Keras==2.2.4 Keras-Applications==1.0.7 Keras-Preprocessing==1.0.9 kiwisolver==1.0.1 Mako==1.0.7 Markdown==3.0.1 MarkupSafe==1.1.1 matplotlib==3.0.2 mistune==0.8.4 mkl-fft==1.0.10 mkl-random==1.0.2 mock==2.0.0 nbconvert==5.3.1 nbformat==4.4.0 nltk==3.4 notebook==5.7.8 numpy==1.14.3 pandas==0.24.1 pandocfilters==1.4.2 parso==0.3.4 pbr==5.1.3 pexpect==4.6.0 pickleshare==0.7.5 prometheus-client==0.6.0 prompt-toolkit==2.0.9 protobuf==3.6.1 ptyprocess==0.6.0 Pygments==2.3.1 pygpu==0.7.6 pyparsing==2.3.1 python-dateutil==2.8.0 pytz==2018.9 pyzmq==18.0.0 qtconsole==4.4.3 scikit-learn==0.19.1 scipy==1.1.0 Send2Trash==1.5.0 six==1.12.0 tensorboard==1.12.2 tensorflow==1.12.0 tensorflow-hub==0.3.0 termcolor==1.1.0 terminado==0.8.1 testpath==0.4.2 Theano==1.0.3 tornado==5.1.1 traitlets==4.3.2 wcwidth==0.1.7 webencodings==0.5.1 Werkzeug==0.14.1 widgetsnbextension==3.4.2 <file_sep>/README.md # Unbiased recruiting ## Context and goal Machine Learning algorithms are more and more used to match job applicants to job offers. One of the arguments used by Machine Learning proponents is that algorithms are more objective than humans but is it really the case? We have seen recent scandals involving recruiting algorithms discriminating against women - Amazon 2018. The question is then how do we make recruiting algorithms genderless? This project aims at making sure that CV representations do not contain any gender component stemming from linguistic characteristics or text syntax but do contain the information necessary to match it to a relevant job offer. You can read about the project and see the presentation in the folder "reports". ## High level explanation To do so we use two neuronal networks trained with job applicants' CVs. Those CVs have been parsed into texts. The first neuronal network is an autoencoder. We train a network to reproduce the text that has been fed to it. The text is beeing first encoded into a vector of smaller size than the initial tokenized texts. The encoded vector is then decoded. The second neuronal network is a binary classifier whose goal is to determine the gender (male or female here) after encoding of CV. We design a custom loss including two variable: * A reconstruction loss, which is the classical autoencoder loss comparing the input to the decoded output * The classifier loss $$ Loss_{Adversarial} = Loss_{Autoencoder} - \beta* Loss_{Classifier} $$ Here we want our networks to work together. Finding out the gender or failing to reconstruct the CV are penalising factors during the training phase of the network. ## Requirement All scripts used in this project use python3. Please refer to the requirements.txt file for the specific libraries to download. ## Pre processing Please create a data folder at the root of thr project and put a CSV file containing parsed CVs and the gender associated to each CV. You have the choice between two types of CV encoding: * Simple word tokenization run `python tokenisation.py` from preprocessing folder * One hot encoding run `python Onehot.py` from preprocessing folder Both scripts will generate 3 files in the data folder named train.csv, val.csv and test.csv. ## Training phase The training phase is simply executed by running `python autoencoder.py` within the models . Once finished the training will produce a log file containing training information such as loss value at different epochs. Models will also be exported in HDFS format. <file_sep>/pre-processing/tokenization.py import pandas as pd import os import numpy as np import numpy as np import string import nltk import re nltk.download('stopwords') nltk.download('punkt') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split """# Data processing ## Loading data """ #Importing data_dir = '../data' df = pd.read_csv(os.path.join(data_dir,"data_with_gender_rec.csv")) #leaning data df = df[['MATRICULEINT', 'TXT', 'GENRE']] df.loc[:,'GENRE'] = pd.to_numeric(df.loc[:,'GENRE'], errors = 'coerce', downcast = 'integer') df.dropna(inplace = True) df = df[df['GENRE'].isin([1, 2])] """##Stop words removal""" filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' #Import stop words language = 'french' stop_words = set(stopwords.words(language)) punctuation = string.punctuation + filters #remember to remove utf words #Row by row tokenization def tokenization_and_stop_words_out(text): x = word_tokenize(text) y = [w for w in x if not w in stop_words and not w in punctuation] return y df.loc[:,'TXT'] = df['TXT'].apply(tokenization_and_stop_words_out) """## Encoding labels Here we use to one hot encoding for encoding genders """ df = pd.get_dummies(df, columns = ['GENRE']) """## Splitting into train and test df""" #Initial split into train and test dataframes df_train_init, df_test = train_test_split(df, test_size = 0.25) #Second split of train dataframe into train and val dataframes df_train, df_val = train_test_split(df_train_init, test_size = 0.25) datasets = [df_train, df_val, df_test] """## Tokenization""" #Tokenizer training num_words = 10000 len_max_seq = df_train.apply(lambda x: len(x['TXT']), axis = 1).max() train_values = df_train.loc[:,'TXT'].tolist() tokenizer = Tokenizer(num_words = num_words, filters= filters,lower =True) tokenizer.fit_on_texts(train_values) #Text to padded sequences for df in datasets: df['TXT'] = tokenizer.texts_to_sequences(df.loc[:,'TXT']) df['TXT'] = pad_sequences(df.loc[:,'TXT'], maxlen = len_max_seq).tolist() """## Export""" df_train.to_csv(os.path.join(data_dir, "train.csv"),index = False) df_val.to_csv(os.path.join(data_dir, "val.csv"),index = False) df_test.to_csv(os.path.join(data_dir, "test.csv"),index = False) <file_sep>/pre-processing/Onehot.py import pandas as pd import os import numpy as np import numpy as np import string import nltk import re nltk.download('stopwords') nltk.download('punkt') from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer """# Data processing ## Loading data """ #Importing data_dir = '../data' df = pd.read_csv(os.path.join(data_dir,"data_with_gender_rec.csv")) #leaning data df = df[['MATRICULEINT', 'TXT', 'GENRE']] df.loc[:,'GENRE'] = pd.to_numeric(df.loc[:,'GENRE'], errors = 'coerce', downcast = 'integer') df.dropna(inplace = True) df = df[df['GENRE'].isin([1, 2])] """##Stop words removal""" filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' #Import stop words language = 'french' stop_words = set(stopwords.words(language)) punctuation = string.punctuation + filters #remember to remove utf words #Row by row tokenization def tokenization_and_stop_words_out(text): x = word_tokenize(text) y = [w for w in x if not w in stop_words and not w in punctuation] z = " ".join(y) return z df.loc[:,'TXT'] = df['TXT'].apply(tokenization_and_stop_words_out) """## Encoding labels Here we use to one hot encoding for encoding genders """ df = pd.get_dummies(df, columns = ['GENRE']) """## Splitting into train and test df""" #Initial split into train and test dataframes df_train_init, df_test = train_test_split(df, test_size = 0.25) #Second split of train dataframe into train and val dataframes df_train, df_val = train_test_split(df_train_init, test_size = 0.25) datasets = [df_train, df_val, df_test] #Encoding CVs vectorizer = CountVectorizer(lowercase=True) vec = vectorizer.fit(df_train['TXT'].tolist()) for df in datasets: df['TXT'] = vec.transform(df['TXT']).toarray().tolist() #"""## Export""" df_train.to_csv(os.path.join(data_dir, "train.csv"),index = False) df_val.to_csv(os.path.join(data_dir, "val.csv"),index = False) df_test.to_csv(os.path.join(data_dir, "test.csv"),index = False) print(len(df_train['TXT'][0])) <file_sep>/pre-processing/Labelization.py #!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd from simpledbf import Dbf5 import numpy as np # In[2]: #Download the INSEE Database of all the name given between 1900 and 2017 : for each (name,years), it shows the number of occurence by gender table=Dbf5('nat2017.dbf', codec='cp1252') dfNameAndGender = table.to_dataframe() dfNameAndGender.columns # In[3]: dfNameAndGender["annais"]=pd.to_numeric(dfNameAndGender["annais"],errors="coerce") # In[4]: #We filter the database of name to only have names of people in the active population : between 1950 and 2000 filter= (dfNameAndGender["annais"]>=1950) & (dfNameAndGender["annais"]<=2000) df = dfNameAndGender.where(filter).groupby(['preusuel','sexe'],as_index=False)['nombre'].sum() # In[5]: #As the INSEE database doesn't give us if a name is female or male, we compute a proportion on all of years of studies df["total"]= df.groupby(["preusuel"],as_index=False)["nombre"].transform("sum") df["proportion"]=df["nombre"]/df["total"] #We then decide to associate a gender to all the name that are give mostly (>=70%) to one of the gender. The other are said to be undetermined (for exemple Dominique) filter1 = (df["proportion"]>=0.70) df1=df.where(filter1) list_prenom = df1["preusuel"].unique() df2=df[~df["preusuel"].isin(list_prenom)] df3= df2.groupby(["preusuel"],as_index=False)["sexe"].max() df3["sexe"]=df3["sexe"].apply(lambda x :0) df1=df1[["preusuel","sexe"]] #We produce a final database with all the "determined" name dfFinal=pd.concat([df1,df3]) # In[82]: ''' Input : string Output : Number, 0:Undertermined, 1:Male, 2:Female From the first word of a CV, this function determined if it's Male, Female or Undetermined. To do so, it looks for each word in our name database. If it doesn't find a gender for any of the word, or if it finds more than one gender, it returns undetermined. Else it returns the gender it found. We stop looking when we compute a word that signify an adress, as more often than not the name is situated before the adress. It also helps with the accuracy, as some street name are people name, which leads to more undetermined case. ''' def gender_cvs(cv_first_words): list_gender=[] words=cv_first_words.upper().split() i=0 while i<len(words) and words[i] not in ["RUE","AVENUE","IMPASSE","BOULEVARD","ROUTE"]: if(not dfFinal[dfFinal["preusuel"]==words[i]].empty): list_gender.append(int(dfFinal[dfFinal["preusuel"]==words[i]]["sexe"].values[0])) i+=1 if len(list_gender)==0: return 0 if list_gender.count(1)>=1: if list_gender.count(2)>=1: return 0 else: return 1 else: return 2 # In[112]: #We charge our data CSV and transform it to have only to column : a column with the Id and a column with the content, parsed from pdf csv_data = pd.read_csv("Data/RECBUD/RDS/V_CentraleSup_CV_REC001_tab.csv",sep='\t') csv_data=csv_data[["MATRICULEINT","TXT_CONTENU1","TXT_CONTENU2","TXT_CONTENU3","TXT_CONTENU4","TXT_CONTENU5"]] # In[115]: cropped_data=csv_data[:].copy().fillna(" ") cropped_data["TXT"]=cropped_data["TXT_CONTENU1"]+cropped_data["TXT_CONTENU2"]+cropped_data["TXT_CONTENU3"]+cropped_data["TXT_CONTENU4"]+cropped_data["TXT_CONTENU5"] cropped_data=cropped_data[["MATRICULEINT","TXT"]] cropped_data.dropna(inplace=True) # In[116]: #We create a new column Gender by applying our function to the text cropped_data.loc[:,"GENRE"]=cropped_data["TXT"].apply(lambda x : gender_cvs(x[:20])) # In[117]: # In[ ]: # In[ ]: # In[118]: #We create a dataframe with all the male CV filter_male=(cropped_data["GENRE"]==1) df_male=cropped_data[filter_male] #df_male # In[119]: #We create a dataframe with all the female CV filter_female=(cropped_data["GENRE"]==2) df_female=cropped_data[filter_female] #df_female # In[120]: #We create then export to csv a dataframe with the Id, the content and the gender of the CV by concatenating and shuffling the female and male dataframe dfData=pd.concat([df_male,df_female]).sample(frac=1) dfData.to_csv("data_with_gender_rec.csv",index=False) # In[34]: filter_undetermined=(cropped_data["GENRE"]==0) df_undetermined=cropped_data.where(filter_undetermined) #df_undetermined
941f6307d97545d371c8a487b5fbfc9e5329c9ab
[ "Markdown", "Python", "Text" ]
6
Python
unbiased-recruiting/unbiased-recruiting
32be275d455d9b458b464399f7ac1c9552358276
40076f7718d135988a8d295b1083782bbbcc5eee
refs/heads/master
<file_sep>import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class GAPopulation implements Comparable<GAPopulation>{ private Random rand = new Random(); SudokuBoard sb = new SudokuBoard(); private ArrayList<GAPopulation> populations; public GAPopulation() { initialize(); } public GAPopulation(Integer arr[]) {sb.fill(arr);} public GAPopulation(int size) { populations = new ArrayList(); for(int i = 0; i < size; i++) { populations.add(new GAPopulation()); } } public void initialize() { Integer firstBoard[] = new Integer[81]; for (int i = 0; i < 81; i++) { firstBoard[i] = getRan(10); } sb.fill(firstBoard); } public void breed() { //code to breed ArrayList<GAPopulation> populations2 = new ArrayList<>(); GAPopulation A, B; int count; A = pickBreeder(); B = pickBreeder(); Integer newArray[] = new Integer[81]; for(int i = 0; i < populations.size(); i++) { //create multiple children //nest two loops create new child count = 0; for(int j = 0; j < 9; j++) { if (j > 0) count++; for (int k = 0; k < 9; k++) { if (k > 0) count++; if (getRan(2) == 0) { newArray[count] = A.sb.cells[j][k]; } else { newArray[count] = B.sb.cells[j][k]; } } } populations2.add(new GAPopulation(newArray)); } populations = populations2; } public void crossover() { //code to crossover ArrayList<GAPopulation> populations2 = new ArrayList<>(); GAPopulation A, B; int count, rand = getRan(81) + 1; A = pickBreeder(); B = pickBreeder(); Integer newArray[] = new Integer[81]; for(int i = 0; i < populations.size(); i++) { //create multiple children //nest two loops create new child count = 0; for(int j = 0; j < 9; j++) { if (j > 0) count++; for (int k = 0; k < 9; k++) { if (k > 0) count++; if (count >= rand) { newArray[count] = A.sb.cells[j][k]; } else { newArray[count] = B.sb.cells[j][k]; } } } populations2.add(new GAPopulation(newArray)); } populations = populations2; } public GAPopulation pickBreeder() { int outP = getRan(99) + 1; int ran1; int sizeOfArray = populations.size(); int temp = (int) (sizeOfArray * .1); if(outP > 0 && outP < 41) { ran1 = getRan(temp); ran1 += (temp*9); return populations.get(ran1); } else if(outP > 40 && outP < 61) { ran1 = getRan(temp); ran1 += (temp*8); return populations.get(ran1); } else if(outP > 60 && outP < 71) { ran1 = getRan(temp); ran1 += (temp*7); return populations.get(ran1); } else if(outP > 70 && outP < 79) { ran1 = getRan(temp); ran1 += (temp*6); return populations.get(ran1); } else if(outP > 78 && outP < 86) { ran1 = getRan(temp); ran1 += (temp*5); return populations.get(ran1); } else if(outP > 85 && outP < 91) { ran1 = getRan(temp); ran1 += (temp*4); return populations.get(ran1); } else if(outP > 90 && outP < 95) { ran1 = getRan(temp); ran1 += (temp*3); return populations.get(ran1); } else if(outP > 94 && outP < 98) { ran1 = getRan(temp); ran1 += (temp*2); return populations.get(ran1); } else if(outP > 97 && outP < 100) { ran1 = getRan(temp); ran1 += (temp); return populations.get(ran1); } else if(outP > 99 && outP < 101) { ran1 = getRan(temp); return populations.get(ran1); } else { System.out.println("error in GAPopulations.java, pickBreeder"); return populations.get(-1); } } public void mutate1() { //System.out.println("MUTATE"); //code to mutate Integer arr[] = new Integer[81]; int rand = getRan(1000); int rand1 = getRan(80)+1; int count = 0; for(int i = 0; i < 9; i++) { if(i >= 1) count++; for(int j = 0; j < 9; j++) { if(j >= 1) count++; arr[count] = populations.get(rand).sb.cells[i][j]; } } arr[rand1] = getRan(10); GAPopulation popin = new GAPopulation(arr); populations.set(rand, popin); } public int sort() { Collections.sort(populations); return 0; } public ArrayList<GAPopulation> sortList(ArrayList<GAPopulation> sortList) { Collections.sort(sortList); return sortList; } public int getRan(int size){return rand.nextInt(size);} public boolean checkFinish() { if(populations.get(populations.size()-1).sb.getFitness() == 243) { return true; } return false; } public void run() { int maxfitness = 0,lastfitness = 0,generation = 0; Stopwatch swatch = new Stopwatch(); swatch.start(); while(true) { generation++; sort(); // sort by fitness lastfitness = populations.get(populations.size()-1).sb.getFitness(); if (lastfitness > maxfitness) { maxfitness = lastfitness; System.out.println("Generation: " + generation + ", Fitness = " + maxfitness + ", Elapsed Time: " + swatch.getElapsedTimeSecs()); } if (checkFinish()) {break;} // check if any are complete breed(); //choose to breed or crossbreed //crossover(); for(int i = 0; i < 100; i++) { //mutate mutate1(); } } swatch.stop(); //line to print final sudoku board System.out.println("Process finished in " + swatch.getElapsedTimeSecs() + " seconds."); } @Override public int compareTo(GAPopulation other) { if(sb.getFitness() > other.sb.getFitness()) { return 1; } else if(sb.getFitness() < other.sb.getFitness()) { return -1; } else { return 0; } } public static void main(String ars[]) { GAPopulation p = new GAPopulation(1000); p.run(); } }
9c58cf575b301f8f60cb288c9bf73fe887e45e04
[ "Java" ]
1
Java
jsyfacunda/GeneticAlgorithm
98d281126b7f2e841e1967b69d6249e5d258b386
7ebc4fef612ee029d9ed2dd392707d78c374ce43
refs/heads/master
<repo_name>RyusizzSNU/SomaCube<file_sep>/calibration/static_test.py import pygame import datetime import os import urx import numpy as np import pickle import cv2 import argparse import utils from cam_tool import cam_tool parser = argparse.ArgumentParser() parser.add_argument('--w', type=int, default=9, help="number of cols of the target") parser.add_argument('--h', type=int, default=6, help="number of rows of the target") parser.add_argument('--auto', type=int, default=0) args = parser.parse_args() nexttime = None def wait(): while True: if args.auto != 0: t = datetime.datetime.now() if t > nexttime: return else: for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: return robot = urx.Robot("192.168.1.109") cam = cam_tool('sony') cam.capture('preview.jpg') cam.show('preview.jpg') _, imgpoints = utils.find_imagepoints_from_images([cv2.imread('preview.jpg')], args.w, args.h, show_imgs=1) imgpoints = np.squeeze(imgpoints[0]) C2B = utils.load_static_C2B() C2I = utils.load_static_C2I() i = 0 nexttime = datetime.datetime.now() + datetime.timedelta(seconds = 5) for i in range(len(imgpoints)): wait() p_I = imgpoints[i] p = utils.static_image_to_base(p_I, C2I, C2B) pose = np.array([[0., 1., 0., p[0]], [1., 0., 0., p[1]], [0., 0., -1., 0.19], [0., 0., 0., 1.]]) robot.movex('movel', pose, acc= 0.1, vel=0.2) nexttime = datetime.datetime.now() + datetime.timedelta(seconds = 1) <file_sep>/annotation/cocohandai550/train/README.md [link](https://drive.google.com/open?id=1bn7P3ydes9I5rA1vQ0shrvYPmbiDcZI-) <file_sep>/README.md # SomaCube Soma Cube Assembly 본 프로그램 제작은 2019년도 정부(과학기술정보통신부)의 재원으로 정보통신기획평가원(2018-0-00622-RMI)의 지원을 받았음. 저작권 결과물은 왼쪽 Branch를 "master"가 아닌 "fd" 로 바꿔주면 나옴(branch "fd"에 있음) <file_sep>/deeplab/deeplab manual.md # 사용방법 ##### by <EMAIL> in SNU ## 0. environment 구성 > deeplab 코드는 다음의 github을 참고하였고 environment 구성은 anaconda로 설명되어 있는 그대로 구성하였음 > > https://github.com/jfzhang95/pytorch-deeplab-xception?source=post_page--------------------------- > > 단, pycocotools는 다음 링크를 참조하여 깔아야 문제 없이 python에서 pycocotools를 사용할 수 있을 것 > > https://github.com/philferriere/cocoapi ## 1. code 실행 - for training: 'pytorch-deeplab-xception' 에 들어가서 train_coco.sh 실행 - for valdating: 'pytorch-deeplab-xception' 에 들어가서 val_coco.sh 실행 > run 디렉토리의 최신 experiment 폴더에 저장될 것임 > > training 시에 조금 시간이 지난 후에 model parameter saving이 됨 > > tensorboard 켜서 groundtruth, prediction 확인 가능 ## 2. custom dataset configuration - COCO dataset 형식에 따라 dataset을 만들었음 > train data 500개, val data 50개로 구성handai_annotations_[train/val].json 에 annotation 데이터 저장handai_dataset_img_[train/val] 에 img 데이터 저장 - cube dataset 은 dataset 디렉토리에 있음 > handai_annotations_train.json: annotation json file for training > > handai_annotations_val.json: annotation json file for validation > > handai_dataset_img_train: img files for training > > handai_dataset_img_val: img files for validation ## 3. Dataset Preprocessing 관련 - *'pytorch-deeplab-xception/datasloaders/datasets/coco.py'* 코드를 읽어보면 됨 - *line 16*: NUM_CLASSES = background + cube 7 종류 = 8 카테고리 - *line 18*: 기존에는 COCO dataset에서 사용할 카테고리 index 를 선택적을 넣었으나, 우리는 0~7 모두를 쓸 것이므로 0~7 모두 기입 - *line 31*: annotation specification json file 경로인데, split 에 따라 다른 파일 참조 > dataset 디렉토리에 보면, 'handai_dataset_ann_train' 과 'handai_dataset_ann_val'가 그것임 - *line32*: handai_ann_ids 경로인데, deeplab 에서 필요한 파일인거 같음 > train_coco.sh 나 val_coco.sh 돌리면 handai_ann_ids_[train|val].pth 가 만들어지는데, 해당 파일이 없을때 처음에만 processing 되므로, dataset에 image나 annotation을 추가 혹은 변경하였다면 handai_ann_ids[train|val].pth 를 삭제하고 코드를 실행시킬 것 - *line 35*: handai_dataset_img 경로이고 마찬가지로 split에 다라 다른 파일 참조 > dataset 디렉토리에 보면, 'handai_dataset_img_train' 과 'handai_dataset_img_val'이 그것임 ## 4. trained model - val_coco.sh의 *—resume* 인자에 적혀있는 'run/coco/deeplab-resnet/experiment_1/checkpoint.pth.tar'가 trained model임 - val.py 는 validation img들을 masked_imgs 디렉토리에 저장하고 iou score를 iou.csv 파일에 저장 - *line 173* ~ *line 192* : iou, masked img 저장 코드<file_sep>/calibration/take_photo.py import piggyphoto, pygame import argparse import utils from cam_tool import cam_tool parser = argparse.ArgumentParser() parser.add_argument('--cam_model', type=str, help="Camera model") parser.add_argument('--file_name', type=str, help="file name to save picture") parser.add_argument('--depth', type=int, default=0, help="to use depth map") args = parser.parse_args() cam = cam_tool(args.cam_model) i = 0 filename = args.file_name while not utils.quit_pressed(): cam.capture(filename + '.jpg', args.depth) utils.show(filename + '.jpg') for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: cam.capture(filename + '_' + str(i) + '.jpg', args.depth) i += 1 <file_sep>/calibration/preview.py import argparse import utils from cam_tool import cam_tool parser = argparse.ArgumentParser() parser.add_argument('--cam_model', type=str, help="Camera model. one of rs(realsense) and sony") parser.add_argument('--depth', type=int, default=0, help="to use depth map") args = parser.parse_args() cam = cam_tool(args.cam_model) while not utils.quit_pressed(): filename = 'preview.jpg' cam.capture(filename, args.depth) utils.show(filename) <file_sep>/annotation/cocohandai550/val/README.md [link](https://drive.google.com/open?id=1iTa3Mfqodko9mkiJlmC_F73PL9FHSvX3) <file_sep>/run/real/robot_control.py import urx from urx.robotiq_two_finger_gripper import Robotiq_Two_Finger_Gripper import numpy as np import utils from pyquaternion import Quaternion from time import sleep import datetime class Robot: def __init__(self, ip): self.robot = urx.Robot('192.168.1.109') self.gripper = Robotiq_Two_Finger_Gripper(self.robot) #rot1 = np.array([[0., 1., 0.], [1., 0., 0.], [0., 0., -1.]]) #rot2 = Quaternion(axis=[0., 0., 1.], degrees=48) #rot = np.matmul(rot1, rot2) self.gripper_rot = np.array([[0.7313537, 0.68199836, 0.], [0.68199836, -0.7313537, 0.], [0., 0., -1.]]) self.initial_position = np.array(self.robot.get_pose().array) # 4 * 4 def set_coordinates(self, center, size, H0): self.center = center self.size = size self.H0 = H0 def l2b(self, x): # lattice coordinates to base coordinates if x[2] == 0: h = self.H0 if x[2] == 1: h = self.H0 + self.size + 0.005 if x[2] == 2: h = self.H0 + self.size * 2 + 0.005 return self.center + np.array([float(x[0]) * self.size, float(x[1]) * self.size, h]) def l2rigid(self, x): # lattic coordinates to rigid matrix return utils.rot_trans_to_rigid(self.gripper_rot, self.l2b(x)) def b2rigid(self, x): return utils.rot_trans_to_rigid(self.gripper_rot, x) def move_l(self, x): #rot1 = np.array([[0., 1., 0.], [1., 0., 0.], [0., 0., -1.]]) #rot2 = Quaternion(axis=[0., 0., 1.], degrees=48) #rot = np.matmul(rot1, rot2) print 'move starts at %s'%datetime.datetime.now() self.robot.movex('movel', self.l2rigid(x), acc=0.5, vel=0.05) print 'move ends at %s'%datetime.datetime.now() def move_b(self, x): print 'move starts at %s'%datetime.datetime.now() self.robot.movex('movel', self.b2rigid(x), acc=0.5, vel=0.05) print 'move ends at %s'%datetime.datetime.now() def grip(self): self.gripper.gripper_action(255) #self.gripper.close_gripper() sleep(2) def release(self): self.gripper.gripper_action(96) #self.gripper.open_gripper() sleep(2) def close(self): self.robot.close() <file_sep>/calibration/read_calibration_results.py import pickle import argparse parser = argparse.ArgumentParser() parser.add_argument("--n", type=int) args = parser.parse_args() dirname = 'cali%d/'%args.n ret = pickle.load(open(dirname + 'ret.pkl', 'rb'), encoding='latin1') mtx = pickle.load(open(dirname + 'mtx.pkl', 'rb'), encoding='latin1') dist = pickle.load(open(dirname + 'dist.pkl', 'rb'), encoding='latin1') rvecs = pickle.load(open(dirname + 'rvecs.pkl', 'rb'), encoding='latin1') tvecs = pickle.load(open(dirname + 'tvecs.pkl', 'rb'), encoding='latin1') print('Reprojection Error :\n', ret) print('Camera Matrix :\n', mtx) print('Distortion Coefficient :\n', dist) print('Rotation Vectors :\n', rvecs) print('Translation Vectors :\n', tvecs) <file_sep>/calibration/README.md ------------ Codes for run ------------ intrinsic_calibration.py : 카메라를 intrinsic calibration 하기 위해 사용 * cam, w, h, size 를 argument로 입력. * 격자(target)을 회전시키고 이동시키면서 사진을 찍음(자동 촬영) * results/intrinsic/<cam>/mtx.pkl 에 calibration 결과 (camera_to_image matrix)가 저장됨. make_pos_image_pairs.py : extrinsic calibration을 위한 데이터 쌍을 얻기 위해 사용 * cam, data_dir 를 argument로 입력 * 화살표와 W/S 로 wrist의 위치를 조정, Q/E/H/K/Y/I 로 wrist의 rotation을 조정하고, 스페이스바로 사진을 찍음. * 사진을 찍으면 사진이 <data_dir>/images에 저장되고, 그 시점에서 로봇의 손목 좌표가 <data_dir>/poses 에 저장됨. extrinsic_calibration.py : 카메라를 extrinsic calibration하기 위해 사용 * cam, w, h, size, data_dir 를 argument로 입력 * cam이 static인 경우 : 손목에 붙어있는 target을 static camera로 촬영하는 경우를 상정. camera_to_base matrix와 target_to_wrist matrix를 추정. * cam이 wrist인 경우 : 바닥에 가만히 있는 target을 wrist camera로 촬영하는 경우를 상정. camera_to_wrist matrix와 target_to_base matrix를 추정. * cam이 both인 경우 : target을 wrist camera와 static camera로 동시에 촬영하는 경우를 상정. static_camera_to_base matrix와 wrist_camera_to_wrist matrix를 추정. * intrinsic_calibration.py에서 구한 카메라 정보와, make_pos_image_pairs.py 에서 만든 데이터 쌍들을 이용해 오브젝트 간의 좌표 변환 matrix를 추정 * results/extrinsic/<cam>/mtx.pkl 에 결과가 저장됨. * cam이 static인 경우, camera_to_base matrix와 target_to_wrist matrix를 stack한 array가 저장됨. * cam이 wrist인 경우, camera_to_wrist matrix와 target_to_base matrix를 stack한 array가 저장됨. * cam이 both인 경우, static_camera_to_base matrix와 wrist_camera_to_wrist matrix를 stack한 array가 저장됨. static_test.py : static camera에 대해 calibration한 것을 테스트하기 위해 사용 * h, w, size, auto를 argument로 입력 * 실행 시, static camera가 target을 보고 있어야 함(손목 등에 의해 가려지면 안됨). * static camera가 찍은 image에서 target을 찾고, 변환을 여러 번 시켜서 target의 base좌표계 좌표를 구함. * wrist를 target의 각 좌표로 이동시킴. auto == 1 인 경우 자동으로 이동하고, auto == 0 인 경우 스페이스바를 누르면 이동함. manual_reaching.py : 정해진 위치에 놓여진 블록들을 정해진 모양대로 조립하게끔 로봇을 움직이는 코드 ------------ Modules ------------ cam_tool.py : 카메라 가동 및 조작을 위한 module. 현재는 sony와 realsense 카메라 모델만 지원함. utils.py : 각종 utility function들이 정의되어 있는 module. ------------ Simple test codes ------------ gripper_test.py : Robot gripper를 테스트하기 위한 코드 preview.py : 카메라 연결 및 카메라에 찍히는 화면을 테스트하기 위한 코드 take_photo.py : 카메라로 사진을 찍어서 저장하기 위한 코드<file_sep>/calibration/set_robot_tcp_to_center.py import urx import utils import numpy as np robot = urx.Robot('192.168.1.109') rot = np.array([[0., 1., 0.], [1., 0., 0.], [0., 0., -1.]]) trans = np.array([-0.45165, -0.1984, 0.20]) r = utils.rot_trans_to_rigid(rot, trans, vel=0.05) robot.movex('movel', r) robot.close() <file_sep>/calibration/make_pos_image_pairs.py import pygame import datetime import os import urx import pickle import numpy as np import argparse import utils from cam_tool import cam_tool from pyquaternion import Quaternion parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='ext_data/') parser.add_argument('--cam', type=str, help="cameras to make data pairs with. one of ['static', 'wrist', 'both']") parser.add_argument('--static_cam_model', type=str, default='sony') parser.add_argument('--wrist_cam_model', type=str, default='rs') parser.add_argument('--auto', type=int, default = 0) parser.add_argument('--num_pic', type=int, default=50, help="number of pictures to take") parser.add_argument('--period', type=float, default=0.5, help="period between which pictures would be taken") args = parser.parse_args() utils.create_muldir(args.data_dir, args.data_dir + '/images', args.data_dir + '/poses',\ args.data_dir + '/images/' + args.cam, args.data_dir + '/poses/' + args.cam) #data_dir = '/home/tidyboy/ARAICodes/catkin_ws/src/robot_cal_tools/rct_examples/data/target_6x7_0/' static_on = (args.cam == 'static' or args.cam == 'both') wrist_on = (args.cam == 'wrist' or args.cam == 'both') if static_on: static_cam = cam_tool(args.static_cam_model) if wrist_on: wrist_cam = cam_tool(args.wrist_cam_model) robot = urx.Robot("192.168.1.109") pic_id = 0 initialized = False nexttime = datetime.datetime.now() + datetime.timedelta(seconds = 5) def wait(): while True: if args.auto != 0: t = datetime.datetime.now() if t > nexttime: return else: return def record(): global pic_id if static_on: static_cam.capture(args.data_dir + '/images/%s/static_%d.jpg'%(args.cam, pic_id)) if wrist_on: wrist_cam.capture(args.data_dir + '/images/%s/wrist_%d.jpg'%(args.cam, pic_id)) pos = np.array(robot.get_pose().array) with open(args.data_dir + '/poses/%s/%d.yaml'%(args.cam, pic_id), 'w') as f: pickle.dump(pos, f) pic_id += 1 while not utils.quit_pressed(): wait() if static_on: static_cam.capture('static_view.jpg') if wrist_on: wrist_cam.capture('wrist_view.jpg') view_fname = '' if args.cam == 'both': view_fname = 'concat_view.jpg' concat_view = utils.concat_images_in_dir(['static_view.jpg', 'wrist_view.jpg'], view_fname) elif args.cam == 'static': view_fname = 'static_view.jpg' elif args.cam == 'wrist': view_fname = 'wrist_view.jpg' if not initialized: pygame.display.set_mode(pygame.image.load(view_fname).get_size()) initialized = True utils.show(view_fname) if args.auto == 0: speed = [0, 0, 0, 0, 0, 0] for event in pygame.event.get(): if event.type == pygame.QUIT: break if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: speed[0] = -0.1 if event.key == pygame.K_RIGHT: speed[0] = 0.1 if event.key == pygame.K_DOWN: speed[1] = -0.1 if event.key == pygame.K_UP: speed[1] = 0.1 if event.key == pygame.K_s: speed[2] = -0.1 if event.key == pygame.K_w: speed[2] = 0.1 if event.key == pygame.K_q: speed[3] = -0.1 if event.key == pygame.K_e: speed[3] = 0.1 if event.key == pygame.K_h: speed[4] = -0.1 if event.key == pygame.K_k: speed[4] = 0.1 if event.key == pygame.K_y: speed[5] = -0.1 if event.key == pygame.K_i: speed[5] = 0.1 if event.key == pygame.K_SPACE: record() robot.speedl(speed, acc=0.1, min_time=2) else: record() if(pic_id >= args.num_pic): break nexttime = datetime.datetime.now() + datetime.timedelta(seconds = args.period) robot.close() <file_sep>/pose_estimation/angle.py import cv2 import numpy as np import math def ImageSobel(): sobelx = cv2.Sobel(thr3, -1, 1, 0, ksize=3) sobely = cv2.Sobel(thr3, -1, 0, 1, ksize=3) new_file = open('angle', 'a') img = cv2.imread('block1_0000.jpg', cv2.IMREAD_GRAYSCALE) img_color = cv2.imread('block1_0000.jpg', cv2.IMREAD_COLOR) ret, origin = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) i = 0 tem = ("template/tem%d.jpg" %i) thr3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 351, 40) contours, hierarchy = cv2.findContours(thr3, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) blur = cv2.GaussianBlur(thr3, (3, 3), 0) for cnt in contours: area = cv2.contourArea(cnt) print(area) if(area >2000) : x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 0), 1) print(x) print(y) print(x+w) print(y+h) cropped = img_color[y-30 : y+h+30 , x-30 : x+w+30] img = cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (0, 0, 255), 1) a = box[3][0] - box[0][0] b = box[3][1] - box[0][1] print(box) #cv2.circle(img_color, (cx, cy), 5, (0, 0, 255), 1) z = b / a angle = math.atan(z) s = np.rad2deg(angle) if (s<0) : s += 90 print("angle : %f" % s) new_file.write("\nangle : %f" % s) new_file.close() else : print("angle : %f" % s) new_file.write("\nangle : %f" % s) new_file.close() #cv2.imshow("result", img) #cv2.waitKey(0) cv2.imshow("result", img_color) cv2.waitKey(0) ImageSobel() cv2.destroyAllWindows() <file_sep>/calibration/extrinsic_calibration.py import os import argparse import cv2 import numpy as np import pickle import utils import glob from pyquaternion import Quaternion from scipy.optimize import minimize parser = argparse.ArgumentParser() parser.add_argument('--cam', type=str, help="cameras to calibrate. one of ['static', 'wrist', 'both']") parser.add_argument('--w', type=int, default=9, help="number of cols of the target") parser.add_argument('--h', type=int, default=6, help="number of rows of the target") parser.add_argument('--size', type=float, default=0.0228, help="size of each lattice of target") parser.add_argument('--data_dir', type=str, default='ext_data/') parser.add_argument('--show_imgs', type=int, default=1) parser.add_argument('--method', type=str, default='nelder-mead', help='which optimization method to use') args = parser.parse_args() static_on = (args.cam == 'both' or args.cam == 'static') wrist_on = (args.cam == 'both' or args.cam == 'wrist') s_imgs = [] w_imgs = [] w_points = [] s_points = [] W2Bs = [] def intersection_dict_by_indices(dicts): result = [] indices = [] for i in range(len(dicts)): result.append([]) for key in dicts[0]: all_dict_have_this_key = True for i in range(len(dicts)): if not (key in dicts[i]): all_dict_have_this_key = False if all_dict_have_this_key: for i in range(len(dicts)): result[i].append(dicts[i][key]) indices.append(key) return result, indices img_indices = [] i = 0 s_imgs = utils.find_images_in_dir(args.data_dir + '/images/%s/static'%args.cam) print 'read %d images from static camera'%len(s_imgs) w_imgs = utils.find_images_in_dir(args.data_dir + '/images/%s/wrist'%args.cam) print 'read %d images from wrist camera'%len(w_imgs) if args.cam == 'both': s_imgs, s_points = utils.find_imagepoints_from_images(s_imgs, args.w, args.h, square=True, show_imgs=args.show_imgs) w_imgs, w_points = utils.find_imagepoints_from_images(w_imgs, args.w, args.h, square=True, show_imgs=args.show_imgs, rotate_angle=90) points, img_indices = intersection_dict_by_indices([s_points, w_points]) s_points = points[0] w_points = points[1] elif args.cam == 'static' : s_imgs, s_points = utils.find_imagepoints_from_images(s_imgs, args.w, args.h, square=False, show_imgs=args.show_imgs) s_points, img_indices = intersection_dict_by_indices([s_points]) s_points = s_points[0] elif args.cam == 'wrist' : w_imgs, w_points = utils.find_imagepoints_from_images(w_imgs, args.w, args.h, square=True, show_imgs=args.show_imgs) w_points, img_indices = intersection_dict_by_indices([w_points]) w_points = w_points[0] print 'found patterns in %d images'%len(img_indices) for i in img_indices: with open(args.data_dir + '/poses/%s/%d.yaml'%(args.cam, i), 'rb') as f: W2Bs.append(pickle.load(f)) b = len(W2Bs) n = args.w * args.h if static_on: s_points = np.squeeze(np.array(s_points)) # b * n * 2 s_p_I = np.expand_dims( np.concatenate((s_points, np.ones([b, n, 1])), \ axis=2\ ), 3\ ) # b * n * 3 * 1 if wrist_on: w_points = np.squeeze(np.array(w_points)) # b * n * 2 w_p_I = np.expand_dims( np.concatenate((w_points, np.ones([b, n, 1])), \ axis=2\ ), 3\ ) # b * n * 3 * 1 W2Bs = np.array(W2Bs) # b * 4 * 4 obj_points = np.squeeze(utils.generate_objpoints(1, args.w, args.h, args.size), 0) if static_on: with open('results/intrinsic/static/mtx.pkl', 'rb') as f: s_C2I = pickle.load(f) if wrist_on: with open('results/intrinsic/wrist/mtx.pkl', 'rb') as f: w_C2I = pickle.load(f) if args.cam=='both': w_C2I = np.matmul(np.array([[0, 1, 0], [-1, 0, 640], [0, 0, 1]]), w_C2I) #w_C2I = np.matmul(np.array([[0, -1, 480], [1, 0, 0], [0, 0, 1]]), w_C2I) # initial guess s_C2B_quat_0 = Quaternion(matrix=np.array([[1., 0., 0.], [0., -1., 0.], [0., 0., -1.]])).q s_C2B_trans_0 = np.array([-0.44, -0.1, 1.1]) w_C2W_quat_0 = Quaternion(matrix=np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])).q w_C2W_trans_0 = np.array([-0., -0.09, 0.]) T2B_quat_0 = Quaternion(matrix=np.array([[0., -1., 0.], [-1., 0., 0.], [0., 0., -1.]])).q T2B_trans_0 = np.array([-0.4531, -0.20, 0.]) w_T2W_quat_0 = Quaternion(matrix=np.array([[0., -1., 0.], [1., 0., 0.], [0., 0., 1.]])).q w_T2W_trans_0 = np.array([0.05, -0.05, -0.01]) #s_C2B_0 = np.array([[1., -0., -0., -0.44], [0., -1., 0., -0.1], [0., 0., -1., 1.1], [0., 0., 0., 1.]]) #w_C2W_0 = np.array([[1., 0., 0., -0.02], [0., 1., 0., -0.09], [0., 0., 1., 0.02], [0., 0., 0., 1.]]) step = 0 def static_loss(x): # x : concatenation of s_C2B_quat, s_C2B_trans, w_T2W_quat, w_T2W_trans. shape : (14) global step step += 1 s_C2B = utils.quat_trans_to_rigid(x[0:4], x[4:7]) # 4 * 4 w_T2W = utils.quat_trans_to_rigid(x[7:11], x[11:14]) # 4 * 4 p_T = np.reshape(obj_points, [-1, 3]) p_T = np.concatenate([p_T, np.ones([n, 1])], 1) # n * 4 p_T = np.expand_dims(p_T, 2) # n * 4 * 1 p = np.matmul(w_T2W, p_T) # n * 4 * 1 p = np.matmul(np.expand_dims(W2Bs, 1), p) # b * n * 4 * 1 p = np.matmul(np.linalg.inv(s_C2B), p) # b * n * 4 * 1 p = p[:, :, :3, :] # b * n * 3 * 1 p = np.matmul(s_C2I, p) # b * n * 3 * 1 p = p / np.expand_dims(p[:, :, 2, :], axis=2) l = np.mean(np.square(p - s_p_I)) if step % 1000 == 0: print 'step%d : %f'%(step, l) return l def w_reprojected(x): w_C2W = utils.quat_trans_to_rigid(x[0:4], x[4:7]) # 4 * 4 T2B = utils.quat_trans_to_rigid(x[7:11], x[11:14]) # 4 * 4 p_T = np.reshape(obj_points, [-1, 3]) p_T = np.concatenate([p_T, np.ones([n, 1])], 1) # n * 4 p_T = np.expand_dims(p_T, 2) # n * 4 * 1 p = np.matmul(T2B, p_T) # n * 4 * 1 p = np.matmul(np.expand_dims(np.linalg.inv(W2Bs), 1), p) # b * n * 4 * 1 p = np.matmul(np.linalg.inv(w_C2W), p) # b * n * 4 * 1 p = p[:, :, :3, :] # b * n * 3 * 1 p = np.matmul(w_C2I, p) # b * n * 3 * 1 p = p / np.expand_dims(p[:, :, 2, :], axis=2) return p def wrist_loss(x): # x : concatenation of w_C2W_quat, w_C2W_trans, T2B_quat, T2B_trans. shape : (14) global step step += 1 p = w_reprojected(x) l = np.mean(np.square(p - w_p_I)) if step % 1000 == 0: print 'step%d : %f'%(step, l) return l s_C2B_ = None def w_reprojected_to_s(x): if len(x) == 7: s_C2B = s_C2B_ w_C2W = utils.quat_trans_to_rigid(x[0:4], x[4:7]) else: s_C2B = utils.quat_trans_to_rigid(x[0:4], x[4:7]) # 4 * 4 w_C2W = utils.quat_trans_to_rigid(x[7:11], x[11:14]) # 4 * 4 w_C2B = np.matmul(W2Bs, w_C2W) # b * 4 * 4 w_I2C = np.linalg.inv(w_C2I) # 3 * 3 w_p_C = np.matmul(w_I2C, w_p_I) # b * n * 3 * 1 w_p_C = np.concatenate((w_p_C, np.ones([b, n, 1, 1])), axis=2) # b * n * 4 * 1 w_p_B = np.matmul(np.expand_dims(w_C2B, 1), w_p_C) # b * n * 4 * 1 o_C = [[0], [0], [0], [1]] # 4 * 1 o_B = np.expand_dims(np.matmul(w_C2B, o_C), 1) # b * 1 * 4 * 1 p = o_B - (o_B[:, :, 2:3, :] / (o_B[:, :, 2:3, :] - w_p_B[:, :, 2:3, :])) * (o_B - w_p_B) # b * n * 4 * 1 p = np.matmul(np.linalg.inv(s_C2B), p) # b * n * 4 * 1 p = p[:, :, :3, :] # b * n * 3 * 1 p = np.matmul(s_C2I, p) # b * n * 3 * 1 p = p / np.expand_dims(p[:, :, 2, :], axis=2) return p def repr_loss(x): # x : concatenation of s_C2B_quat, s_C2B_trans, w_C2W_quat, w_C2W_trans. shape : (14) global step step += 1 p = w_reprojected_to_s(x) l = np.mean(np.square(p - s_p_I)) if step % 1000 == 0: print 'step%d : %f'%(step, l) return l if args.cam == 'both': x = minimize(repr_loss, np.concatenate([s_C2B_quat_0, s_C2B_trans_0, w_C2W_quat_0, w_C2W_trans_0]), method = args.method, options={'xtol':1e-9, 'maxiter' : 100000, 'maxfev' : 640000, 'disp' : True}).x s_C2B_ = utils.quat_trans_to_rigid(x[0:4], x[4:7]) x_ = minimize(repr_loss, x[7:14], method= args.method, options={'xtol':1e-9, 'maxiter' : 100000, 'maxfev' : 640000, 'disp' : True}).x x = np.concatenate((x[0:7], x_)) p = w_reprojected_to_s(x) for i in range(len(w_imgs)): s_img_w_reprojected = np.copy(s_imgs[i]) for j in range(n): s_img_w_reprojected = cv2.circle(s_img_w_reprojected, (int(p[i][j][0][0]), int(p[i][j][1][0])), 3, (0, 0, 255), -1) cv2.imshow('s_img_w_reprojected', s_img_w_reprojected) cv2.waitKey(0) elif args.cam == 'wrist': x = minimize(wrist_loss, np.concatenate([w_C2W_quat_0, w_C2W_trans_0, T2B_quat_0, T2B_trans_0]), method = args.method, options={'xtol':1e-5, 'maxiter' : 100000, 'maxfev' : 640000, 'disp' : True}).x p = w_reprojected(x) for i in range(len(w_imgs)): w_img_reprojected = np.copy(w_imgs[i]) for j in range(n): w_img_reprojected = cv2.circle(w_img_reprojected, (int(p[i][j][0][0]), int(p[i][j][1][0])), 3, (0, 0, 255), -1) cv2.imshow('w_img_reprojected', w_img_reprojected) cv2.waitKey(0) elif args.cam == 'static': x = minimize(static_loss, np.concatenate([s_C2B_quat_0, s_C2B_trans_0, w_T2W_quat_0, w_T2W_trans_0]), method = args.method, options={'xtol':1e-5, 'maxiter' : 10000, 'maxfev' : 640000, 'disp' : True}).x x0 = utils.quat_trans_to_rigid(x[0:4], x[4:7]) x1 = utils.quat_trans_to_rigid(x[7:11], x[11:14]) print x0 print x1 utils.create_muldir('results', 'results/extrinsic/', 'results/extrinsic/%s'%args.cam) with open('results/extrinsic/%s/mtx.pkl'%args.cam, 'w') as f: pickle.dump(np.stack([x0, x1], 0), f) <file_sep>/calibration/utils.py import os import cv2 import numpy as np import pickle import pygame from pyquaternion import Quaternion def create_dir(dirname): if not os.path.exists(dirname): print("Creating %s"%dirname) os.makedirs(dirname) else: pass def create_muldir(*args): for dirname in args: create_dir(dirname) def concat_images(images): h = images[0].shape[0] for i in range(len(images)): if i == 0: continue img = images[i] img = cv2.resize(img, dsize = (img.shape[1] * h / img.shape[0], h), interpolation = cv2.INTER_CUBIC) images[i] = img return np.concatenate(images, axis=1) def concat_images_in_dir(fnames, result_fname): images = [] for f in fnames: images.append(cv2.imread(f)) image = concat_images(images) cv2.imwrite(result_fname, image) def find_images_in_dir(name): images = [] i = 0 while(True): try: with open('%s_%d.jpg'%(name, i)) as f: images.append(cv2.imread('%s_%d.jpg'%(name, i))) i += 1 except IOError: break return images def generate_objpoints(num, target_w, target_h, target_size): # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((target_w * target_h, 3), np.float32) objp[:, :2] = np.mgrid[0:target_w, 0:target_h].T.reshape(-1, 2) objp = objp * target_size objp = np.tile(np.expand_dims(objp, 0), [num, 1, 1]) return objp def rotate_image(img, deg): # rotate image deg degree, counterclockwise if deg == 0: return img rows, cols = img.shape[:2] M = cv2.getRotationMatrix2D((cols/2, rows/2), deg, 1) return cv2.warpAffine(img, M, (cols, rows)) def find_imagepoints_from_images(images, w, h, square=True, show_imgs=0, rotate_angle=0): # Arrays to store object points and image points from all the images. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) read_imgs = [] points_dict = {} for i in range(len(images)): img = images[i] img = rotate_image(img, rotate_angle) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Find the chess board corners if square: ret, corners = cv2.findChessboardCorners(img, (w, h), None) else: ret, corners = cv2.findCirclesGrid(img, (w, h), None) # If found, add object points, image points (after refining them) if ret == True: cv2.cornerSubPix(img, corners, (11, 11), (-1, -1), criteria) points_dict[i] = corners read_imgs.append(img) # Draw and display the corners img = cv2.drawChessboardCorners(img, (w, h), corners, ret) if show_imgs != 0: cv2.imshow('img', img) cv2.waitKey(0) print("succeeded to find points in %d imgs", len(read_imgs)) return read_imgs, points_dict def quit_pressed(): for event in pygame.event.get(): if event.type == pygame.QUIT: return True return False def show_image(picture): surface = pygame.display.get_surface() surface.blit(picture, (0, 0)) pygame.display.flip() def show(fname): picture = pygame.image.load(fname) show_image(picture) def rot_trans_to_rigid(rot, trans): rot = np.concatenate([rot, np.expand_dims(trans, 1)], 1) return np.concatenate([rot, [[0., 0., 0., 1.]]], 0) def quat_trans_to_rigid(quat, trans): # quat : quaternion of shape (4) # trans : translation vector of shape (3) rot = Quaternion(quat).rotation_matrix return rot_trans_to_rigid(rot, trans) def axis_angle_trans_to_rigid(axis, deg, trans): rot = Quaternion(axis=axis, degrees=deg).rotation_matrix return rot_trans_to_rigid(rot, trans) def load_static_C2B(calib='static'): with open('results/extrinsic/%s/mtx.pkl'%calib, 'rb') as f: C2B = pickle.load(f)[0] print 'static C2B from %s calibration:\n'%calib, C2B return C2B def load_static_C2I(): with open('results/intrinsic/static/mtx.pkl', 'rb') as f: C2I = pickle.load(f) print 'static C2I :\n', C2I return C2I def load_wrist_C2W(calib='wrist'): with open('results/extrinsic/%s/mtx.pkl'%calib, 'rb') as f: if calib == 'both': C2W = pickle.load(f)[1] print 'wrist C2W from both calibration:\n', C2W elif calib == 'wrist': C2W = pickle.load(f)[0] print 'wrist C2W from wrist calibration:\n', C2W return C2W def load_wrist_C2I(): with open('results/intrinsic/wrist/mtx.pkl', 'rb') as f: C2I = pickle.load(f) print 'wrist C2I :\n', C2I return C2I def static_image_to_base(p_I, C2I, C2B): p_I = [[p_I[0]], [p_I[1]], [1]] p_C = np.matmul(np.linalg.inv(C2I), p_I) p_B = np.matmul(C2B, np.concatenate((p_C, [[1]]), axis=0)) o_C = [[0], [0], [0], [1]] o_B = np.matmul(C2B, o_C) p = o_B - (o_B[2] / (o_B[2] - p_B[2])) * (o_B - p_B) return p def wrist_image_to_base(p_I, C2I, C2W, W2B): p_I = [[p_I[0]], [p_I[1]], [1]] p_C = np.matmul(np.linalg.inv(C2I), p_I) p_W = np.matmul(C2W, np.concatenate((p_C, [[1]]), axis=0)) p_B = np.matmul(W2B, p_W) o_C = [[0], [0], [0], [1]] o_W = np.matmul(C2W, o_C) o_B = np.matmul(W2B, o_W) p = o_B - (o_B[2] / (o_B[2] - p_B[2])) * (o_B - p_B) return p def base_to_static_image(p_B, C2I, C2B): p_B = [[p_B[0]], [p_B[1]], [p_B[2]], [1]] p_C = np.matmul(np.linalg.inv(C2B), p_B) p_C = p_C[:3, :] p_I = np.squeeze(np.matmul(C2I, p_C)) p_I = p_I / p_I[2] return p_I[:2] def base_to_wrist_image(p_B, C2I, C2W, W2B): p_B = [[p_B[0]], [p_B[1]], [p_B[2]], [1]] p_W = np.matmul(np.linalg.inv(W2B), p_B) p_C = np.matmul(np.linalg.inv(C2W), p_W) p_C = p_C[:3, :] p_I = np.squeeze(np.matmul(C2I, p_C)) p_I = p_I / p_I[2] return p_I[:2] <file_sep>/calibration/intrinsic_calibration.py import time import datetime import numpy as np import cv2 import os import glob import pickle import argparse import utils from cam_tool import cam_tool parser = argparse.ArgumentParser() parser.add_argument('--cam', type=str, help="Camera to calibrate. one of 'static' and 'wrist'") parser.add_argument('--static_cam_model', type=str, default='sony') parser.add_argument('--wrist_cam_model', type=str, default='rs') parser.add_argument('--w', type=int, default=9, help="number of cols of the target") parser.add_argument('--h', type=int, default=6, help="number of rows of the target") parser.add_argument('--size', type=float, default=0.0228, help="size of each lattice of target(meter)") parser.add_argument('--num_pic', type=int, default=50, help="number of pictures to take") parser.add_argument('--period', type=float, default=0.5, help="period between which pictures would be taken") args = parser.parse_args() filename = 'int_cal_pic' if args.cam == 'static': cam = cam_tool(args.static_cam_model) elif args.cam == 'wrist': cam = cam_tool(args.wrist_cam_model) nexttime = datetime.datetime.now() + datetime.timedelta(seconds = 5) t_list = [] for i in range(args.num_pic): while True: t = datetime.datetime.now() if t > nexttime: t_list.append(t) break cam.capture('%s_%d.jpg'%(filename, i)) utils.show('%s_%d.jpg'%(filename, i)) nexttime = nexttime + datetime.timedelta(seconds = args.period) images = utils.find_images_in_dir(filename) imgs, imgpoints = utils.find_imagepoints_from_images(images, args.w, args.h) # 2d points in image plane. objpoints = utils.generate_objpoints(len(imgpoints), args.w, args.h, args.size) # 3d point in real world space imgpoints = np.array([imgpoints[i] for i in imgpoints]) cv2.destroyAllWindows() print (imgs[0].shape[1], imgs[0].shape[0]) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, (imgs[0].shape[1], imgs[0].shape[0]), None, None) print(ret) print(mtx) print(dist) print(rvecs) print(tvecs) utils.create_muldir('results', 'results/intrinsic', 'results/intrinsic/%s'%args.cam) pickle.dump(np.array(ret), open('results/intrinsic/%s/ret.pkl'%args.cam, 'wb')) pickle.dump(np.array(mtx), open('results/intrinsic/%s/mtx.pkl'%args.cam, 'wb')) pickle.dump(np.array(dist), open('results/intrinsic/%s/dist.pkl'%args.cam, 'wb')) pickle.dump(np.array(rvecs), open('results/intrinsic/%s/rvecs.pkl'%args.cam, 'wb')) pickle.dump(np.array(tvecs), open('results/intrinsic/%s/tvecs.pkl'%args.cam, 'wb')) cam.exit() for img_fname in glob.glob('%s_*.jpg'%filename): os.remove(img_fname) <file_sep>/calibration/reprojection_error.py import os import urx import pygame import numpy as np import pickle import cv2 import argparse import utils from cam_tool import cam_tool parser = argparse.ArgumentParser() parser.add_argument('--cam', type=str, help='camera to calculate reprojection error') parser.add_argument('--calib', type=str, help='calibration method to evaluate') parser.add_argument('--w', type=int, default=9, help="number of cols of the target") parser.add_argument('--h', type=int, default=6, help="number of rows of the target") parser.add_argument('--size', type=float, default=0.0228, help='size of each lattice of target') parser.add_argument('--static_cam_model', type=str, default='sony') parser.add_argument('--wrist_cam_model', type=str, default='rs') parser.add_argument('--proj_to_image', type=int, default=1) args = parser.parse_args() if args.cam == 'static': cam = cam_tool(args.static_cam_model) elif args.cam == 'wrist': cam = cam_tool(args.wrist_cam_model) cam.capture('preview.jpg') img = cv2.imread('preview.jpg') _, imgpoints = utils.find_imagepoints_from_images([img], args.w, args.h, show_imgs=1) imgpoints = np.squeeze(imgpoints[0]) robot = urx.Robot('192.168.1.109') W2B = np.array(robot.get_pose().array) center = np.array([-0.45165, -0.1984, 0]) objpoints = utils.generate_objpoints(1, args.w, args.h, args.size) # 1 * (w*h) * 3 objpoints = objpoints * np.array([1., -1., 1.]) + center + np.array([args.w - 1, 0., 0.], dtype=float) * -args.size objpoints = np.squeeze(objpoints, 0) err_sum = 0 if args.cam == 'static': C2B = utils.load_static_C2B(calib=args.calib) C2I = utils.load_static_C2I() if args.proj_to_image != 0: for i in range(len(objpoints)): p_B = objpoints[i] p = utils.base_to_static_image(p_B, C2I, C2B) img = cv2.circle(img, (int(p[0]), int(p[1])), 3, (0, 0, 255), -1) err = np.sqrt(np.sum(np.square(p - imgpoints[i]))) print p, imgpoints[i], err err_sum += err cv2.imshow('img', img) cv2.waitKey(0) else: for i in range(len(imgpoints)): p_I = imgpoints[i] p = utils.static_image_to_base(p_I, C2I, C2B) p = np.squeeze(p)[:3] err = np.sqrt(np.sum(np.square(p - objpoints[i]))) print p, objpoints[i], err err_sum += err elif args.cam == 'wrist': C2W = utils.load_wrist_C2W(calib=args.calib) C2I = utils.load_wrist_C2I() if args.proj_to_image != 0: for i in range(len(objpoints)): p_B = objpoints[i] p = utils.base_to_wrist_image(p_B, C2I, C2W, W2B) img = cv2.circle(img, (int(p[0]), int(p[1])), 3, (0, 0, 255), -1) err = np.sqrt(np.sum(np.square(p - imgpoints[i]))) print p, imgpoints[i], err err_sum += err cv2.imshow('img', img) cv2.waitKey(0) else: err_sum = 0 for i in range(len(imgpoints)): p_I = imgpoints[i] p = utils.wrist_image_to_base(p_I, C2I, C2W, W2B) p = np.squeeze(p)[:3] err = np.sqrt(np.sum(np.square(p - objpoints[i]))) print p, objpoints[i], err err_sum += err print err_sum / len(imgpoints) robot.close() <file_sep>/calibration/gripper_test.py import urx from urx.robotiq_two_finger_gripper import Robotiq_Two_Finger_Gripper robot = urx.Robot('192.168.1.109') gripper = Robotiq_Two_Finger_Gripper(robot) gripper.gripper_action(96) gripper.close_gripper() <file_sep>/calibration/manual_reaching.py import numpy as np import pickle import utils import robot_control center = np.array([-0.4531, -0.20, 0.]) H0 = 0.20 size = 0.024 robot = robot_control.Robot('192.168.1.109') robot.set_coordinates(center, size, H0) robot.move_l([0, -1, 2]) robot.release() robot.move_l([0, -1, 0]) robot.grip() robot.move_l([-3, -1, 0]) robot.release() robot.move_l([-3, -1, 2]) robot.move_l([5, 1, 2]) robot.move_l([5, 1, 1]) robot.grip() robot.move_l([0, 1, 1]) robot.release() robot.move_l([0, 1, 2]) robot.move_l([-4, -3, 2]) robot.move_l([-4, -3, 0]) robot.grip() robot.move_l([-4, -3, 1]) robot.move_l([-4, -1, 1]) robot.release() robot.move_l([-4, -1, 2]) robot.move_l([1, -5, 2]) robot.move_l([1, -5, 0]) robot.grip() robot.move_l([0, -2, 0]) robot.release() robot.move_l([0, -2, 2]) robot.move_l([5, -4, 2]) robot.move_l([5, -4, 1]) robot.grip() robot.move_l([0, -4, 1]) robot.move_l([0, -3, 1]) robot.release() robot.move_l([0, -3, 2]) robot.move_l([-3, -7, 2]) robot.move_l([-3, -7, 0]) robot.grip() robot.move_l([-3, -7, 1]) robot.move_l([-2, -2, 1]) robot.release() robot.move_l([-2, -2, 2]) robot.close() <file_sep>/mask_rcnn/datasets/handai-trainval/coco/readme.txt COCO dataset goes here Example: val2014/ annotations/instances_val2014.json<file_sep>/annotation/README.md annotation ================ - cocohandai550/, data4cv/: 디렉토리는 딥러닝 학습용, data4cv는 computer vision 코드의 검증용으로 사용. 세부적인 레이블링의 기준이 다를 뿐 같은 코드를 사용. - cocohandai/annotations_train.json: training annotation 파일 (레이블) - cocohandai/annotations_train.json: validation annotation 파일 (레이블) - cocohandai550/train: training 이미지 - cocohandai550/val: validation 이미지 - cocohandai550/ann_train: training 이미지에서 이미지들의 annotation 조각(json파일)들의 모음 - cocohandai550/ann_val: validation 이미지에서 이미지들의 annotation 조각(json파일)들의 모음 - bbseg.py: 이미지의 annotation(segementation, bounding box)를 만들어 ann_train, ann_val에 저장함 - collect.py: 사진기와 pc를 연결해 사진을 찍고 저장함 - merge_ann_train.py: 이미지들의 annotation 조각(train)을 합침 - merge_ann_val.py: 이미지들의 annotation 조각(val)을 합침 <file_sep>/mask_rcnn/datasets/handai/bbseg.py import argparse import os import os.path as osp import pygame import json import time from pycocotools.coco import COCO colors = [ pygame.Color("red"), pygame.Color("blue"), pygame.Color("brown"), pygame.Color("green"), pygame.Color("purple"), pygame.Color("orange"), pygame.Color("yellow"), ] cat_map = { "red": 1, "blue": 2, "brown": 3, "green": 4, "purple": 5, "orange": 6, "yellow": 7 } ''' "annotations": [ { "id": 1, "category_id": 1, "iscrowd": 0, "segmentation": [[0.0, 0.0, 100.0, 0.0, 100.0, 100.0, 0.0, 100.0]], "image_id": 1, "bbox": [0.0, 0.0, 100.0, 100.0] } ] ''' #python3 def get_sorted_img_id_list(annFile): with open(annFile, "r") as f: raw = json.load(f) return [(x["file_name"], x["id"]) for x in sorted(raw["images"], key=lambda x: x["id"])] class Annotation: def __int__(self): ann_list try: input = raw_input except NameError: pass def print_info(): print( ''' ======================================== [A]: new category annotation (exit/save current annotation) [S]: next point group for current annotation [R]: redo current image [N]: next image (exit/save current annotation) [Q]: quit unexpectedly (not recommended) ======================================== ''') def main(): prs = argparse.ArgumentParser() prs.add_argument("-d", "--dataset_path", type=str, default='handai_dataset_img') prs.add_argument("-a", "--annotation", type=str, default='handai_annotations.json') prs.add_argument("-o", "--output_path", type=str, default='handai_dataset_ann') prs.add_argument("-n", "--output_name", type=str, default='out.json') prs.add_argument("-s", "--start_index", type=int, default=0) prs.add_argument("-e", "--end_index", type=int, default=200) prs.add_argument("-c", "--single_category", type=int, default=-1) args = prs.parse_args() os.makedirs(args.output_path, exist_ok=True) coco=COCO(args.annotation) dataset_path = args.dataset_path img_id_list = get_sorted_img_id_list(args.annotation)[args.start_index:args.end_index] n = len(img_id_list) i = 0 assert n > 0 pygame.init() pic = pygame.image.load(osp.join(dataset_path, img_id_list[0][0])) pygame.display.set_mode(pic.get_size()) screen = pygame.display.get_surface() done = False ann_id = 1 cat_id = None annotations = [] while i < n and not done: file_name = img_id_list[i][0] file_id = img_id_list[i][1] file_full_name = osp.join(dataset_path,file_name) pic = pygame.image.load(file_full_name) screen.blit(pic, (0, 0)) pygame.display.flip() img_done = False while not(img_done): #print("1") time.sleep(0.1) if args.single_category > 0: cat_id = args.single_category else: cat_id = input("Catergory (1~7/color)? ") if cat_id in '1234567': cat_id = int(cat_id) elif cat_id in cat_map.keys(): cat_id = cat_map[cat_id] elif cat_id == 'n': img_done = True i += 1 continue else: continue ann_done = False ann = { "id": ann_id, "category_id": cat_id, "iscrowd": 0, "segmentation": [], "image_id": file_id, "bbox": [] } n_pt = 0 seg = [[]] while not(ann_done): #print("2") key_down = False print_info() while not(key_down): #print("3") time.sleep(0.01) for event in pygame.event.get(): if event.type == pygame.QUIT: key_down = True key = "q" elif event.type == pygame.KEYDOWN: #print(event) if event.key == pygame.K_a: key = "a" key_down = True elif event.key == pygame.K_s: key = "s" key_down = True elif event.key == pygame.K_r: key = "r" key_down = True elif event.key == pygame.K_n: key = "n" key_down = True elif event.key == pygame.K_q: key = "q" key_down = True elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() pos = [float(pos[0]), float(pos[1])] n_pt += 1 if n_pt >= 2: pygame.draw.line(screen, colors[cat_id-1], prev_pos, pos, width=1) pygame.display.flip() prev_pos = pos seg[-1].extend(pos) if key in 'anr': ann_done = True if key == 's': seg.append([]) n_pt = 0 if key == 'n': img_done = True i += 1 if key == 'r': while len(annotations) > 0 and annotations[-1]['image_id'] == file_id: annotations = annotations[:-1] img_done = True if key == 'q': done = img_done = ann_done = True if ann_done and key != 'r': ann["segmentation"] = seg flat = [item for sublist in seg for item in sublist] x_flat = flat[::2] y_flat = flat[1::2] x_min = min(x_flat) y_min = min(y_flat) x_max = max(x_flat) y_max = max(y_flat) bbox = [x_min, y_min, x_max-x_min, y_max-y_min] ann["bbox"] = bbox annotations.append(ann) ann_id += 1 print(json.dumps(annotations)) with open(osp.join(args.output_path, args.output_name), 'w') as f: json.dump(annotations, f) if __name__ == '__main__': main() <file_sep>/annotation/cocohandai550/collect.py import argparse import os.path as osp import piggyphoto, pygame import os import time #python2 # 종료 상황을 감지 def quit_pressed(): for event in pygame.event.get(): if event.type == pygame.QUIT: return True if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: return True return False # 키보드의 "." 키가 눌렸는지 감지 def key_pressed(): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_PERIOD: return True return False def show(main_surface, file_name): picture = pygame.image.load(file_name) main_surface.blit(picture, (0, 0)) pygame.display.flip() def screenshot(cam, file_name): cam.capture_preview(file_name) def main(): prs = argparse.ArgumentParser() prs.add_argument("-p", "--prefix_name", type=str, default='') prs.add_argument("-s", "--suffix_index", type=int, default=-1) prs.add_argument("-n", "--number_of_data", type=int, default=1) ''' [실행 예] python2 collect.py -p block1 -n 20 => 현재 디렉토리에 "block1_0.jpg" ~ "block1_20.jpg" 사진을 저장함 ''' args = prs.parse_args() pygame.init() prefix = args.prefix_name if args.prefix_name == '': assert args.suffix_index >= 0 dir_path = 'dataset' n = args.number_of_data #screen = pygame.display.set_mode((100, 100)) # 카메라를 통해 비친 화면을 통해 계속해서 보여줌 cam = piggyphoto.camera() cam.leave_locked() cam.capture_preview('preview.jpg') picture = pygame.image.load("preview.jpg") pygame.display.set_mode(picture.get_size()) main_surface = pygame.display.get_surface() os.remove('preview.jpg') if n <= 1: file_name = osp.join(dir_path, args.prefix_name) while not quit_pressed(): cam.capture_preview(file_name) show(main_surface, file_name) #pygame.display.flip() #print(file_name) else: i = 0 done = False # n개의 이미지만큼 촬 while i < n and not done: key_pressed = False # "."키가 눌렸으면 저장함 file_name = osp.join(dir_path, '{}_{:04d}.jpg'.format(args.prefix_name, i)) while not(key_pressed): cam.capture_preview(file_name) show(main_surface, file_name) #pygame.display.flip() #print(file_name) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True key_pressed = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: done = True key_pressed = True if event.key == pygame.K_PERIOD: i += 1 key_pressed = True if done: os.remove(file_name) if __name__ == '__main__': main() <file_sep>/deeplab/dataset/merge_ann_train.py import json file_list = [ "ann_train/out_block1.json", "ann_train/out_block2.json", "ann_train/out_block3.json", "ann_train/out_block4.json", "ann_train/out_block5.json", "ann_train/out_block6.json", "ann_train/out_block7.json", "ann_train/out_scatter_block1.json", "ann_train/out_scatter_block2.json", "ann_train/out_scatter_block3.json", "ann_train/out_scatter_block4.json", "ann_train/out_scatter_block5.json", "ann_train/out_scatter_block6.json", "ann_train/out_scatter_block7.json", "ann_train/out_cube.json", "ann_train/out2_block1.json", "ann_train/out2_block2.json", "ann_train/out2_block3.json", "ann_train/out2_block4.json", "ann_train/out2_block5.json", "ann_train/out2_block6.json", "ann_train/out2_block7.json", "ann_train/out2_scatter_block1.json", "ann_train/out2_scatter_block2.json", "ann_train/out2_scatter_block3.json", "ann_train/out2_scatter_block4.json", "ann_train/out2_scatter_block5.json", "ann_train/out2_scatter_block6.json", "ann_train/out2_scatter_block7.json", "ann_train/out2_cube1.json", "ann_train/out2_cube2.json", "ann_train/out2_cube3.json"] data = [] id_offset = 0 for file_name in file_list: with open(file_name, "r") as f: loaded_data = json.load(f) for ann in loaded_data: ann["id"] += id_offset data.extend(loaded_data) id_offset += len(loaded_data) print(id_offset) with open("ann_train/out_merged.json", "w") as f: json.dump(data, f)<file_sep>/calibration/auto_reaching.py import urx import cv2 import math import numpy as np import utils from PIL import Image, ImageFile, ImageFilter import robot_control from cam_tool import cam_tool import grippoint size = 0.024 H0 = 0.20 H1 = H0 + size + 0.005 H2 = H1 + size robot = robot_control.Robot('192.168.1.109') cam = cam_tool('sony') cam.capture('view.jpg') grip = grippoint.find_grip_points('view.jpg') # 7 * 2 C2B = utils.load_static_C2B() C2I = utils.load_static_C2I() print grip, C2B, C2I poses = [] for p_I in grip: p = utils.static_image_to_base(p_I, C2I, C2B) poses.append(p) print p o_x = poses[4][0] o_y = poses[4][1] robot.move_b([poses[3][0], poses[3][1], H2]) robot.release() robot.move_b([poses[3][0], poses[3][1], H0]) robot.grip() robot.move_b([poses[3][0], poses[3][1], H2]) robot.move_b([o_x + size, o_y - size, H2]) robot.move_b([o_x + size, o_y - size, H1]) robot.release() robot.move_b([o_x + size, o_y - size, H2]) robot.move_b([poses[2][0], poses[2][1], H2]) robot.move_b([poses[2][0], poses[2][1], H0]) robot.grip() robot.move_b([poses[2][0], poses[2][1], H2]) robot.move_b([o_x + size*3, o_y, H2]) robot.move_b([o_x + size*3, o_y, H1]) robot.release() robot.move_b([o_x + size*3, o_y, H2]) temp_pos = np.array([poses[0][0] - size, poses[0][1] + size, 0]) robot.move_b(temp_pos + [0, 0, H2]) robot.move_b(temp_pos + [0, 0, H0]) robot.grip() robot.move_b(temp_pos + [0, 0, H2]) robot.move_b([o_x, o_y - size, H2]) robot.move_b([o_x, o_y - size, H1]) robot.release() robot.move_b([o_x, o_y - size, H2]) robot.move_b([poses[6][0], poses[6][1], H2]) robot.move_b([poses[6][0], poses[6][1], H0]) robot.grip() robot.move_b([poses[6][0], poses[6][1], H2]) robot.move_b([o_x + size*4, o_y - size*2, H2]) robot.move_b([o_x + size*4, o_y - size*2, H0]) robot.release() robot.move_b([o_x + size*4, o_y - size*2, H2]) robot.move_b([poses[1][0], poses[1][1], H2]) robot.move_b([poses[1][0], poses[1][1], H1]) robot.grip() robot.move_b([poses[1][0], poses[1][1], H2]) robot.move_b([o_x + size*4, o_y - size*3, H2]) robot.move_b([o_x + size*4, o_y - size*3, H1]) robot.release() robot.move_b([o_x + size*4, o_y - size*3, H2]) robot.move_b([poses[5][0], poses[5][1], H2]) robot.move_b([poses[5][0], poses[5][1], H0]) robot.grip() robot.move_b([poses[5][0], poses[5][1], H2]) robot.move_b([o_x + size*1.5, o_y - size*3, H2]) robot.move_b([o_x + size*1.5, o_y - size*3, H1]) robot.release() robot.move_b([o_x + size*1.5, o_y - size*3, H2]) <file_sep>/pose_estimation/README.md pose_estimation ================ - pp3.py와 grippoint.py는 DeeplabModule()을 통해 7가지 block의 종류와 위치를 구하여 로봇이 block을 잡아야 할 좌표를 계산함. - segmentation/deepLab/deeplab manual.md에 따라 환경 구축해야 함. - deeplab.run()에 학습시키고 싶은 image를 넣어주고 코드 전체를 실행하면 됨. ( ex)out = deeplab.run("blocks.jpg") ) - img = cv2.imread('', cv2.IMREAD_GRAYSCALE), img_color = cv2.imread('', cv2.IMREAD_COLOR) 에도 같은 이미지를 넣어주어 시각적으로 결과를 확인 함. - input image를 학습시켜 블록의 lable을 구분함. OpenCV의 contourArea()로 영역의 크기를 지정해서 선택된 영역에만 boundingRect()를 쳐서 block의 angle을 구함. (이때 angle은 절대값이 아닌 90이하의 값) - 정확한 회전각을 구하기 위해서 OpenCV의 matchTemplate()을 이용('TM_CCOEFF_NORMED' 사용). template 리스트는 mk_ps_tp()에서 생성됨. - lable_to_pose에서 lable 당 가능한 pose 후보군을 설정. boundingRect()를 통해 구한 angle을 90 간격으로 4가지 후보군 설정. - 위에 대한 결과로 얻은 결과로 회전된 절대각을 구하여 pose1(),pose2(),pose3(),pose4(),pose5(),pose6(),pose7(),pose8()에서 잡아야 할 좌표를 계산해줌. pose가 같더라도 block 당 잡아야할 위치가 다르기 때문에 lable에 따라 다르게 계산되도록 함. - pp3의 출력값은 template 매칭된 결과의 대각선 좌표들이며, grippoint의 결과는 잡아야 할 좌표임. <file_sep>/calibration/grippoint.py # -*- coding: utf-8 -*- import cv2 import numpy as np import math import matplotlib.pyplot as plt from PIL import Image, ImageFile, ImageFilter from torchvision import transforms import numpy as np import torch import random import matplotlib.image as mpimg import matplotlib.pyplot as plt import scipy.misc from modeling.deeplab import * ImageFile.LOAD_TRUNCATED_IMAGES = True class FixScaleCrop(object): def __init__(self, crop_size): self.crop_size = crop_size def __call__(self, sample): img = sample w, h = img.size if w > h: oh = self.crop_size ow = int(1.0 * w * oh / h) else: ow = self.crop_size oh = int(1.0 * h * ow / w) img = img.resize((ow, oh), Image.BILINEAR) # center crop w, h = img.size x1 = int(round((w - self.crop_size) / 2.)) y1 = int(round((h - self.crop_size) / 2.)) img = img.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size)) return img class Normalize(object): """Normalize a tensor image with mean and standard deviation. Args: mean (tuple): means for each channel. std (tuple): standard deviations for each channel. """ def __init__(self, mean=(0., 0., 0.), std=(1., 1., 1.)): self.mean = mean self.std = std def __call__(self, sample): img = sample img = np.array(img).astype(np.float32) img /= 255.0 img -= self.mean img /= self.std return img class ToTensor(object): """Convert ndarrays in sample to Tensors.""" def __call__(self, sample): # swap color axis because # numpy image: H x W x C # torch image: C X H X W img = sample img = np.array(img).astype(np.float32).transpose((2, 0, 1)) img = torch.from_numpy(img).float() return img def decode_seg_map_sequence(label_masks, dataset='pascal'): rgb_masks = [] for label_mask in label_masks: rgb_mask = decode_segmap(label_mask, dataset) rgb_masks.append(rgb_mask) rgb_masks = torch.from_numpy(np.array(rgb_masks).transpose([0, 3, 1, 2])) return rgb_masks def decode_segmap(label_mask, dataset, plot=False): """Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. plot (bool, optional): whether to show the resulting color image in a figure. Returns: (np.ndarray, optional): the resulting decoded color image. """ if dataset == 'pascal' or dataset == 'coco': n_classes = 21 label_colours = get_pascal_labels() elif dataset == 'cityscapes': n_classes = 19 label_colours = get_cityscapes_labels() else: raise NotImplementedError r = label_mask.copy() g = label_mask.copy() b = label_mask.copy() for ll in range(0, n_classes): r[label_mask == ll] = label_colours[ll, 0] g[label_mask == ll] = label_colours[ll, 1] b[label_mask == ll] = label_colours[ll, 2] rgb = np.zeros((label_mask.shape[0], label_mask.shape[1], 3)) rgb[:, :, 0] = r / 255.0 rgb[:, :, 1] = g / 255.0 rgb[:, :, 2] = b / 255.0 if plot: plt.imshow(rgb) plt.show() else: return rgb def get_pascal_labels(): """Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) """ return np.asarray([[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]]) class DeeplabModule(): def __init__(self): self.composed_transforms = transforms.Compose([ FixScaleCrop(crop_size=1024), Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ToTensor() ]) self.model = DeepLab(num_classes=8, backbone="resnet", output_stride=16, sync_bn=None, freeze_bn=False) self.display_func = (lambda x:\ decode_seg_map_sequence(torch.max(x, 1)[1].detach().cpu().numpy(),\ dataset="coco")[0]) self.model_init() self.load_checkpoint() def model_init(self): self.model.eval() self.model.cuda() def load_checkpoint(self): checkpoint = torch.load("model_best.pth.tar") self.model.load_state_dict(checkpoint['state_dict']) def run(self, input_img_str): img = Image.open(input_img_str).convert('RGB') img = self.composed_transforms(img).cuda() output = self.model(img.view(1, 3, 1024, 1024)) #result = output result = self.display_func(output) return result def restoreOrigin(sample): x_pad = np.zeros((3, 1024, 259)) # # of classes = 8, original size = (1542, 1024) img = sample.squeeze().detach().cpu().numpy() rest_img = np.concatenate((x_pad, img, x_pad), axis=2) #* 255 # denormalize print(rest_img.dtype) rest_img = np.transpose((rest_img * 255).astype(np.uint8), (1, 2, 0)) print(rest_img.dtype, rest_img.shape) # k = scipy.misc.imresize(rest_img, (680, 1024), interp='bilinear') k = np.array(Image.fromarray(rest_img).resize((1024, 680))) # return np.transpose(k, (0, 2, 1)) return k def pose1(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/4 a = r x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle) ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose2(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=3 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = r x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle) ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose3(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1.5 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = ((r/2)**2+r**2)**0.5 x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) print angle, pa ag = math.radians(-angle)+pa print math.radians(-angle), ag ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose4(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1.5 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = ((r/2)**2+r**2)**0.5 x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle)-pa ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose5(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1.5 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = ((r/2)**2+r**2)**0.5 x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle)+pa ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose6(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr = 1 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/2 a = r*((2)**0.5)/2 x =cx-(r) y =cy+(r/2) pa=math.atan(1) standardpoint=(x,y) ag = math.radians(-angle)+pa ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose7(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1.5 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = ((r/2)**2+r**2)**0.5 x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle)-pa ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point def pose8(img_color, contours, cx,cy,angle) : #block4_2 for cnt in contours: area = cv2.contourArea(cnt) if((area >2000)&(area<100400)) : pr=1.5 x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 255), 1) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_color, [box], 0, (255, 255, 255), 1) cx= int(cx) cy =int(cy) center = (cx,cy) d = ((area*pr)**0.5) r= d/3 a = ((r/2)**2+r**2)**0.5 x =cx-(r) y =cy+(r/2) pa=math.atan(1./2.) standardpoint=(x,y) ag = math.radians(-angle)+pa ##여기에 angle 값 넣으면됨 ######## rx =cx+a*math.cos(ag) ry =cy+a*math.sin(ag) rx =int(rx) ry =int(ry) rot_point = [rx,ry] return center,rot_point lable_to_color = {0:[128, 0, 0], 1:[0, 128, 0], 2:[128, 128, 0], 3:[0, 0, 128], 4:[128, 0, 128], 5:[0, 128, 128], 6:[128, 128, 128] } def coco_thresholding(img, lbl): color = lable_to_color[lbl] mask = np.all(img == color, axis=-1).astype(np.uint8)*255 return mask def find_center(contours): center = [] ag = [] area = [] for cnt in contours: area = cv2.contourArea(cnt) print(area) if((area >2000)&(area<15000)) : x, y, w, h = cv2.boundingRect(cnt) #cv2.rectangle(img_color, (x, y), (x + w, y + h), (0, 255, 0), 1) cx = (x*2+w)/2 cy = (y*2+h)/2 cx= int(cx) cy =int(cy) ct = (area,(cx,cy)) center.append(ct) # area.append(aread) rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) #cv2.drawContours(img_color, [box], 0, (0, 0, 255), 1) a = box[3][0] - box[0][0] b = box[3][1] - box[0][1] #print(box) z = float(b) / float(a) angle = math.atan(z) s = np.rad2deg(angle) if (s<0) : s *=-1 d = round(s,1) ag.append(d) return center,ag def mk_ps_tp(angle, lable) : # blocks_pose_lists = [None]*7 # for i in range(7): # for st in blocks_angles : lable_to_pose = {0: [1, 6], 1: [6], 2: [6], 3: [2, 3, 4], 4: [6], 5: [2, 5, 8], 6: [2, 7]} poses = lable_to_pose[lable] template_lists = [] for p in poses: templates = [] for i in range (0,4) : d = angle+i*90 d = str(d) templates.append("resize/pose{}/pose{}_{}.jpg".format(p, p, d)) template_lists.append(templates) return template_lists def find_grip_points(img_fname): deeplab = DeeplabModule() out = deeplab.run(img_fname) # plt.imshow(np.transpose(out, (1,2,0))) img_mask = restoreOrigin(out) plt.imshow(img_mask) plt.show() num = (7,) print(num + img_mask.shape) # mask = np.all(res == (128, 128, 128), axis=-1).astype(np.uint8)*255 blocks_mask = np.zeros(shape=((7,) + img_mask.shape[:-1]), dtype=np.uint8) blocks_contours = [None]*7 blocks_hierarchies = [None]*7 for i in range(7): blocks_mask[i, :] = mask = coco_thresholding(img_mask, i) _, contours, hierarchy = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) blocks_contours[i] = contours blocks_hierarchies[i] = hierarchy blocks_cts = [None]*7 blocks_angles = [None]*7 img_centerp = img_mask.copy() centers = [] for i in range(7): ct, angle = find_center(blocks_contours[i]) print ct, angle blocks_cts[i] = ct blocks_angles[i] = angle # print(ct) # print(angle) cv2.circle(img_centerp, ct[0][1], 0, (255, 255, 255), 5) centers.append(ct[0][1]) blocks_template_lists = [None]*7 for i in range(7): blocks_template_lists[i] = mk_ps_tp(blocks_angles[i][0], i) print(blocks_template_lists) # methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'] # methods = ['cv2.TM_SQDIFF', 'cv2.TM_CCORR_NORMED'] methods = ['cv2.TM_CCOEFF_NORMED'] for meth in methods: method = eval(meth) blocks_result = [None]*7 blocks_pose = [None]*7 blocks_p1 = [None]*7 img_boxed = img_centerp.copy() for i in range(7) : template_lists = blocks_template_lists[i] template_lists = sum(template_lists, []) max_f = 0 max_index = 0 for j, temp in enumerate(template_lists): temp_img = cv2.imread(temp, cv2.IMREAD_GRAYSCALE) #TODO: 템플릿 크기조절 필요 temp_img = np.array(Image.fromarray(temp_img).resize((175,175))) w,h = temp_img.shape[::-1] print(i, j, w, h) # method = eval('cv2.TM_CCOEFF') res = cv2.matchTemplate(blocks_mask[i], temp_img, method) min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(res) #print(np.min(res), np.max(res)) # print(max_val, np.max(res)) blocks_result[i] = s = max_val if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc if max_f < s: max_f = s max_index = j bottom_right = (top_left[0]+h, top_left[1]+w) blocks_p1[i] = (top_left, bottom_right) blocks_pose[i] = temp # print(i, max_index) cv2.rectangle(img_boxed, blocks_p1[i][0], blocks_p1[i][1], lable_to_color[i], 5) print(blocks_pose[i]) temp_img = cv2.imread(blocks_pose[i], cv2.IMREAD_GRAYSCALE) temp_img = np.array(Image.fromarray(temp_img).resize((175,175))) print(blocks_p1) print(blocks_p1) layer = np.ones_like(img_boxed)*128 img_overlayed = img_boxed.copy() pl =np.zeros(7) b= np.zeros(7) for i in range(7) : # template_lists = blocks_template_lists[i] # max_index = blocks_pose[i] # template_lists = sum(template_lists, []) temp = blocks_pose[i] a = list(blocks_pose[i]) p=a[17:18] pl[i]=int(p[0]) agstr = a[19:-4] l = len(agstr) c=0 if l == 5: b[i] = int(agstr[0])*100+int(agstr[1])*10+int(agstr[2])+int(agstr[4])*0.1 c+=1 elif l == 4 : b[i] = int(agstr[0])*10+int(agstr[1])*1+int(agstr[3])*0.1 c+=1 elif i == 3 : b[i] = int(agstr[0]) + int(agstr[2]) * 0.1 else : b[i] = int(agstr[0])*1 + int(agstr[2])*0.1 c+=1 temp_img = cv2.imread(temp, cv2.IMREAD_GRAYSCALE) temp_img = np.array(Image.fromarray(temp_img).resize((175, 175))) # print(temp_img.shape) layer[blocks_p1[i][0][1]:blocks_p1[i][1][1], blocks_p1[i][0][0]:blocks_p1[i][1][0], :] = np.tile(np.expand_dims(temp_img, axis=2), [1,1,3]) img_overlayed = cv2.addWeighted(img_overlayed, 0.5, layer, 0.5, 0) grip = [] i=0 while i <7: img = cv2.imread(blocks_pose[i], cv2.IMREAD_GRAYSCALE) img_color = cv2.imread(blocks_pose[i], cv2.IMREAD_COLOR) ret, origin = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) _, contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cx = (blocks_p1[i][0][0]+blocks_p1[i][1][0])/2 cy = (blocks_p1[i][0][1]+blocks_p1[i][1][1])/2 if pl[i] == 1: center,rot_point= pose1(img_color, contours, cx,cy,b[i]) print(b[i]) i+=1 elif pl[i] == 2: center,rot_point= pose2(img_color, contours, cx,cy,b[i]) i+=1 elif pl[i] == 3: center,rot_point= pose3(img_color, contours, cx,cy,b[i]-180) i+=1 elif pl[i] == 4: center,rot_point= pose4(img_color, contours, cx,cy,b[i]) i+=1 elif pl[i] == 5: center,rot_point= pose5(img_color, contours, cx,cy,b[i]) i+=1 elif pl[i] == 6: if i == 2: center,rot_point= pose6(img_color, contours, cx,cy,b[i] - 180) elif i == 4: center,rot_point= pose6(img_color, contours, cx,cy,b[i] - 90) else: center, rot_point = pose6(img_color, contours, cx, cy, b[i]) i+=1 elif pl[i] == 7: center,rot_point= pose7(img_color, contours, cx,cy,b[i] - 180) i+=1 else: center,rot_point= pose8(img_color, contours, cx,cy,b[i]) i+=1 rot_point_tuple = (rot_point[0], rot_point[1]) cv2.circle(img_overlayed, rot_point_tuple, 1,(0,125, 255), 3) grip.append(rot_point) print(grip) plt.figure(figsize=(15,12)) plt.imshow(img_overlayed) plt.show() return grip <file_sep>/deeplab/pytorch-deeplab-xception/utils/summaries.py import os import torch from torchvision.utils import make_grid from tensorboardX import SummaryWriter from dataloaders.utils import decode_seg_map_sequence import numpy as np #import time class TensorboardSummary(object): def __init__(self, directory): self.directory = directory def create_summary(self): writer = SummaryWriter(log_dir=os.path.join(self.directory)) return writer def visualize_image(self, writer, dataset, image, target, output, global_step): grid_image = make_grid(image[:3].clone().cpu().data, 3, normalize=True) writer.add_image('Image', grid_image, global_step) ''' grid_image = make_grid(decode_seg_map_sequence(torch.max(output[:3], 1)[1].detach().cpu().numpy(), dataset=dataset), 3, normalize=False, range=(0, 255)) ''' # TODO tmp = decode_seg_map_sequence(torch.max(output[:3], 1)[1].detach().cpu().numpy(), dataset=dataset).double() img = torch.tensor(image[:3].clone().cpu()).double() #grid_image = make_grid(tmp + img, 3, normalize=False, range=(0, 255)) grid_image = make_grid(tmp * 10+ img, 3, normalize=True) # 'normalize' is the problem result = grid_image writer.add_image('Predicted label', grid_image, global_step) grid_image = make_grid(decode_seg_map_sequence(torch.squeeze(target[:3], 1).detach().cpu().numpy(), dataset=dataset), 3, normalize=False, range=(0, 255)) writer.add_image('Groundtruth label', grid_image, global_step) return result <file_sep>/deeplab/dataset/merge_ann_val.py import json file_list = [ "ann_val/out_block1.json", "ann_val/out_block2.json", "ann_val/out_block3.json", "ann_val/out_block4.json", "ann_val/out_block5.json", "ann_val/out_block6.json", "ann_val/out_block7.json", "ann_val/out_scatter_block1.json", "ann_val/out_scatter_block2.json", "ann_val/out_scatter_block3.json", "ann_val/out_scatter_block4.json", "ann_val/out_scatter_block5.json", "ann_val/out_scatter_block6.json", "ann_val/out_scatter_block7.json", "ann_val/out_cube.json"] data = [] id_offset = 20000 for file_name in file_list: with open(file_name, "r") as f: loaded_data = json.load(f) for ann in loaded_data: ann["id"] += id_offset data.extend(loaded_data) id_offset += len(loaded_data) print(id_offset) with open("ann_val/out_merged.json", "w") as f: json.dump(data, f)<file_sep>/annotation/cocohandai550/edit_ref_point.py import argparse import os import pygame import json import time from pycocotools.coco import COCO colors = [ pygame.Color("red"), pygame.Color("blue"), pygame.Color("brown"), pygame.Color("green"), pygame.Color("purple"), pygame.Color("orange"), pygame.Color("yellow"), ] cat_map = { "red": 1, "blue": 2, "brown": 3, "green": 4, "purple": 5, "orange": 6, "yellow": 7 } ''' "annotations": [ { "id": 1, "category_id": 1, "iscrowd": 0, "ref_point": [50, 50], "image_id": 1, } ] ''' def get_sorted_img_id_list(annFile): with open(annFile, "r") as f: raw = json.load(f) return [(x["file_name"], x["id"]) for x in sorted(raw["images"], key=lambda x: x["id"])] def print_info(): print( ''' ======================================== [A]: new category annotation (exit/save current annotation) [R]: redo current image [N]: next image (exit/save current annotation) [Q]: quit unexpectedly (not recommended) ======================================== ''') def edit_ref_point(): prs = argparse.ArgumentParser() prs.add_argument("-d", "--dataset_path", type=str, choices=['train', 'val']) prs.add_argument("-a", "--annotation", type=str, choices=['annotations_train.json', 'annotations_val.json'], default='annotations_train.json') prs.add_argument("-o", "--output_path", type=str, choices=['ann_train', 'ann_val'], default='ref_point_train') prs.add_argument("-n", "--output_name", type=str, default='ref_point.json') prs.add_argument("-s", "--start_index", type=int, default=0) prs.add_argument("-e", "--end_index", type=int, default=500) prs.add_argument("-c", "--single_category", type=int, default=-1) args = prs.parse_args() assert ((args.dataset_path in args.annotation) and (args.dataset_path in args.output_path)) os.makedirs(args.output_path, exist_ok=True) coco=COCO(args.annotation) dataset_path = args.dataset_path img_id_list = get_sorted_img_id_list(args.annotation)[args.start_index:args.end_index] n = len(img_id_list) i = 0 assert n > 0 pygame.init() pic = pygame.image.load(os.path.join(dataset_path, img_id_list[0][0])) pygame.display.set_mode(pic.get_size()) screen = pygame.display.get_surface() done = False ann_id = 1 cat_id = None annotations = [] while i < n and not done: file_name = img_id_list[i][0] file_id = img_id_list[i][1] file_full_name = os.path.join(dataset_path,file_name) pic = pygame.image.load(file_full_name) screen.blit(pic, (0, 0)) pygame.display.flip() img_done = False while not(img_done): #print("1") time.sleep(0.1) if args.single_category > 0: cat_id = args.single_category else: cat_id = input("Catergory (1~7/color)? ") if cat_id in '1234567': cat_id = int(cat_id) elif cat_id in cat_map.keys(): cat_id = cat_map[cat_id] elif cat_id == 'n': img_done = True i += 1 continue else: continue ann_done = False ann = { "id": ann_id, "category_id": cat_id, "iscrowd": 0, "ref_point": [], "image_id": file_id } while not(ann_done): #print("2") key_down = False print_info() while not(key_down): #print("3") time.sleep(0.01) for event in pygame.event.get(): if event.type == pygame.QUIT: key_down = True key = "q" elif event.type == pygame.KEYDOWN: #print(event) if event.key == pygame.K_a: key = "a" key_down = True elif event.key == pygame.K_r: key = "r" key_down = True elif event.key == pygame.K_n: key = "n" key_down = True elif event.key == pygame.K_q: key = "q" key_down = True elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() #pos = [float(pos[0]), float(pos[1])] pygame.draw.circle(screen, colors[cat_id-1], pos, 5, 2) pygame.display.flip() ann["ref_point"] = pos if key in 'anr': ann_done = True if key == 'n': img_done = True i += 1 if key == 'r': while len(annotations) > 0 and annotations[-1]['image_id'] == file_id: annotations = annotations[:-1] img_done = True if key == 'q': done = img_done = ann_done = True if ann_done and key != 'r': annotations.append(ann) ann_id += 1 print(json.dumps(annotations)) with open(os.path.join(args.output_path, args.output_name), 'w') as f: json.dump(annotations, f) if __name__ == '__main__': edit_ref_point() <file_sep>/jfiddle.lua #!/usr/local/bin/luajit -i if IS_FIDDLE then return end local ok = pcall(dofile, '../include.lua') if not ok then pcall(dofile, 'include.lua') end -- Important libraries in the global space mp = require'msgpack.MessagePack' si = require'simple_ipc' local libs = { 'ffi', -- 'torch', 'util', 'vector', 'Body', } -- Load the libraries for _,lib in ipairs(libs) do local ok, lib_tbl = pcall(require, lib) if ok then _G[lib] = lib_tbl else print("Failed to load", lib) print(lib_tbl) end end -- FSM communicationg fsm_chs = {} for sm, en in pairs(Config.fsm.enabled) do local fsm_name = sm..'FSM' local ch = en and si.new_publisher(fsm_name.."!") or si.new_dummy() _G[sm:lower()..'_ch'] = ch fsm_chs[fsm_name] = ch end -- Shared memory local listing = unix.readdir(HOME..'/Memory') local shm_vars = {} for _,mem in ipairs(listing) do local found, found_end = mem:find'cm' if found then local name = mem:sub(1,found_end) table.insert(shm_vars,name) require(name) end end -- Local RPC for testing rpc_ch = si.new_requester'rpc' dcm_ch = si.new_publisher'dcm!' state_ch = si.new_publisher'state!' --print(util.color('FSM Channel', 'yellow'), table.concat(fsm_chs, ' ')) --print(util.color('SHM access', 'blue'), table.concat(shm_vars, ' ')) local function gen_screen(name, script, ...) local args = {...} return table.concat({ 'screen', '-S', name..table.concat(args), '-L', '-dm', 'luajit', script },' ') end function pkill(name, idx) if tostring(idx) then local ret = io.popen("pkill -f "..name) else local ret = io.popen("pkill -f "..name..' '..tostring(idx)) end end -- Start script local runnable = {} for _,fname in ipairs(unix.readdir(HOME..'/Run')) do local found, found_end = fname:find'_wizard' if found then local name = fname:sub(1,found-1) runnable[name] = 'wizard' end end for _,fname in ipairs(unix.readdir(ROBOT_HOME)) do local found, found_end = fname:find'run_' local foundlua, foundlua_end = fname:find'.lua' if found and foundlua then local name = fname:sub(found_end+1, foundlua-1) runnable[name] = 'robot' end end function pstart(scriptname, idx) local kind = runnable[scriptname] if not kind then return false end local script = kind=='wizard' and scriptname..'_wizard.lua' or 'run_'..scriptname..'.lua' if tostring(idx) then script = script..' '..tostring(idx) end pkill(script) unix.chdir(kind=='wizard' and HOME..'/Run' or ROBOT_HOME) local screen = gen_screen(scriptname, script, idx) print('screen', screen) local status = os.execute(screen) unix.usleep(1e6/4) local ret = io.popen("pgrep -fla "..script) for pid in ret:lines() do if pid:find('luajit') then return true end end end IS_FIDDLE = true if arg and arg[-1]=='-i' and jit then if arg[1] then -- Test file first dofile(arg[1]) end -- hardcoded script @befreor local block_xpos = wcm.get_cubes_xpos() local block_ypos = wcm.get_cubes_ypos() -- BLOCK ID (SIM) to BLOCK ID (REAL) -- for accessing 'final_block_rel_loc' -- e.g. to access BLOCK ID '3' (SIM) -- final_block_rel_loc[block_id_map[3]] local block_id_map = {1, 5, 7, 4, 2, 3, 6} -- [TODO] INITIAL 'X' LOCATION local x_hold_offset = 0.04 local refine_cubes_xpos = {} for i=1,7 do table.insert(refine_cubes_xpos, block_xpos[i] - x_hold_offset) end print("refine_cubes_xpos") for i=1,7 do print(refine_cubes_xpos[i]) end -- [TODO] RELATIVE/FINAL LOCATION -- relative loc based on BLOCK ID (REAL) '0' local final_block_rel_loc = { {0,0,0}, {-3 * 0.025, 1 * 0.025, 0}, {-3 * 0.025, -3 * 0.025, 0}, {-1 * 0.025, -2 * 0.025, 0}, {-2 * 0.025, 0, 0}, {0, -3 * 0.025, 0}, {-4 * 0.025, -1 * 0.025, 0} } local final_offset = {0.3, -0.3, 0.0125} -- final block location local final_block_loc = {} for i=1,7 do local tmp = {final_block_rel_loc[block_id_map[i]][1] + final_offset[1], final_block_rel_loc[block_id_map[i]][2] + final_offset[2], final_block_rel_loc[block_id_map[i]][3] + final_offset[3]} table.insert(final_block_loc, tmp) end -- block catch order in BLOCK ID (SIM) local order = {7, 4, 6, 1, 3, 5, 2} -- heuristic values --local xoffset = 0.05 -- for set gripper appropriately --local block_xoffset = {-0.065, -0.017, -0.02, -0.03, -0.075, -0.075, -0.05} local z_max_offset = 0.3 local z_1_offset = 0.25 local z_2_offset = 0.2 local z_3_offset = 0.1 local z_min_offset = 0.05 local z_put_offset = 0.3--0.05 local gripInit = {0.06, 0.06} local gripHold = {0.02, 0.02} local gripRelease = gripInit -- assemble loc info --local loc_offset = {0.4, -0.4, 0.0125} --local block_loc = {{-0.025, 0.075, 0.0}, -- {-0.025, 0.1, 0.1}, -- {-0.075, 0.05, 0.0}, -- {-0.025, 0.0375, 0.0}, -- {-0.1, 0.1, -0.006}, -- {-0.1, 0.0, 0.0}, -- {-0.025, 0.0, 0.0}} --local block_hold_pos_offset = {{}} function wait() os.execute("sleep 4") end --function loc_cal(idx, x) -- x: 0=x, 1=y -- return loc_offset[x] + block_loc[idx][x] --end print("block xpos", block_xpos) print("block ypos", block_ypos) function pickBlock(idx) hcm.set_arm_grabxyz({refine_cubes_xpos[idx], block_ypos[idx], z_max_offset}) arm_ch:send'moveto' wait() hcm.set_arm_grabxyz({refine_cubes_xpos[idx], block_ypos[idx], z_min_offset}) arm_ch:send'moveto' wait() hcm.set_arm_gripperTarget(gripHold) wait() hcm.set_arm_grabxyz({refine_cubes_xpos[idx], block_ypos[idx], z_max_offset}) arm_ch:send'moveto' wait() hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_max_offset}) arm_ch:send'moveto' wait() --hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_1_offset + 0.01}) --arm_ch:send'moveto' --wait() --hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_2_offset + 0.01}) --arm_ch:send'moveto' --wait() --hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_3_offset + 0.01}) --arm_ch:send'moveto' --wait() hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_put_offset + 0.01}) arm_ch:send'moveto' wait() gt = hcm.get_arm_gripperTarget() print(gt[1]) gt[1] = gt[1] + 0.06 gt[2] = gt[2] + 0.006 print(gt[2]) hcm.set_arm_gripperTarget(gt) wait() hcm.set_arm_grabxyz({final_block_loc[idx][1], final_block_loc[idx][2], z_max_offset}) arm_ch:send'moveto' wait() hcm.set_arm_gripperTarget(gripInit) wait() end hcm.set_arm_gripperTarget(gripInit) wait() --for i=1,7 do -- pickBlock(order[i]) --end --pickBlock(3) -- Interactive LuaJIT package.path = package.path..';'..HOME..'/Tools/iluajit/?.lua' dofile(HOME..'/Tools/iluajit/iluajit.lua') end <file_sep>/mask_rcnn/datasets/handai/merge_ann.py import json file_list = [ "handai_dataset_ann/out_block1.json", "handai_dataset_ann/out_block2.json", "handai_dataset_ann/out_block3.json", "handai_dataset_ann/out_block4.json", "handai_dataset_ann/out_block5.json", "handai_dataset_ann/out_block6.json", "handai_dataset_ann/out_block7.json", "handai_dataset_ann/out_scatter_block1.json", "handai_dataset_ann/out_scatter_block2.json", "handai_dataset_ann/out_scatter_block3.json", "handai_dataset_ann/out_scatter_block4.json", "handai_dataset_ann/out_scatter_block5.json", "handai_dataset_ann/out_scatter_block6.json", "handai_dataset_ann/out_scatter_block7.json", "handai_dataset_ann/out_cube.json"] data = [] id_offset = 0 for file_name in file_list: with open(file_name, "r") as f: loaded_data = json.load(f) for ann in loaded_data: ann["id"] += id_offset data.extend(loaded_data) id_offset += len(loaded_data) print(id_offset) with open("handai_dataset_ann/out_merged.json", "w") as f: json.dump(data, f)<file_sep>/calibration/cam_tool.py import piggyphoto import pyrealsense2 as rs import os import cv2 import pygame import numpy as np class cam_tool: def __init__(self, cam_type): self.cam_type = cam_type print 'Initializing %s...'%cam_type if cam_type == 'sony': self.C = piggyphoto.camera() self.C.leave_locked() self.capture('temp.jpg') elif cam_type == 'rs': self.pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) # Start streaming self.pipeline.start(config) self.capture('temp.jpg') picture = pygame.image.load('temp.jpg') pygame.display.set_mode(picture.get_size()) self.main_surface = pygame.display.get_surface() os.remove('temp.jpg') def capture(self, path=None, depth=False): tempname = 'temp.jpg' if path == tempname: tempname = 'temp2.jpg' if self.cam_type == 'sony': if path == None: return self.C.capture_preview() else: self.C.capture_preview(tempname) elif self.cam_type == 'rs': frames = self.pipeline.wait_for_frames() color_frame = frames.get_color_frame() if not color_frame: return if depth: depth_frame = frames.get_depth_frame() if not depth_frame: return color_image = np.asanyarray(color_frame.get_data()) if depth: depth_image = np.asanyarray(depth_frame.get_data()) #depth_image = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET) depth_image = np.tile(np.expand_dims(cv2.convertScaleAbs(depth_image, alpha=0.03), 2), [1, 1, 3]) image = np.hstack((color_image, depth_image)) else: image = color_image if path == None: return image cv2.imwrite(tempname, image) os.rename(tempname, path) def show_image(self, picture): self.main_surface.blit(picture, (0, 0)) pygame.display.flip() def show(self, file): picture = pygame.image.load(file) self.show_image(picture) def exit(self): if self.cam_type == 'rs': self.pipeline.stop()
37af8ce45f85c7b213d9221e7bc82d45c1f37e1e
[ "Markdown", "Python", "Text", "Lua" ]
33
Python
RyusizzSNU/SomaCube
d6e0cffc4951daf8b010f330d6bfa1d3358f4303
e3cd47a283e091db95d52793b852d7705efd5af3
refs/heads/master
<repo_name>aleksandaratanasov/AngularJsMinimalistic<file_sep>/nbproject/project.properties auxiliary.org-netbeans-modules-web-clientproject-api.js_2e_libs_2e_folder=js/libs file.reference.AngularJsMinimalistic-public_html=public_html file.reference.AngularJsMinimalistic-test=test files.encoding=UTF-8 project.license=gpl20 site.root.folder=${file.reference.AngularJsMinimalistic-public_html} test.folder=${file.reference.AngularJsMinimalistic-test} <file_sep>/public_html/js/app.js /* * Copyright (C) 2015 redbaron * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ 'use strict'; var helloWorldApp = angular.module('helloWorldApp', [ 'ngRoute', 'helloWorldControllers' ]); helloWorldApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider.when('/', { templateUrl: 'partials/main.html', controller: 'MainCtrl' }).when('/show', { templateUrl: 'partials/show.html', controller: 'ShowCtrl'}); $locationProvider.html5Mode(false).hashPrefix('!'); }]);<file_sep>/public_html/js/controller.js /* * Copyright (C) 2015 redbaron * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ 'use strict'; var helloWorldControllers = angular.module('helloWorldControllers', []); helloWorldControllers.controller('MainCtrl', ['$scope', '$location', '$http', function MainCtrl($scope, $location, $http) { $scope.message = "Hello World!"; } ]); helloWorldControllers.controller('ShowCtrl', ['$scope', '$location', '$http', function ShowCtrl($scope, $location, $http) { $scope.message = "Showing some important stuff...or not."; } ]);
e8d6efc2d0d3c0a0988e59ac3a104834971ea90f
[ "JavaScript", "INI" ]
3
INI
aleksandaratanasov/AngularJsMinimalistic
072a384cace5fde8db3d10faf497df23f8d68d4a
2dca12d9eaf84d0c5b6286f972459dd41abc9601
refs/heads/master
<repo_name>softtrymee/Object-Draw<file_sep>/DrawArc.java import objectdraw.*; import java.awt.Color; /** * DrawArc draws a circle at a given location. * upon started on as a thread, e.g. * Thread arc = new DrawArc(<params>); * arc.start(); * the circle moves diagonally down and back up the screen. */ public class DrawArc extends Thread { private double x; private double y; private DrawingCanvas canvas; public FilledArc fa1; public FilledArc face; private final double ARC1_SIZE = 400; private final double ARC2_SIZE = 300; private final double START_ANGLE = 0; private final double ARC_ANGLE = 360; /** * @param x - x starting location for the arc * @param y - y starting location for the arc * @param canvas - the canvas to draw the arc in. Should be * provided by objectdraw */ public DrawArc(double x, double y, DrawingCanvas canvas) { this.x = x; this.y = y; this.canvas = canvas; int color1 = 37; int color2 = 168; int color3 = 220; Color bigColor = new Color(color1, color2, color3); //draw the background fa1 = new FilledArc(x, y, ARC1_SIZE, ARC1_SIZE, START_ANGLE, ARC_ANGLE, canvas); //set background color fa1.setColor(bigColor); //draw the face face = new FilledArc(x, y, ARC2_SIZE, ARC2_SIZE, START_ANGLE, ARC_ANGLE, canvas); //set face color face.setColor(Color.BLACK); } /** * Executed when the thread starts and runs indefinitly, moving the arc * across the screen. */ public void run() { int edge = 400; double downY=2; double downX=1; int moving = 53; for(int i = 0; i < moving; i++ ) { face.move(downX, downY); Animate.catchSleep(1); } } } <file_sep>/DrawArc1.java import objectdraw.*; import java.awt.Color; /** * DrawArc1 draws a circle at a given location. * upon started on as a thread, e.g. * Thread arc = new DrawArc(<params>); * arc.start(); * the circle moves diagonally down and back up the screen. */ public class DrawArc1 extends Thread { private double x; private double y; private DrawingCanvas canvas; private FilledArc cheekLeft; private FilledArc cheekRight; private final double ARC_CHEEK = 80; private final double START_ANGLE = 0; private final double ARC_ANGLE = 360; /** * @param x - x starting location for the arc * @param y - y starting location for the arc * @param canvas - the canvas to draw the arc in. Should be * provided by objectdraw */ public DrawArc1(double x, double y, DrawingCanvas canvas) { this.x = x; this.y = y; this.canvas = canvas; int color1 = 220; int color2 = 0; int color3 = 26; Color bigColor = new Color(color1, color2, color3); //drwa his cheeks and set them red. cheekLeft = new FilledArc(x, y, ARC_CHEEK, ARC_CHEEK, START_ANGLE, ARC_ANGLE, canvas); cheekLeft.setColor(bigColor); cheekRight = new FilledArc(x, y, ARC_CHEEK, ARC_CHEEK, START_ANGLE, ARC_ANGLE, canvas); cheekRight.setColor(bigColor); } /** * Executed when the thread starts and runs indefinitly, moving the arc * across the screen. */ public void run() { int edge = 400; double downY1=3.7; double downX1=-0.7; double downY2= downY1; double downX2=4; cheekLeft.show(); cheekRight.show(); int moving = 53; int time = 10; //bring cheeks to their positions for(int i = 0; i < moving; i++ ) { cheekLeft.move(downX1, downY1); cheekLeft.show(); cheekRight.move(downX2, downY2); cheekLeft.show(); Animate.catchSleep(time); } } } <file_sep>/DrawArc2.java import objectdraw.*; import java.awt.Color; /** * DrawArc2 draws a circle at a given location. * upon started on as a thread, e.g. * Thread arc = new DrawArc(<params>); * arc.start(); * the circle moves diagonally down and back up the screen. */ public class DrawArc2 extends Thread { private double x; private double y; private DrawingCanvas canvas; private static FilledArc leftBigEar; private static FilledArc leftSmallEar; private static FilledArc rightBigEar; private static FilledArc rightSmallEar; private static FilledArc leftBigEye; public static FilledArc leftSmallEye; private static FilledArc rightBigEye; public static FilledArc rightSmallEye; private final double bigEarSize = 70; private final double smallEarSize = 30; private final double bigEyeSize = 65; private final double smallEyeSize = 24; private final double START_ANGLE = 0; private final double ARC_ANGLE = 360; /** * @param x - x starting location for the arc * @param y - y starting location for the arc * @param canvas - the canvas to draw the arc in. Should be * provided by objectdraw */ public DrawArc2(double x, double y, DrawingCanvas canvas) { this.x = x; this.y = y; this.canvas = canvas; int color1 = 220; int color2 = 0; int color3 = 26; Color bigColor = new Color(color1, color2, color3); //drwa his ears and eyes leftBigEar = new FilledArc(x, y, bigEarSize, bigEarSize, START_ANGLE, ARC_ANGLE, canvas); leftBigEar.setColor(Color.BLACK); leftSmallEar = new FilledArc(x, y, smallEarSize, smallEarSize, START_ANGLE, ARC_ANGLE, canvas); leftSmallEar.setColor(Color.WHITE); rightBigEar = new FilledArc(x, y, bigEarSize, bigEarSize, START_ANGLE, ARC_ANGLE, canvas); rightBigEar.setColor(Color.BLACK); rightSmallEar = new FilledArc(x, y, smallEarSize, smallEarSize, START_ANGLE, ARC_ANGLE, canvas); rightSmallEar.setColor(Color.WHITE); leftBigEye = new FilledArc(x, y, bigEyeSize, bigEyeSize, START_ANGLE, ARC_ANGLE, canvas); leftBigEye.setColor(Color.WHITE); leftSmallEye = new FilledArc(x, y, smallEyeSize, smallEyeSize, START_ANGLE, ARC_ANGLE, canvas); leftSmallEye.setColor(Color.BLACK); rightBigEye = new FilledArc(x, y, bigEyeSize, bigEyeSize, START_ANGLE, ARC_ANGLE, canvas); rightBigEye.setColor(Color.WHITE); rightSmallEye = new FilledArc(x, y, smallEyeSize, smallEyeSize, START_ANGLE, ARC_ANGLE, canvas); rightSmallEye.setColor(Color.BLACK); } /** * Executed when the thread starts and runs indefinitly, moving the arc * across the screen. */ public void run() { double downY1=3; double downX1=2; double downY2=3.2; double downX2=2.2; double downY3=3; double downX3=6.7; double downY4=3.2; double downX4=7.25; double downY5=4.5; double downX5=3; double downY6=4.5; double downX6=3.2; double downY7=4.5; double downX7=5.8; double downY8=5.2; double downX8=6.5; int moving = 50; int time = 10; int eyeballmoving = 41; for(int i = 0; i < moving; i++ ) { leftBigEar.move(downX1, downY1); leftBigEar.show(); leftSmallEar.move(downX2, downY2); leftSmallEar.show(); rightBigEar.move(downX3, downY3); rightBigEar.show(); rightSmallEar.move(downX4, downY4); rightSmallEar.show(); leftBigEye.move(downX5, downY5); leftBigEye.show(); leftSmallEye.move(downX6, downY6); leftSmallEye.show(); rightBigEye.move(downX7, downY7); rightBigEye.show(); rightSmallEye.move(downX8, downY8); rightSmallEye.show(); Animate.catchSleep(time); } //move eyeballs while (true) { for (int i = 0; i < eyeballmoving; i++) { leftSmallEye.move(1,1); rightSmallEye.move(-1, -1); Animate.catchSleep(time); } for (int i = 0; i < eyeballmoving; i++) { leftSmallEye.move(-1,-1); rightSmallEye.move(1, 1); Animate.catchSleep(time); } } } } <file_sep>/DrawOval1.java import objectdraw.*; import java.awt.Color; /** * DrawOval1 draws a circle at a given location. * upon started on as a thread, e.g. * Thread arc = new DrawArc(<params>); * arc.start(); * the circle moves diagonally down and back up the screen. */ public class DrawOval1 extends Thread { private double x; private double y; private DrawingCanvas canvas; private FilledOval bigMouth; public static FilledOval smallmouth; private static FilledOval nose; private final double bigHeight = 130; private final double bigWidth = 150; private final double smallHeight = 45; private final double smallWidth = 30; private final double noseHeight = 40; private final double noseWidth = 45; private static boolean click = false; /** * @param x - x starting location for the arc * @param y - y starting location for the arc * @param canvas - the canvas to draw the arc in. Should be * provided by objectdraw */ public DrawOval1(double x, double y, DrawingCanvas canvas) { this.x = x; this.y = y; this.canvas = canvas; //draw mouth and nose bigMouth = new FilledOval(x, y, bigWidth, bigHeight, canvas); bigMouth.setColor(Color.WHITE); smallmouth = new FilledOval(x, y, smallWidth, smallHeight, canvas); smallmouth.setColor(Color.BLACK); nose = new FilledOval(x, y, noseWidth, noseHeight, canvas); nose.setColor(Color.BLACK); } /** * name: setWhite * method set the small mouth white and invisible, then draw another * moving mouth in another class */ public static void setWhite() { smallmouth.setColor(Color.WHITE); } /** * Executed when the thread starts and runs indefinitly, moving the arc * across the screen. */ public void run() { int edge = 400; double downY1=6.1; double downX1=3.6; double downY2=7.5; double downX2=4.8; double downY3=6.2; double downX3=4.7; //moving mouth and nose to their positions for(int i = 0; i < 50; i++ ) { bigMouth.move(downX1, downY1); bigMouth.show(); smallmouth.move(downX2, downY2); smallmouth.show(); nose.move(downX3, downY3); nose.show(); Animate.catchSleep(10); } } } <file_sep>/MoveMouth.java import objectdraw.*; import java.awt.Color; /** * DrawArc draws a circle at a given location. * upon started on as a thread, e.g. * Thread arc = new DrawArc(<params>); * arc.start(); * the circle moves diagonally down and back up the screen. */ public class MoveMouth extends Thread { private double x; private double y; private DrawingCanvas canvas; public static FilledOval smallmouth; private final double smallHeight = 45; private final double smallWidth = 30; /** * @param x - x starting location for the arc * @param y - y starting location for the arc * @param canvas - the canvas to draw the arc in. Should be * provided by objectdraw */ public MoveMouth(double x, double y, DrawingCanvas canvas) { this.x = x; this.y = y; this.canvas = canvas; int start1 = 238; int start2 = 375; //draw another small mouth smallmouth = new FilledOval(start1, start2, smallWidth, smallHeight, canvas); smallmouth.setColor(Color.BLACK); } /** * Executed when the thread starts and runs indefinitly, moving the arc * across the screen. */ public void run() { DrawOval1.setWhite();//set the previous one invisible //make the new one move int loop = 15; int time = 10; while (true) { for (int i = 0; i < loop; i++) { smallmouth.setSize(smallmouth.getWidth() + 1, smallmouth.getHeight() - 1); Animate.catchSleep(time); } for (int i = 0; i < loop; i++) { smallmouth.setSize(smallmouth.getWidth() - 1, smallmouth.getHeight() + 1); Animate.catchSleep(time); } } } }
302fbebbd6c7c998443bc375bc142c3cbea9ccd8
[ "Java" ]
5
Java
softtrymee/Object-Draw
1675f63d800fdc792f60eefce679d54770418e6d
24b06b1099103949f0994e81b70a50e0c20e98e9
refs/heads/master
<file_sep>import { validate } from "class-validator"; import { IPipeTransform } from "classrouter"; import { IInvalidProperties, ValidationFormException } from "@napp/exception"; export class ValidatePipe implements IPipeTransform { async transform(value: any) { let errors = await validate(value); if (errors.length > 0) { let msg: IInvalidProperties = {}; errors.map((e) => { if (e && e.constraints) { Object.keys(e.constraints).map((k) => { if (Array.isArray(msg[e.property])) { msg[e.property].push(e.constraints[k]); } else { msg[e.property] = [e.constraints[k]]; } }); } }); throw new ValidationFormException("validation error", msg); } else { return value; } } } <file_sep>import { Get, Action, Controller, QueryParam, RequestParam } from "classrouter"; import { CustomerController } from "./customer/controller"; import { LoginController } from "./login"; @Controller({ name: 'main', path: '/console', controllers : [ CustomerController, LoginController ] }) export class MainController { @Get({ path: '/', name: 'home' }) async home() { return { page: 'home', at: new Date().toISOString() } } @Get({ path: '/about', name: 'about' }) async about() { return { page: 'about', at: new Date().toISOString() } } }<file_sep>import { initialize, Model } from 'objection'; import { connection, knex } from './knex'; import { DBSession } from './m.session'; export async function dbInit() { Model.knex(connection); await initialize(connection, [DBSession]); } export { knex, connection }<file_sep>export function bearerParse(tokenkey: string) { if (tokenkey) { let parts = tokenkey.split(' '); if (parts.length === 2) { var bearer = parts[0].toLowerCase(); if (bearer === 'bearer') { return parts[1]; } } } return null; }<file_sep>import { confUserly } from "./config"; import { RestFull } from "./common/restfull"; const jwt = require('jsonwebtoken'); export namespace userly { export interface ILoginResult { userid: string name: string confirmed: boolean roles: string[], usertoken: string; lastlogin_at: Date; tokenexp: number; } function token() { let key = confUserly.USERLY_KEY_PRI; let payload = { a: confUserly.USERLY_KEY_APP } console.log('payload',payload) console.log('payload', key.toString()) return jwt.sign(payload, key.toString(), { jwtid: 'client', expiresIn: '30s', algorithm: 'RS256' }); } export async function loginByTokencode(appusertoken: string) { let headers = { // Authorization: 'Bearer ' + token() }; return await RestFull.post<ILoginResult>(`${confUserly.USERLY_KEY_URL}/v4/auth/appuser`, { appusertoken }, { headers }); } export async function userProfileByAppuserid1(appuserid: string) { let headers = { Authorization: 'Bearer ' + token() } console.log('headers',headers); let resp = await RestFull.get<ILoginResult>(`${confUserly.USERLY_KEY_URL}/v4/app/profile/${appuserid}/info`, { headers }); console.log('respppppp', resp) return resp; } }<file_sep>import { Get, Action, Controller, QueryParam, RequestParam } from "classrouter"; @Controller({ name: 'customer', path: '/customer' }) export class CustomerController { @Get({ path: '/list', name: 'home' }) async list() { return [ {id:1, name: 'time.mn', desc: 'time.mn news portal site'}, {id:2, name: 'news.mn', desc: 'news.mn news portal site'} ] } }<file_sep>import { validateOrReject, ValidationError, ValidatorOptions, validate } from "class-validator"; import { IPipeTransform, Classtype } from "classrouter"; import { IInvalidProperties, ValidationFormException } from "@napp/exception"; import { plainToClass } from "class-transformer"; export class DtoValidatePipe implements IPipeTransform { constructor(public classty: Classtype, public options?: ValidatorOptions) { } async transform(value: any) { let ins = plainToClass(this.classty, value); let errors = await validate(ins); if (errors.length) { let msg: IInvalidProperties = {}; for (let e of errors) { if (e && e.constraints) { Object.keys(e.constraints).map((k) => { if (Array.isArray(msg[e.property])) { msg[e.property].push(e.constraints[k]); } else { msg[e.property] = [e.constraints[k]]; } }); } } throw new ValidationFormException("invalid properties", msg); } return ins; } } <file_sep>// Update with your config settings. const conf = require('./opt/db.conf'); module.exports = { client: conf.DB_CLIENT, connection: { database: conf.DB_DATABASE, user: conf.DB_USERNAME, password: conf.DB_PASSWORD }, migrations: { loadExtensions: ['.js'] } }; <file_sep>import envalid, { makeValidator } from 'envalid'; import path from 'path'; import fs from 'fs'; const fileContent = makeValidator(x => { let p = path.resolve(x); if (fs.existsSync(p)) { let c = fs.readFileSync(p); return c; } else { throw new Error(`file not found. path=${p}`); } }); export const confEnv = envalid.cleanEnv( process.env, { NODE_APP_INSTANCE: envalid.num({ default: 0, }), SERVER_HOST: envalid.host({ default: '0.0.0.0' }), SERVER_PORT: envalid.port({ default: 3000, desc: 'The port to start the server on' }), DB_CLIENT: envalid.str({ default: 'mysql2', choices: ['mysql', 'mysql2', 'pg', 'oracledb', 'mssql'] }), DB_HOST: envalid.host({ default: 'localhost' }), DB_PORT: envalid.port({ default: 3306 }), DB_DATABASE: envalid.str({ docs: 'db database name' }), DB_USERNAME: envalid.str({ docs: 'db username' }), DB_PASSWORD: envalid.str({ docs: 'db userpassword' }), DB_CHARSET: envalid.str({ default: 'utf8', docs: 'db connection charset' }), DB_TIMEZONE: envalid.str({ default: '+08:00', docs: 'db connection timezone', }), DB_POOL_MIN: envalid.num({ default: 1, docs: 'db connection pool min', }), DB_POOL_MAX: envalid.num({ default: 10, docs: 'db connection pool nax', }), LOG_DIR: envalid.str({ default: 'log', desc: 'file log write dir' }), // access log LOG_ACCESS: envalid.bool({ default: true, desc: 'access log write flag' }), LOG_ACCESS_FORMAT: envalid.str({ choices: ['combined', 'common', 'short', 'dev', 'tiny'], default: 'common', devDefault: 'dev', desc: 'access log write format' }), // sql log file LOG_SQL_FILE: envalid.bool({ default: true, desc: 'Sql logg file write flag' }), LOG_SQL_FILE_LEVEL: envalid.str({ choices: ['debug', 'info', 'warn', 'error'], default: 'info', devDefault: 'debug', desc: 'Sql logg file write level(min value)' }), LOG_SQL_FILE_FILESIZE: envalid.num({ default: 10485760, desc: 'log file size. vlues is bytes. default=10mb' }), LOG_SQL_FILE_MAXFILE: envalid.num({ default: 10, desc: 'log file max count. vlues is bytes. default=10' }), // sql log console LOG_SQL_CONSOLE: envalid.bool({ default: true, desc: 'Sql console logg write flag' }), LOG_SQL_CONSOLE_LEVEL: envalid.str({ choices: ['debug', 'info', 'warn', 'error'], default: 'info', devDefault: 'debug', desc: 'Sql logg console write level(min value)' }), // default log file LOG_DEFAULT_FILE: envalid.bool({ default: true, desc: 'default logg file write flag' }), LOG_DEFAULT_FILE_LEVEL: envalid.str({ choices: ['debug', 'info', 'warn', 'error'], default: 'info', devDefault: 'debug', desc: 'default logg file write level(min value)' }), LOG_DEFAULT_FILE_FILESIZE: envalid.num({ default: 10485760, desc: 'log file size. vlues is bytes. default=10mb' }), LOG_DEFAULT_FILE_MAXFILE: envalid.num({ default: 10, desc: 'log file max count. vlues is bytes. default=10' }), // default log console LOG_DEFAULT_CONSOLE: envalid.bool({ default: true, desc: 'default console logg write flag' }), LOG_DEFAULT_CONSOLE_LEVEL: envalid.str({ choices: ['debug', 'info', 'warn', 'error'], default: 'info', devDefault: 'debug', desc: 'default logg console write level(min value)' }), // userly USERLY_KEY_APP : envalid.str({desc : 'userly application id'}), USERLY_KEY_URL : envalid.url({default : 'https://api.userly.mn', desc : 'userly application base url'}), USERLY_KEY_PRI : fileContent({}), USERLY_KEY_PUB : fileContent({}) }, { strict: true } ); export default confEnv; export const confSys = { APP_INSTANCE: confEnv.NODE_APP_INSTANCE } // tslint:disable-next-line: no-namespace export namespace confDatabse { export const DB_CLIENT = confEnv.DB_CLIENT; export const DB_HOST = confEnv.DB_HOST; export const DB_PORT = confEnv.DB_PORT; export const DB_DATABASE = confEnv.DB_DATABASE; export const DB_PASSWORD = confEnv.DB_PASSWORD; export const DB_USERNAME = confEnv.DB_USERNAME; export const DB_CHARSET = confEnv.DB_CHARSET; export const DB_TIMEZONE = confEnv.DB_TIMEZONE; export const DB_POOL_MIN = confEnv.DB_POOL_MIN; export const DB_POOL_MAX = confEnv.DB_POOL_MAX; } export const confUserly = { USERLY_KEY_APP: confEnv.USERLY_KEY_APP, USERLY_KEY_URL: confEnv.USERLY_KEY_URL, USERLY_KEY_PRI: confEnv.USERLY_KEY_PRI, USERLY_KEY_PUB: confEnv.USERLY_KEY_PUB } <file_sep>const path = require('path'); // const HtmlWebpackPlugin = require('html-webpack-plugin'); const nodeExternals = require('webpack-node-externals'); const server = { devtool: 'inline-source-map', // cache: false, entry: { server: 'src/server.ts' }, output: { path: path.resolve('dist'), filename: 'server.js', }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, target: 'node', node: { __filename: false, __dirname: false, }, externals: [nodeExternals()], resolve: { extensions: ['.tsx', '.ts', '.js'], // modules: [ // path.resolve('node_modules'), // path.resolve('.'), // path.resolve('.'), // ], alias: { //common: path.resolve(__dirname, '../common'), 'src': path.resolve('src'), 'console-dto': path.resolve('../console-dto'), } }, plugins: [ ], }; module.exports = server;<file_sep>import knex from 'knex' import { confDatabse } from 'src/config' import { loggerSql } from 'src/logger' export const connection = knex({ client: confDatabse.DB_CLIENT, connection: { database: confDatabse.DB_DATABASE, host: confDatabse.DB_HOST, user: confDatabse.DB_USERNAME, password: <PASSWORD>, charset: confDatabse.DB_CHARSET, port: confDatabse.DB_PORT, timezone: confDatabse.DB_TIMEZONE, }, pool: { min: confDatabse.DB_POOL_MIN, max: confDatabse.DB_POOL_MAX, log: (m, l) => loggerSql.log(l, m) }, log: { warn: (m) => loggerSql.warn(m), error: (m) => loggerSql.error(m), debug: (m) => loggerSql.debug(m), deprecate: (method, alternative) => loggerSql.warn(`deprecate. ${method}; ${alternative}`) }, debug: true, migrations: { tableName: 'knex_migrations' } }); export { knex }<file_sep>import { Model } from 'objection'; export class DBSession extends Model { id!: string; userly!: string; userly_token!: string; created_at!: Date; expired_at!:Date; static get tableName() { return 'sessions'; } }<file_sep>const envalid = require('envalid'); module.exports = envalid.cleanEnv( process.env, { DB_CLIENT: envalid.str({ default: 'mysql2', choices: ['mysql', 'mysql2', 'pg', 'oracledb', 'mssql'] }), DB_HOST: envalid.host({ default: 'localhost' }), DB_PORT: envalid.port({ default: 3306 }), DB_DATABASE: envalid.str({ docs: 'db database name' }), DB_USERNAME: envalid.str({ docs: 'db username' }), DB_PASSWORD: envalid.str({ docs: 'db userpassword' }), DB_CHARSET: envalid.str({ default: 'utf8', docs: 'db connection charset' }), DB_TIMEZONE: envalid.str({ default: '+08:00', docs: 'db connection timezone', }), }, { strict: true } );<file_sep>import { confSys } from "../config"; const shortid = require('shortid'); // shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@'); if (0 <= confSys.APP_INSTANCE && confSys.APP_INSTANCE <= 16) { shortid.worker(confSys.APP_INSTANCE); } else { throw new Error('shortid of worker id. Should be an integer between 0 and 16'); } export function uuid(): string { return shortid.generate(); } <file_sep>import "reflect-metadata"; import confEnv from "src/config"; import { ClassrouterFactory, JsonResponseFilter } from 'classrouter' import { ExceptionConvert } from "@napp/exception"; import { MainController } from "src/api/main.controller"; import loggerDefault from "src/logger"; import { dbInit } from "src/model"; const express = require('express'); const morgan = require('morgan'); const cors = require('cors') async function startup() { const app = express(); try { await dbInit(); } catch (error) { loggerDefault.error('db connectio error', ExceptionConvert(error).toObject()); throw error; } if (confEnv.LOG_ACCESS) { app.use(morgan(confEnv.LOG_ACCESS_FORMAT)); } app.use(cors()) app.use(express.static('dist.console.frontend')); const factory = new ClassrouterFactory({ basePath: '/api', logger: (l: string, m: string, d: any) => loggerDefault.log(l, m, d), routerBuilder: () => express.Router(), errorParser: (err: any) => ExceptionConvert(err), controllers: [MainController], responseFilters: { default: new JsonResponseFilter(), filters: [ ] // your custom response filters }, }); factory.build(app); app.listen(confEnv.SERVER_PORT, confEnv.SERVER_HOST, () => { const serverType = confEnv.isProduction ? 'production' : 'development' loggerDefault.info(`Server (${serverType}) running port="${confEnv.SERVER_PORT}", host="${confEnv.SERVER_HOST}"`, { port: confEnv.SERVER_PORT, host: confEnv.SERVER_HOST, app_instance: confEnv.NODE_APP_INSTANCE }) }); } // tslint:disable-next-line: no-console startup().catch(console.log); <file_sep>import * as winston from 'winston'; import * as path from 'path'; import confEnv, { confSys } from 'src/config'; const formatFile = winston.format.combine( winston.format.timestamp({}), winston.format.json({}) ); const colorizer = winston.format.colorize({}); const formatConsole = winston.format.combine( winston.format.timestamp({}), winston.format.printf(msg => { let text = msg.timestamp + colorizer.colorize(msg.level, ` [${msg.level}] `) + msg.message; let meta: Record<string, any> = {}; for (let k of Object.keys(msg)) { if (k === 'level' || k === 'message' || k === 'timestamp') { continue; } meta[k] = msg[k]; } return text + ' ' + colorizer.colorize('info', `${JSON.stringify(meta)}`); }) ); export const loggerSql = winston.createLogger({ transports: [] }); if (confEnv.LOG_SQL_FILE) { loggerSql.add(new winston.transports.File({ format: formatFile, filename: path.resolve(confEnv.LOG_DIR, `sql-${confSys.APP_INSTANCE}.log`), level: confEnv.LOG_SQL_FILE_LEVEL, maxsize: confEnv.LOG_SQL_FILE_FILESIZE, maxFiles: confEnv.LOG_SQL_FILE_MAXFILE })); } if (confEnv.LOG_SQL_CONSOLE) { loggerSql.add(new winston.transports.Console({ format: formatConsole, level: confEnv.LOG_SQL_CONSOLE_LEVEL })); } export const loggerDefault = winston.createLogger({ transports: [], exceptionHandlers: [ new winston.transports.File({ format: formatFile, filename: path.resolve(confEnv.LOG_DIR, `exceptions-${confSys.APP_INSTANCE}.log`), }), new winston.transports.Console({ format: formatConsole }) ] }); if (confEnv.LOG_DEFAULT_FILE) { loggerDefault.add(new winston.transports.File({ format: formatFile, filename: path.resolve(confEnv.LOG_DIR, `default-${confSys.APP_INSTANCE}.log`), level: confEnv.LOG_DEFAULT_FILE_LEVEL, maxsize: confEnv.LOG_DEFAULT_FILE_FILESIZE, maxFiles: confEnv.LOG_DEFAULT_FILE_MAXFILE })); } if (confEnv.LOG_DEFAULT_CONSOLE) { loggerDefault.add(new winston.transports.Console({ format: formatConsole, level: confEnv.LOG_DEFAULT_CONSOLE_LEVEL })); } export default loggerDefault;<file_sep>import { plainToClass } from "class-transformer"; import { IPipeTransform, Classtype } from "classrouter"; export class DtoPipe implements IPipeTransform { constructor(public classty: Classtype) { } transform(value: any) { let ins = plainToClass(this.classty, value); return ins; } } <file_sep>const bodyParser = require("body-parser"); export function urlencodedBodyParser() { return bodyParser.urlencoded({ extended: false }); } export function jsonBodyParser() { return bodyParser.json(); } <file_sep>import { Get, Action, Controller, QueryParam, RequestParam, Post, BodyParam } from "classrouter"; import { dtoLoginByToken, dtoLoginBySid } from "console-dto/login"; import { jsonBodyParser } from "src/common/parser"; import { DtoValidatePipe } from "src/common/dto.valid.pipe"; import { DtoPipe } from "src/common/dto.pipe"; import { IsNotEmpty } from "class-validator"; import { userly } from "src/userly"; import { DBSession } from "src/model/m.session"; import { uuid } from "src/common/uuid"; // tslint:disable-next-line: no-namespace namespace dto { export class LoginTokenReq implements dtoLoginByToken.IReq { @IsNotEmpty() appusertoken!: string; } export class LoginTokenRes implements dtoLoginByToken.IRes { username: string = ''; sid: string = ''; } export class LoginSidReq implements dtoLoginBySid.IReq { @IsNotEmpty() sid: string = ''; } export class LoginSidRes implements dtoLoginBySid.IRes { username: string = ''; } } @Controller({ name: 'login', path: '/login', }) export class LoginController { @Post({ path: '/token', name: 'token', befores: [jsonBodyParser] }) async loginToken( @BodyParam(new DtoValidatePipe(dto.LoginTokenReq)) { appusertoken }: dto.LoginTokenReq ): Promise<dto.LoginTokenRes> { // console.log('userlytoken',userlytoken) let user = await userly.loginByTokencode(appusertoken); let sess = await DBSession.query().insert({ id: uuid(), userly: user.userid, userly_token: user.usertoken, created_at: new Date(), expired_at: new Date(Date.now() + user.tokenexp) }); return { username: user.name, sid: sess.id || '' } } @Post({ path: '/sid', name: 'sid', befores: [jsonBodyParser] }) async loginSid( @BodyParam(new DtoValidatePipe(dto.LoginSidReq)) { sid }: dto.LoginSidReq ): Promise<dto.LoginSidRes> { let sess = await DBSession.query().findById(sid); if (sess) { let user1 = await userly.userProfileByAppuserid1(sess.userly); console.log('user', user1) return { username: 'aaa' } } throw new Error('session not found'); } }<file_sep>{ "name": "userly-banner-backend", "version": "2.0.0", "description": "userly banner system", "scripts": { "db:init": "node opt/db.init.js", "db:new": "knex migrate:make", "db:up": "knex migrate:latest", "db:down": "knex migrate:rollback", "build": "webpack --config=opt/webpack.config.js --mode=production", "watch": "webpack --config=opt/webpack.config.js --mode=development --watch", "nodemon": "nodemon --config opt/nodemon.config.json", "start": "concurrently -i \"npm run nodemon\" \"npm run watch\"", "tslint": "tslint --project tsconfig.json --config tslint.json", "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "@napp/exception": "^2.0.0", "body-parser": "^1.19.0", "class-transformer": "^0.2.3", "class-validator": "^0.11.1", "classrouter": "4.4.2", "cors": "^2.8.5", "cross-fetch": "^3.0.4", "envalid": "^6.0.1", "express": "^4.17.1", "jsonwebtoken": "^8.5.1", "knex": "^0.20.13", "morgan": "^1.9.1", "mysql2": "^2.1.0", "objection": "^2.1.3", "reflect-metadata": "^0.1.13", "shortid": "^2.2.15", "winston": "^3.2.1" }, "devDependencies": { "@types/node": "^13.9.1", "concurrently": "^5.1.0", "nodemon": "^2.0.2", "rimraf": "^3.0.2", "source-map-support": "^0.5.16", "ts-loader": "^6.2.1", "tslint": "^6.1.0", "typescript": "^3.8.3", "webpack": "^4.42.0", "webpack-cli": "^3.3.11", "webpack-node-externals": "^1.7.2" }, "private": true, "author": "<EMAIL>", "license": "ISC" } <file_sep>const knex = require('knex'); exports.up = /** * * @param {knex} knex */ function (knex) { return knex.schema .createTable('sessions', function (table) { table.string('id').primary(); table.string('userly').notNullable(); table.string('userly_token').notNullable(); table.dateTime('created_at').notNullable(); table.dateTime('expired_at').notNullable(); }) }; exports.down = function (knex) { return knex.schema .dropTable("sessions") }; <file_sep>import fetch, { Response, Request } from 'cross-fetch'; import { ExceptionConvert } from '@napp/exception'; export namespace RestFull { export interface IOptions { headers: Record<string, string> } const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } async function _fetch(res: Response) { if (res.ok && res.json) { return res.json(); } if(res.json) { let err =await res.json(); console.log('err',err) throw ExceptionConvert(err); } console.log(await res.text()) throw Error(res.statusText); } export async function get<T>(url: string, options?: IOptions): Promise<T> { let raw = await fetch((url), { method: 'GET', headers: { ...headers, ...(options?.headers) } }) ; return await _fetch(raw) } export async function post<T>(url: string, data: Record<string, any>, options?: IOptions): Promise<T> { let raw = await fetch((url), { method: 'POST', headers: { ...headers, ...(options?.headers) }, body: JSON.stringify(data || {}) }); return await _fetch(raw) } }
0ce2c826f7e542a8005cb0ab65922a22809dbe48
[ "JavaScript", "JSON", "TypeScript" ]
22
TypeScript
Farcek/startup-backend
ed78fe0ebfcf7453573b90405f3fde8dddc198e8
21f4ed86a8b8d03db85d83d2a7910148c838c02b
refs/heads/master
<file_sep>const async = require('async'); const logger = require('winston'); const common = require('spred-common'); const algoliaSearch = require('algoliasearch'); var client; var globalIndex; var tagIndex; var userIndex; var castIndex; function init() { logger.info('Intializing algolia search engine ...'); client = algoliaSearch('KGZYQKI2SD', '5363665898cdaa3fef7b751b1d46717d'); globalIndex = client.initIndex('global'); userIndex = client.initIndex('users'); tagIndex = client.initIndex('tags'); castIndex = client.initIndex('casts'); } function indexAll(cb) { logger.info('Indexing users ...'); common.userModel.find({}, function (err, fUsers) { if (err) { cb(err); } else { var users = []; fUsers.forEach(function (user) { users.push({ type: 'user', pseudo: '@' + user.pseudo, name: '@' + user.pseudo, fistname: user.firstName, lastname: user.lastName, objectID: user._id }); }); logger.info('Indexing tags ...'); common.tagModel.getAll(function (err, fTags) { if (err) { cb(err); } else { var tags = []; fTags.forEach(function (tag) { tags.push({ type: 'tag', name: '#' + tag.name, objectID: tag._id }); }); logger.info('Indexing spredcasts ...'); var casts = []; common.spredCastModel.find({ isPublic: true }, function (err, fCats) { if (err) { cb(err); } else { fCats.forEach(function (cast) { casts.push({ type: 'cast', name: cast.name, url: cast.url, objectID: cast._id }); }); var allIndex = users.concat(tags, casts); globalIndex.addObjects(allIndex, function (err) { if (err) { cb(err); } else { userIndex.addObjects(users, function (err) { if (err) { cb(err); } else { tagIndex.addObjects(tags, function (err) { if (err) { cb(err); } else { castIndex.addObjects(casts, function (err) { if (err) { cb(err); } else { cb(); } }); } }); } }); } }); } }); } }); } }); } function addIndex(indexes, objects, cb) { logger.info('Adding object to algolia ...'); async.waterfall([ function (callback) { if (indexes.indexOf('global') != -1) { globalIndex.addObjects(objects, function (err) { callback(err); }); } else { callback(null); } }, function (callback) { if (indexes.indexOf('user') != -1) { userIndex.addObjects(objects, function (err) { callback(err); }); } else { callback(null); } }, function (callback) { if (indexes.indexOf('tag') != -1) { tagIndex.addObjects(objects, function (err) { callback(err); }); } else { callback(null); } }, function (callback) { if (indexes.indexOf('cast') != -1) { castIndex.addObjects(objects, function (err) { callback(err); }); } else { callback(null); } } ], function (err) { cb(err); }); } module.exports.init = init; module.exports.indexAll = indexAll; module.exports.addIndex = addIndex;<file_sep>const vhost = require('vhost'); const config = require('config'); const devService = require('spred-dev-service'); const loginService = require('spred-login-service'); const apiService = require('spred-api-service'); function registerApp (masterApp, algoliaAddIndexFunc) { masterApp.use(vhost(config.get('devService.url'), devService.getApp(true, algoliaAddIndexFunc))); masterApp.use(vhost(config.get('loginService.url'), loginService.getApp(true, algoliaAddIndexFunc))); masterApp.use(vhost(config.get('apiService.url'), apiService.getApp(true, algoliaAddIndexFunc))); } module.exports.registerApp = registerApp;<file_sep>const gulp = require('gulp'); const shell = require('gulp-shell'); const eslint = require('gulp-eslint'); gulp.task('default', function () { console.log('Default task'); }); gulp.task('lint', function () { return gulp.src(['src/*.js', 'src/app/*.js', 'test/**/*.js', 'task/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('update-dep', shell.task(['npm update spred-dev-service', 'npm update spred-login-service', 'npm update spred-api-service'])); <file_sep># rest-service Rest service host for spred <file_sep>const common = require('spred-common'); const httpHelper = require('spred-http-helper'); function remindCast(cb) { var castIndex = 0; var remindDate = new Date().getTime() + 20 * 60000; common.spredCastModel.getNeedRemindCast(remindDate, function (err, fCasts) { if (err) { cb(err); } else { if (fCasts.length > 0) { fCasts.forEach(function (fCast) { httpHelper.sendMail(fCast.creator.email, 'remind-caster', { username: fCast.creator.pseudo, cast_name: fCast.name, cast_url: fCast.url }, function (err) { if (err) { cb(err); } else { common.spredcastReminderModel.getCastReminder(fCast._id, function (err, fReminders) { if (err) { cb(err); } else { var i = 0; if (fReminders.length > 0) { fReminders.forEach(function (fReminder) { httpHelper.sendMail(fReminder.user.email, 'remind-viewer', { username: fReminder.user.pseudo, cast_name: fCast.name, cast_url: fCast.url }, function (err) { if (err) { cb(err); } else { i++; if (i === fReminders.length) { common.spredCastModel.reminded(fCast._id, function (err) { if (err) { cb(err); } else { castIndex++; if (castIndex === fCasts.length) { cb(); } } }); } } }); }); } else { common.spredCastModel.reminded(fCast._id, function (err) { if (err) { cb(err); } else { castIndex++; if (castIndex === fCasts.length) { cb(); } } }); } } }); } }); }); } else { cb(); } } }); } function endCast(cb) { var endDate = new Date(); endDate.setMinutes(endDate.getMinutes() + 15); common.spredCastModel.find({ state: 0, date: { $lt: endDate } }, function (err, fCasts) { if (err) { cb(err); } else if (fCasts.length == 0) { cb(null); } else { var i = 0; fCasts.forEach(function (fCast) { fCast.state = 3; fCast.save(function (err) { if (err) { cb(err); } else { if (i == fCasts.length - 1) { cb(null); } ++i; } }); }); } }); } module.exports.remindCast = remindCast; module.exports.endCast = endCast;
ca4f51f8999320b7a2d950057404b1082602ad61
[ "JavaScript", "Markdown" ]
5
JavaScript
SpredCo/rest-service
9629207eaa94c2bf4ad30c5cf571581a2def95ce
afcb23c438c582aceeeff7de44e3ee5f64e1285f
refs/heads/master
<file_sep>package com.example.deliciousfood; import android.app.Dialog; import android.content.Intent; import android.nfc.Tag; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.deliciousfood.Widget.MyDialog; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int STATE_FILTER = 1; private static final int STATE_NORMAL = 2; private int mState = STATE_NORMAL; private ImageButton myImageBtn; private CheckBox mCheckBoxChineseFood; private CheckBox mCheckBoxFastFood; private CheckBox mCheckBoxDessert; private RadioGroup mRadioGroup; private RadioButton mSpicyYes; private RadioButton mSpicyNo; private TextView mTvPrice; private SeekBar mSeekBarPrice; private Button mBtnReset; private Button mBtnSearch; private Button mBtnPrev; private Button mBtnNext; private List<Food> mFoodList,filteredFood; private int mCurrentPage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<Food> foods = FoodAPI.getDemoFood(this); initViews(); myImageBtn = (ImageButton) findViewById(R.id.image_btn); } private void initViews(){ mCheckBoxChineseFood = (CheckBox) findViewById(R.id.checkBox_chinesefood); mCheckBoxFastFood = (CheckBox) findViewById(R.id.checkBox_fastfood); mCheckBoxDessert = (CheckBox) findViewById(R.id.checkBox_desert); mCheckBoxChineseFood.setChecked(true); mCheckBoxFastFood.setChecked(true); mCheckBoxDessert.setChecked(true); mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup); mSpicyYes = (RadioButton) findViewById(R.id.radio_yes); mSpicyNo = (RadioButton) findViewById(R.id.radio_no); mRadioGroup.check(R.id.radio_no); mTvPrice = (TextView) findViewById(R.id.tv_price); mSeekBarPrice = (SeekBar) findViewById(R.id.seekBar); mSeekBarPrice.setProgress(100); mTvPrice.setText(""+mSeekBarPrice.getProgress()); mSeekBarPrice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTvPrice.setText(""+progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); myImageBtn = (ImageButton) findViewById(R.id.image_btn); mFoodList = initData(); mCurrentPage = 0; myImageBtn.setImageResource(mFoodList.get(mCurrentPage).getImgResID()); mBtnPrev = (Button) findViewById(R.id.btn_prev); mBtnNext = (Button) findViewById(R.id .btn_next); mBtnPrev.setOnClickListener(this); mBtnNext.setOnClickListener(this); mBtnReset = (Button) findViewById(R.id.btn_reset); mBtnSearch = (Button) findViewById(R.id.btn_search); mBtnReset.setOnClickListener(this); mBtnSearch.setOnClickListener(this); } private List<Food> initData(){ return FoodAPI.getDemoFood(this); } public void onClick(View v){ switch (v.getId()){ case R.id.btn_prev: showPrevPage(); break; case R.id.btn_next: showNextPage(); break; case R.id.btn_reset: mState = STATE_NORMAL; loadInitialView(); break; case R.id.btn_search: mState = STATE_FILTER; showFilteredFoods(); break; } } private void loadInitialView(){ mCheckBoxDessert.setChecked(true); mCheckBoxFastFood.setChecked(true); mCheckBoxChineseFood.setChecked(true); mRadioGroup.check(R.id.radio_no); showPage(0); } private void showFilteredFoods(){ filteredFood = filteredFoods(); boolean isFilteredFoodEmpty = (filteredFood.size() < 1); if(isFilteredFoodEmpty){ Log.d("MainActivity",""+filteredFood.size()); /*MyDialog myDialog = new MyDialog(MainActivity.this); myDialog.setConfirm(new MyDialog.IOnConfirmListener() { @Override public void onConfirm(MyDialog dialog) { loadInitialView(); } }); 自定义dialog跳出未成功,待解决*/ Toast.makeText(this,"筛选条件有误或未搜到此产品",Toast.LENGTH_LONG).show(); mCheckBoxDessert.setChecked(true); mCheckBoxFastFood.setChecked(true); mCheckBoxChineseFood.setChecked(true); mRadioGroup.check(R.id.radio_no); mSeekBarPrice.setProgress(100); mState = STATE_NORMAL; } else{ showPage(0); } } private List<Food> filteredFoods(){ int maxPrice = mSeekBarPrice.getProgress(); boolean isSpicy = mRadioGroup.getCheckedRadioButtonId() ==R.id.radio_yes; List<Integer> selectedFoodTypes = new ArrayList<>(); if(mCheckBoxChineseFood.isChecked()){ selectedFoodTypes.add(Food.CHINESE_FOOD); } if(mCheckBoxFastFood.isChecked()){ selectedFoodTypes.add(Food.FAST_FOOD); } if(mCheckBoxDessert.isChecked()){ selectedFoodTypes.add(Food.DESSERT_FOOD); } List<Food> results = new ArrayList<>(); for(Food food:mFoodList){ if(food.getPrice() < maxPrice && selectedFoodTypes.contains(food.getType()) && food.isSpicy() == isSpicy){ results.add(food); } } return results; } private List<Food> currentShowingFood(){ switch (mState){ case STATE_FILTER: return filteredFood; case STATE_NORMAL: return mFoodList; default: return mFoodList; } } private void showPrevPage(){ int prevPage = (mCurrentPage + currentShowingFood().size()- 1) % (currentShowingFood().size()); showPage(prevPage); } private void showNextPage(){ int nextPage = (mCurrentPage + 1) % (currentShowingFood().size()); showPage(nextPage); } private void showPage(int index){ Log.d("MainActivity",""+index); Food food = currentShowingFood().get(index); myImageBtn.setImageResource(food.getImgResID()); mCurrentPage = index; } public void openDetail(View view) { Intent intent = new Intent(this,DetailActivity.class); Bundle bundle = new Bundle(); Food food = currentShowingFood().get(mCurrentPage); bundle.putString("name",food.getName()); bundle.putInt("imgResId",food.getImgResID()); bundle.putInt("price",food.getPrice()); bundle.putFloat("rating",food.getRating()); bundle.putBoolean("isSpicy",food.isSpicy()); intent.putExtras(bundle); startActivity(intent); } } <file_sep>package com.example.deliciousfood; import android.content.Context; import java.util.ArrayList; import java.util.List; public class FoodAPI { public static List<Food> getDemoFood(Context context){ List<Food> foods = new ArrayList<>(); foods.add(new Food("提拉米苏",R.drawable.tilamisu,80,Food.DESSERT_FOOD,false,4.5f)); foods.add(new Food("舒芙蕾",R.drawable.souffle,65,Food.DESSERT_FOOD,false,4f)); foods.add(new Food("欧培拉",R.drawable.opera,48,Food.DESSERT_FOOD,false,3.5f)); foods.add(new Food("汉堡包",R.drawable.hamberger,15,Food.FAST_FOOD,false,4.0f)); foods.add(new Food("三明治",R.drawable.sanmingzhi,8,Food.FAST_FOOD,false,4.5f)); foods.add(new Food("麻辣鸡块",R.drawable.malajikuai,18,Food.CHINESE_FOOD,true,4.0f)); foods.add(new Food("宫保鸡丁",R.drawable.gongbaojiding,20,Food.CHINESE_FOOD,true,5.0f)); foods.add(new Food("鱼香肉丝",R.drawable.yuxiangrousi,24,Food.CHINESE_FOOD,false,4.0f)); foods.add(new Food("水煮肉片",R.drawable.shuizhurou,32,Food.CHINESE_FOOD,true,4.5f)); foods.add(new Food("红烧肉",R.drawable.hongshaorou,38,Food.CHINESE_FOOD,false,5.0f)); return foods; } } <file_sep>package com.example.deliciousfood; public class Food { public static final int CHINESE_FOOD = 1; public static final int FAST_FOOD = 2; public static final int DESSERT_FOOD = 3; private String name; private int imgResID; private int price; private int type; private boolean isSpicy; private float rating; public Food(String name, int imgResID, int price, int type, boolean isSpicy, float rating) { this.name = name; this.imgResID = imgResID; this.price = price; this.type = type; this.isSpicy = isSpicy; this.rating = rating; } public Food() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getImgResID() { return imgResID; } public void setImgResID(int imgResID) { this.imgResID = imgResID; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getType() { return type; } public void setType(int type) { this.type = type; } public boolean isSpicy() { return isSpicy; } public void setSpicy(boolean spicy) { isSpicy = spicy; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } }
5bebb52f8a9b18a5913fa51b574a88bee7d0fdba
[ "Java" ]
3
Java
Noyce765103/DeliciousFood
4eae95aa430376dc80a0a0f75e2dc43a43efdd18
36e557835e4f62b11443b6ea9f0e6f6882911096
refs/heads/master
<repo_name>hiboma/bukkowasu<file_sep>/Vagrantfile # -*- mode: ruby -*- VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "CentOS 6.5 x86_64" config.vm.box_url = "https://github.com/2creatives/vagrant-centos/releases/download/v6.5.1/centos65-x86_64-20131205.box" config.vm.provider :virtualbox do |vb| vb.gui = true end # Prevent Vagrantfile to be deleted by `rm -rfv /` !!!! config.vm.synced_folder ".", "/vagrant", disabled: true end
20c748097711927c7f7742010184ed97269a941d
[ "Ruby" ]
1
Ruby
hiboma/bukkowasu
bb7be15218571e028f88bcc025096ed3cf4e4688
25ce52843f761f4b68ce4210367afb430125efb5
refs/heads/master
<file_sep>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using CsvHelper; using MoreLinq.Extensions; namespace MaxMinds { class Program { private const string CityDatabase = "GeoLite2-City-Blocks-IPv4.csv"; private const string LocationDatabase = "GeoIP2-Country-Locations-en.csv"; private const string SourceData = "Locations_in.csv"; private const string TargetGood = "Locations_success.csv"; private const string TargetBad = "Locations_failed.csv"; private const string TargetOther = "Locations_different_region.csv"; private const int ThreadsToUse = 12; private static ConcurrentBag<Bar> _goodIds; private static ConcurrentBag<Bar> _badIds; private static ConcurrentBag<Bar> _wrongRegion; private static List<MaxMindLocationCsv> _locations; private static List<MaxMindCsv> _blocks; static void Main(string[] args) { Console.WriteLine( "This product includes GeoLite2 data created by MaxMind, available from\r\n<a href=\"https://www.maxmind.com\">https://www.maxmind.com</a>."); var sw = new Stopwatch(); sw.Start(); var originalColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; //read inputs var inputReader = new StreamReader(SourceData); var inputCsv = new CsvReader(inputReader); inputCsv.Configuration.IgnoreBlankLines = true; inputCsv.Configuration.BadDataFound = null; var records = inputCsv.GetRecords<Foo>().ToArray(); //read maxminds csv, note the mmdb files do not allow postcode lookup, hence using the blocks csv file var maxMindReader = new StreamReader(CityDatabase); var maxMindCsv = new CsvReader(maxMindReader); maxMindCsv.Configuration.IgnoreBlankLines = true; maxMindCsv.Configuration.BadDataFound = null; _blocks = maxMindCsv.GetRecords<MaxMindCsv>().ToList(); var maxMindLocationReader = new StreamReader(LocationDatabase); var maxMindLocationCsv = new CsvReader(maxMindLocationReader); maxMindLocationCsv.Configuration.IgnoreBlankLines = true; maxMindLocationCsv.Configuration.BadDataFound = null; _locations = maxMindLocationCsv.GetRecords<MaxMindLocationCsv>().ToList(); //result stores _goodIds = new ConcurrentBag<Bar>(); _badIds = new ConcurrentBag<Bar>(); _wrongRegion = new ConcurrentBag<Bar>(); //split into threads for speed var total = records.Count(); int recordsPerThread = total / ThreadsToUse; var tasks = new List<Task>(); foreach (var record in records.Batch(recordsPerThread)) { var task = Task.Run(() => { ProcessBatch(record); }); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); sw.Stop(); inputCsv.Dispose(); inputReader.Close(); maxMindCsv.Dispose(); maxMindReader.Close(); Console.WriteLine($"Total of {total} lines processed in {sw.Elapsed.TotalSeconds} seconds."); Console.WriteLine($"Total of {_goodIds.Count} postcodes found."); Console.WriteLine($"Total of {_badIds.Count} postcodes not found."); Console.WriteLine($"Of those not found, {_wrongRegion.Count} postcodes found in another region."); var outputGood = new StreamWriter(TargetGood); var goodCsv = new CsvWriter(outputGood); goodCsv.WriteRecords(_goodIds); goodCsv.Dispose(); var outputBad = new StreamWriter(TargetBad); var badCsv = new CsvWriter(outputBad); badCsv.WriteRecords(_badIds); badCsv.Dispose(); var outputOther = new StreamWriter(TargetOther); var otherCsv = new CsvWriter(outputOther); otherCsv.WriteRecords(_wrongRegion); otherCsv.Dispose(); Console.ForegroundColor = originalColor; Console.WriteLine("Done!"); Console.ReadKey(); } private static void ProcessBatch(IEnumerable<Foo> records) { foreach (var record in records) { LookupMaxMindLocation(record); } } public static void LookupMaxMindLocation(Foo record) { if (string.IsNullOrEmpty(record.Postcode)) { Console.WriteLine($"Skipped {record.Id} as the postcode {record.Postcode} is not populated!"); return; } var finds = _blocks.Where(x => x.postal_code.Trim().Equals(record.Postcode.Trim(), StringComparison.OrdinalIgnoreCase)).ToArray(); foreach (var found in finds) { //which region is it? var region = _locations.FirstOrDefault(l => l.geoname_id.Trim().Equals(found.registered_country_geoname_id.Trim(), StringComparison.OrdinalIgnoreCase)); if (region != null) { if (region.country_iso_code.Trim().Equals(record.RegionCode.Trim(), StringComparison.OrdinalIgnoreCase)) { _goodIds.Add(new Bar() { Id = record.Id, maxmind_latitude = found.latitude, maxmind_longitude = found.longitude, SourceRegion = record.RegionCode, SourcePostcode = record.Postcode, maxmind_country_iso_code = region?.country_iso_code }); return; } } } //Could not find postcode in specified region, try any... if (finds.Any()) { //Console.WriteLine($"Could not find postcode: {record.Postcode} in specified region."); var firstMatch = finds.First(); var firstRegion = _locations.FirstOrDefault(l => l.geoname_id.Trim().Equals(firstMatch.registered_country_geoname_id.Trim(), StringComparison.OrdinalIgnoreCase)); if (firstRegion != null) { _wrongRegion.Add(new Bar() { Id = record.Id, maxmind_latitude = firstMatch.latitude, maxmind_longitude = firstMatch.longitude, SourceRegion = record.RegionCode, SourcePostcode = record.Postcode, maxmind_country_iso_code = firstRegion.country_iso_code }); return; } } //otherwise, totally couldn't find _badIds.Add(new Bar() {Id = record.Id, SourceRegion = record.RegionCode, SourcePostcode = record.Postcode}); } } public class MaxMindCsv { public string network { get; set; } public string geoname_id { get; set; } public string registered_country_geoname_id { get; set; } public string represented_country_geoname_id { get; set; } public string is_anonymous_proxy { get; set; } public string is_satellite_provider { get; set; } public string postal_code { get; set; } public string latitude { get; set; } public string longitude { get; set; } public string accuracy_radius { get; set; } } public class MaxMindLocationCsv { public string geoname_id { get; set; } public string locale_code { get; set; } public string continent_code { get; set; } public string continent_name { get; set; } public string country_iso_code { get; set; } public string country_name { get; set; } public string is_in_european_union { get; set; } } public class Foo { public string Id { get; set; } public string Name { get; set; } public string RegionName { get; set; } public string RegionCode { get; set; } public string City { get; set; } public string County { get; set; } public string Postcode { get; set; } public string State { get; set; } } public class Bar { public string Id { get; set; } public string SourcePostcode { get; set; } public string SourceRegion { get; set; } public string maxmind_latitude { get; set; } public string maxmind_longitude { get; set; } public string maxmind_country_iso_code { get; set; } } } <file_sep># MaxMinds Demo usage of the MaxMinds developer suite. This product includes GeoLite2 data created by MaxMind, available from "https://www.maxmind.com\" With the standard MaxMind database files and nuget libs, it is not possible to lookup latitude/longitude from a PostCode and Region. Here is a rough Proof of concept to acheive the lookup using 2 CSV files that are available from MaxMind.
b1b5a43b716793e5287113935f5d6f29ce425b28
[ "Markdown", "C#" ]
2
C#
paulcamp/MaxMinds
7aa183ef147e6668c47697edcf1675a48987993c
9449adaed596a8e913157e4878f99135098cd6f9
refs/heads/master
<file_sep>/** * Project Euler - https://projecteuler.net/ * <NAME> - 20.09.2016 * * Problem description: * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ (function() { var fib = [1, 2], sum = 2; while (fib[fib.length - 1] < 4e+6) { var n = fib[fib.length - 2] + fib[fib.length - 1]; sum += (n % 2 === 0) ? n : 0; fib.push(n); } console.log(sum); return sum; })(); <file_sep>/** * Project Euler - https://projecteuler.net/ * <NAME> - 20.09.2016 * * Problem description: * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. * Find the sum of all the multiples of 3 or 5 below 1000. */ (function() { var sum = 0, n = 1000; while (n--) { sum += (n % 3 === 0 || n % 5 === 0) ? n : 0; } console.log(sum); return sum; })();
407dcb21d28270cd16f246a8d5586ff6648130c9
[ "JavaScript" ]
2
JavaScript
hugohabel/project-euler
9ff217a16a215ef900ef937bac08d14ca45e6260
90f695b00594bc848d3fa70b881e71f3c9ae866b
refs/heads/master
<file_sep><?php require 'db_connect.php'; use TAOINCOM\Db\Connect as aConn; $conn = new aConn(); $fullName = $_POST['fullName']; $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $emailAddress = $_POST['emailAddress']; echo $conn->send_data($fullName, $username, $password, $emailAddress).'<br>'; // Closing connection $conn->close_conn();<file_sep><?php namespace TAOINCOM\Db; class Connect { // Declaring private variables - for additional security! private $conn; // private $data_search; private $msg; // Declaring public variables for connection to my main Database. private $host_name; private $user_name; private $pass_word; private $db_name; public $data; // public $data_output; public $emailAddress; public $fullName; public $id; public $password; public $sql_data; public $username; public $num_rows; public function __construct() { // Declaring variables to store data to send to database later $this->host_name = 'localhost'; $this->user_name = 'root'; $this->pass_word = ''; $this->db_name = 'website_data_db'; // Creating a connection with the website_data_db database $this->conn = mysqli_connect($this->host_name, $this->user_name, $this->pass_word, $this->db_name); if(!$this->conn) { $this->msg = 'Connection failed!'; // Informing user if connection failed } else { $this->msg = 'Connection successful!'; // Informing user if connection successful } echo $this->msg.'<br>'; } public function send_data($fullName, $username, $password, $emailAddress) { $this->fullName = $fullName; $this->username = $username; $this->password = $<PASSWORD>; $this->emailAddress = $emailAddress; $sql = "SELECT * FROM contact_details;"; if ($result = mysqli_query($this->conn, $sql)) { $this->num_rows = mysqli_num_rows($result); } echo 'There are '.$this->num_rows.' rows in the contact_details table'.'<br>';; //$sql = "SELECT COUNT(*) FROM contact_details;"; settype($this->id, "integer"); // Converting id to int so I can perform Math ops on it $this->id = $this->num_rows + 1; // Ensuring that row_1[id]=1, row_2[id]=2, ... row_n[id]=n echo "The next id value is: ".$this->id.'<br>'; $this->sql_data = "INSERT INTO contact_details (id, full_name, username, password, email_address) VALUES('$this->id', '$this->fullName', '$this->username', '$this->password', '$this->emailAddress');"; if($this->conn ->query($this->sql_data) === TRUE) { $this->msg = 'Data successfully sent to database'.'<br>'; } else { $this->msg = 'Error: '.$this->sql_data.'<br>'.$this->conn->error; } } public function get_data($data) { $data_search = "SELECT * FROM contact_details WHERE full_name = '$data' OR username = '$data' OR password = <PASSWORD>' OR email_address = '$data';"; $result = $this->conn->query($data_search); $row = $result->fetch_assoc(); return $data_output = 'Full Name: '.$row['full_name'].', Username: '. $row['username'].', Email Address: '.$row['email_address'].', Password: '. $row['<PASSWORD>'].'<br>'; } public function get_latest_id() { return $this->id; } public function close_conn() { $this->conn->close(); } }<file_sep><?php require 'db_connect.php'; use TAOINCOM\Db\Connect as aConn; $conn = new aConn(); echo $conn->connect_message(); $conn -> close_conn(); <file_sep><?php require 'db_connect.php'; // include 'data_retrieval.html'; use TAOINCOM\Db\Connect as aConn; $conn = new aConn(); $data = $_POST["data"]; // Retrieving a user's data echo $msg = $conn->get_data($data).'<br>'; // Closing connection $conn->close_conn();<file_sep>const a = Math.max(5, 10); let b = a.toString(); document.write(b);<file_sep><?php class Connect_Class { public $conn; public $msg; public function __contruct($conn, $msg) { $this->conn = $conn; $this->msg = $msg; } public function connect() { // Declaring variables to store data to send to database later $host_name = 'localhost'; $user_name = 'root'; $pass_word = ''; $db_name = 'website_data_db'; // Creating a connection with the test_db database $this->conn = mysqli_connect($host_name, $user_name, $pass_word, $db_name); } public function get_message() { if (!$this->conn) { $this->msg = 'Something went wrong!'; } if($this->conn) { $this->msg = 'Connection successful!'; } return $this->msg; } } $object = new Connect_Class(); $object->connect(); $message = $object->get_message(); echo $message; $this->conn -> close();<file_sep># SW-Eng-Project-Code I have changed the names of the "contact_details" files - both the HTML and PHP ones - to "registration_page". I have also just added 2 new files - one in HTML and one in PHP = and named them "data_retrieval". They are primarily for use by the Service Procider - i.e. me - so I can check the contact details of any given user / member of my website. After loads of trial and error, I have decided to rather have all my php code inside one file, which I have names as "unified_file.php"
db2023388971b3d482a0332d1d4a5cdae6a3b64f
[ "JavaScript", "Markdown", "PHP" ]
7
PHP
Alsim05/SW-Eng-Project-Code
5002fec9bd7ae4e443d4791ce07ac87ebd782e01
41db77a920334d28b72d02784bae96555dd3ae50
refs/heads/master
<repo_name>Seowyongtao/running-event-frontend<file_sep>/src/Container/RegisterModal/RegisterModal.js import React from "react"; import "./RegisterModal.css" import { Form, FormGroup, Label, Input, Row, Col, Button} from 'reactstrap'; import {Link} from "react-router-dom"; class RegisterModal extends React.Component{ state={ registration_fee:"", first_name:"", last_name:"", email:"", date_of_birth:"", age:"", gender:"", nationality:"", nric:"", phone_number:"", address:"" } registration_feeInputHandler=(event)=>{ this.setState({registration_fee:this.props.location.state.registration_fee}) } first_nameInputHandler=(event)=>{ this.setState({first_name:event.target.value}) } last_nameInputHandler=(event)=>{ this.setState({last_name:event.target.value}) } emailInputHandler=(event)=>{ this.setState({email:event.target.value}) } date_of_birthInputHandler=(event)=>{ this.setState({date_of_birth:event.target.value}) } ageInputHandler=(event)=>{ this.setState({age:event.target.value}) } genderInputHandler=(event)=>{ this.setState({gender:event.target.value}) } nationalityInputHandler=(event)=>{ this.setState({nationality:event.target.value}) } nricInputHandler=(event)=>{ this.setState({nric:event.target.value}) } phone_numberInputHandler=(event)=>{ this.setState({phone_number:event.target.value}) } addressInputHandler=(event)=>{ this.setState({address:event.target.value}) } // registerHandler=()=>{ // const data ={ // event_id:this.props.match.params.id, // registration_fee:this.props.location.state.registration_fee, // first_name: this.state.first_name, // last_name:this.state.last_name, // email:this.state.email, // date_of_birth:this.state.date_of_birth, // age:this.state.age, // gender:this.state.gender, // nationality:this.state.nationality, // nric:this.state.nric, // phone_number:this.state.phone_number, // address:this.state.address, // } // axios.post(`http://localhost:5000/api/v1/registration/new`, data,{ // headers: { // "Authorization": "Bearer " + localStorage.getItem("JWT") // } // }) // .then((response) => { // alert('Successfully register! '); // }) // .catch(function (error) { // console.log(error); // }); // } render(){ let gender=["male", "female"] return( <div style={{height:"100vh", width:"100vw",backgroundColor:"#232222"}}> <div className="Modal fade-in"> <Form> <FormGroup> <Label tag="h4" for="exampleEmail">Register Form</Label> </FormGroup> <hr></hr> <h5>Personal details</h5> <Row> <Col> <FormGroup> <Label for="firstName">First Name</Label> <Input type="text" name="firstName" placeholder="please enter your first name" onChange={this.first_nameInputHandler} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="lastName">Last Name</Label> <Input type="text" name="lastName" placeholder="please enter your last name" onChange={this.last_nameInputHandler} /> </FormGroup> </Col> </Row> <Row> <Col md="4"> <FormGroup> <Label for="dateOfBirth">Date of Birth</Label> <Input type="text" name="dateOfBirth" placeholder="DD/MM/YYYY" onChange={this.date_of_birthInputHandler} /> </FormGroup> </Col> <Col md="4"> <FormGroup> <Label for="age">Age</Label> <Input type="text" name="age" placeholder="e.g 20" onChange={this.ageInputHandler} /> </FormGroup> </Col> <Col md="4"> <FormGroup> <Label for="gender">Gender</Label> <Input type="select" name="gender" placeholder="e.g male" onChange={this.genderInputHandler} > <option></option> { gender.map((o, index)=> { return(<option key={index} value={o}>{o}</option>) } ) } </Input> </FormGroup> </Col> </Row> <Row> <Col md="3"> <FormGroup> <Label for="nric">NRIC</Label> <Input type="text" name="nric" placeholder="IC number" onChange={this.nricInputHandler} /> </FormGroup> </Col> <Col md="3"> <FormGroup> <Label for="nationality">Nationality</Label> <Input type="text" name="nationality" placeholder="e.g Malaysia" onChange={this.nationalityInputHandler} /> </FormGroup> </Col> <Col md="6"> <FormGroup> <Label for="email">Email</Label> <Input type="text" name="email" placeholder="please enter valid email" onChange={this.emailInputHandler} /> </FormGroup> </Col> </Row> <h5>Contact details</h5> <Row> <Col> <FormGroup> <Label for="mobilePhone">Mobile Phone</Label> <Input type="text" name="mobilePhone" placeholder="please enter your phone number" onChange={this.phone_numberInputHandler} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="address">Residential Address</Label> <Input type="text" name="address" placeholder="please enter your residential address" onChange={this.addressInputHandler} /> </FormGroup> </Col> </Row> <h5>Payment detail</h5> <Row> <Col> <FormGroup> <Label for="registrationFee">Registration Fee</Label> <Input type="text" name="registrationFee" value={this.props.location.state.registration_fee} onChange={this.registration_feeInputHandler} /> </FormGroup> </Col> </Row> <Link to={{pathname:"/payment", state:{registration_fee:this.props.location.state.registration_fee, data :{ event_id:this.props.match.params.id, registration_fee:this.props.location.state.registration_fee, first_name: this.state.first_name, last_name:this.state.last_name, email:this.state.email, date_of_birth:this.state.date_of_birth, age:this.state.age, gender:this.state.gender, nationality:this.state.nationality, nric:this.state.nric, phone_number:this.state.phone_number, address:this.state.address }}}}><Button className="btn-success btn-block"> Submit</Button></Link> <Link to={{pathname:"/event"}}><Button className="btn-danger btn-block" >Cancel</Button></Link> </Form> </div> </div> ) } } export default RegisterModal;<file_sep>/src/Container/ShowEvent/ShowEvent.js import React from "react"; import "./ShowEvent.css"; import { Navbar, NavbarBrand, Nav, NavItem, NavLink, Row, Col,UncontrolledDropdown, DropdownToggle, DropdownMenu,DropdownItem} from 'reactstrap'; import {Redirect, Link} from "react-router-dom"; import AddEventModal from "../../Components/AddEventModal/AddEventModal"; import axios from "axios"; import Categorylogo from "../../Assets/Images/category.jpg" // let ID =localStorage.getItem("user_id") class ShowEvent extends React.Component{ state={ logout:false, showAddItem:false, name:"", file_name:"", category:"", location:"", reward:"", event_date:"", registration_fee:"", registration_closes:"", description:"", events:[], // registerModal:false } componentDidMount(){ this.fetchEvent() } fetchEvent= ()=>{ axios.get(`http://localhost:5000/api/v1/event/show`,{ headers: { "Authorization": "Bearer " + localStorage.getItem("JWT") } }) .then(result => { this.setState({events:result.data.event}) }) .catch(error => { console.log('ERROR: ', error) }) } logoutHandler = () =>{ localStorage.removeItem("JWT") localStorage.removeItem("user_id") localStorage.removeItem("username") this.setState({logout: true}) } closeAddItem =()=>{ this.setState({showAddItem:false}) } // closeRegistration = ()=>{ // this.setState({registerModal: false}) // } nameInputHandler =(event)=>{ this.setState({name:event.target.value}) } file_nameInputHandler =(event)=>{ this.setState({file_name:event.target.value}) } categoryInputHandler =(event)=>{ this.setState({category:event.target.value}) } locationInputHandler =(event)=>{ this.setState({location:event.target.value}) } rewardInputHandler =(event)=>{ this.setState({reward:event.target.value}) } event_dateInputHandler =(event)=>{ this.setState({event_date:event.target.value}) } registration_feeInputHandler =(event)=>{ this.setState({registration_fee:event.target.value}) } registration_closesInputHandler =(event)=>{ this.setState({registration_closes:event.target.value}) } descriptionInputHandler =(event)=>{ this.setState({description:event.target.value}) } addEventHandler =(event)=>{ event.preventDefault(); const data ={ name: this.state.name, file_name: this.state.file_name, category:this.state.category, location:this.state.location, reward:this.state.reward, event_date:this.state.event_date, registration_fee:this.state.registration_fee, registration_closes:this.state.registration_closes, description:this.state.description } axios.post(`http://localhost:5000/api/v1/event/new`, data,{ headers: { "Authorization": "Bearer " + localStorage.getItem("JWT") } }) .then((response) => { alert('Successfully Add An Event! '); this.setState({showAddItem:!this.state.showAddItem}) this.fetchEvent() }) .catch(function (error) { console.log(error); }); } render(){ // console.log(localStorage.getItem("user_id")) if(this.state.logout ===true){ return <Redirect to="/" /> } return( <div> <Navbar className="Navbar " light expand="md" sticky="top"> <NavbarBrand href="/"><strong className="NavbarTitle">RUN<strong style={{color:"#F0E68C"}}>a`Z</strong></strong></NavbarBrand> <Nav className="ml-auto" navbar> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret> <img src={Categorylogo} className="categorylogo" alt='test'/> <strong>More</strong> </DropdownToggle> <DropdownMenu right> <DropdownItem> <NavItem> <NavLink style={{cursor:"pointer", color:"black"}} onClick={()=>this.setState({showAddItem:!this.state.showAddItem})}>Organise Event</NavLink> </NavItem> </DropdownItem> <DropdownItem> <NavItem> <Link to={{pathname:`/myevent/${localStorage.getItem("user_id")}`}} style={{cursor:"pointer", color:"black",marginLeft:"10px"}} >My events</Link> </NavItem> </DropdownItem> <DropdownItem divider /> <DropdownItem> <NavItem> <NavLink style={{cursor:"pointer", color:"black"}} onClick={this.logoutHandler}>Log Out</NavLink> </NavItem> </DropdownItem> </DropdownMenu> </UncontrolledDropdown> </Nav> </Navbar> <Row style={{backgroundColor:"#232222", minHeight:"130%vh"}}> { this.state.events.map((event, index)=>{ return( <Col md={{ size: 8, offset: 2 }} style={{ height:"330px", backgroundColor:"white", position:"relative", marginTop:"100px", marginBottom:"50px"}} className="event" key={index} onClick={()=>this.setState({registerModal:true})}> <Link to={{pathname:`/registration/${event.event_id}`,state:{registration_fee:event.registration_fee}}}> <Row className="h-100 w-100 eventOption" style={{position:"absolute", color:"black"}}> <Col className="h-100 p-0" md="8" ><img className="h-100 w-100" src="https://source.unsplash.com/user/erondu/654x330" alt="event"></img></Col> <Col className="h-100 w-100 p-2" md="4" > {/* <br></br> */} <strong style={{fontFamily:"Anton", fontSize:"x-large"}} >{event.name}</strong> <hr></hr> <div> <p><strong>EVENT DATE:</strong> {event.event_date}</p> <p><strong>LOCATION:</strong> {event.location}</p> <p><strong>CATEGORY:</strong> {event.category}</p> <p><strong>REWARDS:</strong> {event.reward}</p> <p><strong>REGISTRATION FEE:</strong> RM{event.registration_fee}</p> <p><strong style={{color:"red"}}>REGISTRATION CLOSES:</strong> {event.registration_closes}</p> </div> </Col> </Row> </Link> {/* { this.state.registerModal===true ?<RegisterModal registration_fee={event.registration_fee} > </RegisterModal> :null } */} </Col> ) }) } { this.state.showAddItem===true ?<AddEventModal name={this.nameInputHandler} file_name={this.file_nameInputHandler} category={this.categoryInputHandler} location={this.locationInputHandler} reward={this.rewardInputHandler} event_date={this.event_dateInputHandler} registration_fee={this.registration_feeInputHandler} registration_closes={this.registration_closesInputHandler} description={this.descriptionInputHandler} addEvent={this.addEventHandler} closeAddItem={this.closeAddItem}></AddEventModal> :null } {/* { this.state.registerModal===true ?<RegisterModal closeRegistration={this.closeRegistration} > </RegisterModal> :null } */} </Row> </div> ) } } export default ShowEvent;<file_sep>/src/Container/Homepage/Homepage.js import React from "react"; import { Navbar, NavbarBrand, Nav, NavItem, NavLink} from 'reactstrap'; import "./Homepage.css"; import SignUpModal from "../../Components/SignUpModal/SignUpModal" ; import LogInModal from "../../Components/LogInModal/LoginModal"; import axios from "axios"; import {Redirect} from "react-router-dom"; class Homepage extends React.Component{ state={ showSignUp: false, showLogIn: false, username:"", email:"", password:"", login: false } closeSignUpModal=()=>{ this.setState({showSignUp:!this.state.showSignUp}) } closeLogInModal=()=>{ this.setState({showLogIn:!this.state.showLogIn}) } nameInputHandler =(event)=>{ this.setState({username:event.target.value}) } emailInputHandler =(event)=>{ this.setState({email:event.target.value}) } passwordInputHandler =(event)=>{ this.setState({password: event.target.value}) } signUpHandler=(event)=>{ const validateEmail = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test(this.state.email) const validatePassword = /^[\dA-Za-z]\w{8,}$/.test(this.state.password) const inputIsNotEmpty = this.state.email.length !== 0 && this.state.username.length !== 0 && this.state.password.length !== 0 if(validateEmail === false){ alert("please enter valid email address") } if(validatePassword ===false){ alert("password format does not match!") } if(this.state.email.length === 0 ){ alert("please enter your email address!") } if(this.state.password.lenth === 0){ alert("please enter your password!") } if(this.state.username.lenth === 0){ alert("please enter your username!") } if (validatePassword && validateEmail && inputIsNotEmpty){ alert('Successfully Sign up! '); event.preventDefault(); const data ={ username: this.state.username, email: this.state.email, password:<PASSWORD>, } axios.post(`http://localhost:5000/api/v1/users/`, data) .then((response) => { localStorage.setItem('username', response.data.user.username) localStorage.setItem('user_id', response.data.user.id) localStorage.setItem('JWT', response.data.access_token) this.setState({login:true}) }) .catch(function (error) { console.log(error); }); } } logInHandler=(event)=>{ const validateEmail = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test(this.state.email) const validatePassword = /^[\<PASSWORD>,}$/.test(this.state.password) const inputIsNotEmpty = this.state.email.length !== 0 && this.state.password.length !== 0 if(validateEmail === false){ alert("please enter valid email address") } if(validatePassword ===false){ alert("password format does not match!") } if(this.state.email.length === 0 ){ alert("please enter your email address!") } if(this.state.password.lenth === 0){ alert("please enter your password!") } if (validatePassword && validateEmail && inputIsNotEmpty){ event.preventDefault(); const data ={ email: this.state.email, password:<PASSWORD>, } axios.post(`http://localhost:5000/api/v1/auth/`, data) .then((response) => { alert('Successfully Log In! '); localStorage.setItem('username', response.data.user.username) localStorage.setItem('user_id', response.data.user.id) localStorage.setItem('JWT', response.data.access_token) this.setState({login: true}) }) .catch(function (error) { console.log(error); }); } } render(){ if(this.state.login ===true){ return <Redirect to="/event"/> }else{ return( <div> <Navbar className="Navbar" light expand="md"> <NavbarBrand href="/"><strong className="NavbarTitle">RUN<strong style={{color:"#F0E68C"}}>a`Z</strong></strong></NavbarBrand> <Nav className="ml-auto" navbar> <NavItem> <NavLink style={{cursor:"pointer"}} onClick={()=>this.setState({showLogIn:!this.state.showLogIn, showSignUp:false})}>Log In</NavLink> </NavItem> <NavItem> <NavLink style={{cursor:"pointer"}} onClick={()=>this.setState({showSignUp:!this.state.showSignUp, showLogIn:false})}>Sign Up</NavLink> </NavItem> </Nav> </Navbar> <div style={{backgroundColor:"#232222", height:"92.9vh"}}> { this.state.showSignUp===true ?<SignUpModal closeSignUpModal={this.closeSignUpModal} nameInputHandler={this.nameInputHandler} emailInputHandler={this.emailInputHandler} passwordInputHandler={this.passwordInputHandler} signUpHandler={this.signUpHandler}></SignUpModal> :null } { this.state.showLogIn===true ?<LogInModal closeLogInModal={this.closeLogInModal} emailInputHandler={this.emailInputHandler} passwordInputHandler={this.passwordInputHandler} logInHandler={this.logInHandler}></LogInModal> :null } </div> </div> ) } } } export default Homepage;<file_sep>/src/Components/AddEventModal/AddEventModal.js import React from "react"; import "./AddEventModal.css" import { Form, FormGroup, Label, Input, Row, Col, Button} from 'reactstrap'; let location=["Kuala Lumpur", "Putrajaya", "Perlis", "Kedah", "Terengganu", "Pahang", "Perak", "Kelantan", "Penang", "Selangor", "Negeri Sembilan", "Johor", "Malacca", ] let category=["5km", "10km", "21km", "42km"] const AddEventModal =(props)=>( <div className="Modal fade-in"> <Form> <FormGroup> <Label tag="h4" for="exampleEmail">Fill In Your Event Information</Label> </FormGroup> <hr></hr> <FormGroup> <Label for="Name">Name</Label> <Input type="text" name="name" placeholder="please enter event name" onChange={props.name} /> </FormGroup> <Row> <Col> <FormGroup> <Label for="File_name">File name</Label> <Input type="text" name="file_name" placeholder="please enter file_name" onChange={props.file_name} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="Location">Location</Label> <Input type="select" name="Location" onChange={props.location} > <option></option> { location.map((o, index)=> { return(<option key={index} value={o}>{o}</option>) } ) } </Input> </FormGroup> </Col> <Col> <FormGroup> <Label for="Category">Category</Label> <Input type="select" name="Category" onChange={props.category} > <option></option> { category.map((o, index)=> { return(<option key={index} value={o}>{o}</option>) } ) } </Input> </FormGroup> </Col> </Row> <FormGroup> <Label for="Rewards">Reward</Label> <Input type="text" name="Rewards" placeholder="please enter event rewards" onChange={props.reward} /> </FormGroup> <Row> <Col> <FormGroup> <Label for="Event Date">Event Date</Label> <Input type="text" name="Event Date" placeholder="DD/MM/YYYY" onChange={props.event_date} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="registration_closes_date">Registration Closes Date</Label> <Input type="text" name="registration closes date" placeholder="DD/MM/YYYY" onChange={props.registration_closes} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="registration_fee">Registration Fee</Label> <Input type="text" name="registration fee" placeholder="RM" onChange={props.registration_fee} /> </FormGroup> </Col> </Row> <FormGroup> <Label for="description">Description</Label> <Input type="textarea" name="description" onChange={props.description} /> </FormGroup> <Button className="btn-success btn-block" onClick={props.addEvent}>Submit</Button> <Button className="btn-danger btn-block" onClick={props.closeAddItem}>Cancel</Button> </Form> </div> ) export default AddEventModal; <file_sep>/src/Components/SignUpModal/SignUpModal.js import React from "react"; import "./SignUpModal.css"; import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap'; const signUpModal=(props)=>( <div className="Modal fade-in"> <Form> <FormGroup> <Label tag="h4" for="exampleEmail">Sign Up</Label> </FormGroup> <br></br> <FormGroup> <Label for="Username">Username</Label> <Input type="name" name="username" placeholder="Enter username" onChange={props.nameInputHandler} /> </FormGroup> <FormGroup> <Label for="Email">Email</Label> <Input type="email" name="email" id="exampleEmail" placeholder="please enter valid email" onChange={props.emailInputHandler} /> <FormText> We'll never share your email with anyone else. </FormText> </FormGroup> <FormGroup> <Label for="Password">Password</Label> <Input type="password" name="password" id="examplePassword" placeholder="Enter password " onChange={props.passwordInputHandler} /> <FormText className="text-muted"> Password must contain more than 8 words </FormText> </FormGroup> <br></br> <Button className="btn-block btn-success" onClick={props.signUpHandler}>Sign Up</Button> <Button className="btn-block btn-danger" onClick={props.closeSignUpModal}>cancel</Button> </Form> </div> ) export default signUpModal;
a89f8e3b265a174b1d22ff53c6b641d1e2c7d23f
[ "JavaScript" ]
5
JavaScript
Seowyongtao/running-event-frontend
7608ea3602c768067588c6a81265d84cbf22390c
3a7ea47988ffaddd8378252fa791edb14bc2131c
refs/heads/master
<file_sep>package main import ( "bytes" "errors" "fmt" "os" "strconv" "strings" _ "github.com/go-sql-driver/mysql" "github.com/urfave/cli/v2" "xorm.io/core" "xorm.io/xorm" "xorm.io/xorm/schemas" ) const ( defaultDSN = "root:123456@tcp(localhost:3306)/test" defaultDriverType = "mysql" ) var ( m *model mt *modelTemplate ) type field struct { Name string Type string Tag string } type model struct { Name string //模型名称 Path string //项目目录 Table string //表名,默认同模型名称 DSN string //数据库连接的dsn配置 DB string //数据库名称 DriverType string //驱动类型,默认mysql } type modelTemplate struct { SnakeName string //模型名称的蛇型法 PackageName string //模型名称的包名 ModelName string //模型名称的驼峰法 Entity string //表的实体结构名称 Table string //表名 TableEntity string //表的结构定义 } func (m *model) getDriverType() string { if m.DriverType == "" { return defaultDriverType } return m.DriverType } func (m *model) getDSN() string { var dsn string if m.DSN != "" { dsn = m.DSN } else { dsn = os.Getenv("SNOW_DSN") } if dsn == "" { dsn = defaultDSN } if m.DB != "" { arr := strings.SplitN(dsn, "/", 2) if len(arr) < 2 { arr = append(arr, m.DB) } else { arr[1] = m.DB } dsn = strings.Join(arr, "/") } return dsn } func init() { m = new(model) mt = new(modelTemplate) } //new model func runModel(ctx *cli.Context) (err error) { if ctx.Args().Len() == 0 { return errors.New("required model name") } m.Name = ctx.Args().First() if m.Name == "" { return errors.New("model name is empty") } if m.Table == "" { m.Table = m.Name } if m.Path == "" { m.Path, _ = os.Getwd() } else { if !isDirExist(m.Path) { return errors.New("project directory is not exist") } } snakeMapper := new(core.SnakeMapper) mt.SnakeName = snakeMapper.Obj2Table(m.Name) mt.PackageName = packageCase(mt.SnakeName) + "model" mt.Entity = snakeMapper.Table2Obj(mt.SnakeName) mt.ModelName = snakeMapper.Table2Obj(mt.SnakeName) + "Model" mt.Table = m.Table //create model directory path := strings.Join([]string{m.Path, "app/models", mt.PackageName}, string(os.PathSeparator)) if err = os.MkdirAll(path, 0755); err != nil { return } //dsn dsn := m.getDSN() if dsn == "" { return errors.New("dsn is empty") } //连接数据库 engine, err := xorm.NewEngine(m.getDriverType(), dsn) if err != nil { return } //获取数据库表定义 tables, err := engine.DBMetas() if err != nil { return } //获取表结构定义 var ok bool for _, table := range tables { if table.Name != mt.Table { continue } ok = true mt.TableEntity = genTableEntity(table) break } if !ok { return errors.New("cannot find related table") } //将模板写入文件 file := path + string(os.PathSeparator) + mt.SnakeName + ".go" err = write(file, tplModel, mt) if err != nil { return } //输出提示信息 fmt.Printf("Table: %s\n", mt.Table) fmt.Printf("Entity: %s\n", mt.Entity) fmt.Printf("Model Name: %s\n", mt.ModelName) fmt.Printf("Package Name: %s\n", mt.PackageName) fmt.Printf("Directory: %s\n\n", path) fmt.Println("The model has been created.") return nil } //将蛇形命名法转换为go包名连写命名法 func packageCase(name string) string { name = strings.ToLower(name) rs := []rune(name) var buffer bytes.Buffer var s string for _, v := range rs { s = string(v) if s == "_" { continue } buffer.WriteString(s) } return buffer.String() } //目录是否存在 func isDirExist(path string) bool { fi, e := os.Stat(path) if e != nil { return false } return fi.IsDir() } //将数据库table的定义转换为数据结构实体定义 func genTableEntity(table *schemas.Table) string { columns := table.Columns() snakeMapper := new(core.SnakeMapper) RowInfoList := make([]*field, 0) for _, column := range columns { sqlType := column.SQLType rowInfo := &field{ // 变量名 Name: snakeMapper.Table2Obj(column.Name), } // 变量类型 if sqlType.Name == core.DateTime { rowInfo.Type = "time.Time" } else if sqlType.Name == core.TimeStamp { rowInfo.Type = "time.Time" } else { rowInfo.Type = schemas.SQLType2Type(sqlType).Name() } // xorm注释 tag := "`xorm:\"'" + column.Name + "'" if sqlType.Name == core.DateTime { tag += " datetime" } else if sqlType.Name == core.TimeStamp { tag += " timestamp" } else if sqlType.Name == core.BigInt { tag += " bigint(" + strconv.Itoa(sqlType.DefaultLength) + ")" } else if sqlType.Name == core.Int { tag += " int(" + strconv.Itoa(sqlType.DefaultLength) + ")" } else if sqlType.Name == core.Decimal { tag += " decimal(" + strconv.Itoa(sqlType.DefaultLength) + "," + strconv.Itoa(sqlType.DefaultLength2) + ")" } else if sqlType.Name == core.Varchar { tag += " varchar(" + strconv.Itoa(sqlType.DefaultLength) + ")" } else if sqlType.Name == core.Char { tag += " char(" + strconv.Itoa(sqlType.DefaultLength) + ")" } else { tag += " " + sqlType.Name } //特殊字段加点盐 if column.Name == "id" { tag += " pk autoincr" } else if column.Name == "deleted_at" { tag += " deleted" } tag += "\"`" rowInfo.Tag = tag RowInfoList = append(RowInfoList, rowInfo) } maxVarNameStrLen := 0 maxVarTypeStrLen := 0 for _, field := range RowInfoList { if len(field.Name) > maxVarNameStrLen { maxVarNameStrLen = len(field.Name) } if len(field.Type) > maxVarTypeStrLen { maxVarTypeStrLen = len(field.Type) } } maxVarNameStrLen += 1 maxVarTypeStrLen += 1 // 生成文件内容 structText := "type " + mt.Entity + " struct {\n" for _, field := range RowInfoList { structText += "\t" structText += field.Name if len(field.Name) < maxVarNameStrLen { padSpanTotal := maxVarNameStrLen - len(field.Name) for index := 0; index < padSpanTotal; index++ { structText += " " } } structText += field.Type if len(field.Type) < maxVarTypeStrLen { padSpanTotal := maxVarTypeStrLen - len(field.Type) for index := 0; index < padSpanTotal; index++ { structText += " " } } structText += field.Tag structText += "\n" } structText += `}` return structText } <file_sep>package main import "time" var toolIndexs = []*Tool{ { Name: "snow", Alias: "snow", BuildTime: time.Date(2019, 7, 19, 0, 0, 0, 0, time.Local), Install: "go install github.com/qit-team/snow/tool/snow@latest", Summary: "snow工具集本体", Platform: []string{"darwin", "linux", "windows"}, Author: "snow", }, } <file_sep>module github.com/qit-team/snow go 1.12 require ( github.com/BurntSushi/toml v0.4.1 github.com/SkyAPM/go2sky v0.6.0 github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/fatih/color v1.13.0 github.com/gin-gonic/gin v1.7.7 github.com/go-openapi/jsonreference v0.19.6 // indirect github.com/go-openapi/swag v0.19.15 // indirect github.com/go-resty/resty/v2 v2.7.0 github.com/go-sql-driver/mysql v1.6.0 github.com/mailru/easyjson v0.7.7 // indirect github.com/prometheus/client_golang v1.11.0 github.com/qit-team/snow-core v0.1.28 github.com/qit-team/work v0.3.11 github.com/robfig/cron v1.2.0 github.com/swaggo/gin-swagger v1.3.3 github.com/swaggo/swag v1.7.6 github.com/urfave/cli/v2 v2.3.0 gopkg.in/go-playground/validator.v9 v9.31.0 xorm.io/core v0.7.3 xorm.io/xorm v1.2.5 )<file_sep>package main const ( _tplReadme = `## Snow Snow是一套简单易用的Go语言业务框架,整体逻辑设计简洁,支持HTTP服务、队列调度和任务调度等常用业务场景模式。 ## Quick start ### Build sh build/shell/build.sh ### Run ` + "```" + `shell 1. build/bin/snow -a api #启动Api服务 2. build/bin/snow -a cron #启动Cron定时任务服务 3. build/bin/snow -a job #启动队列调度服务 4. build/bin/snow -a command -m test #执行名称为test的脚本任务 ` + "```" + ` ## Documents - [项目地址](https://github.com/qit-team/snow) - [中文文档](https://github.com/qit-team/snow/wiki) - [changelog](https://github.com/qit-team/snow/blob/master/CHANGLOG.md) - [xorm](http://gobook.io/read/github.com/go-xorm/manual-zh-CN/) ` _tplGitignore = `/.idea /vendor /.env !/.env.example ` _tplGoMod = `module {{.ModuleName}} go 1.12 require ( github.com/BurntSushi/toml v0.4.1 github.com/SkyAPM/go2sky v0.6.0 github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/fatih/color v1.13.0 github.com/gin-gonic/gin v1.7.7 github.com/go-openapi/jsonreference v0.19.6 // indirect github.com/go-openapi/swag v0.19.15 // indirect github.com/go-resty/resty/v2 v2.7.0 github.com/go-sql-driver/mysql v1.6.0 github.com/mailru/easyjson v0.7.7 // indirect github.com/prometheus/client_golang v1.11.0 github.com/qit-team/snow-core v0.1.28 github.com/qit-team/work v0.3.11 github.com/robfig/cron v1.2.0 github.com/swaggo/gin-swagger v1.3.3 github.com/swaggo/swag v1.7.6 github.com/urfave/cli/v2 v2.3.0 gopkg.in/go-playground/validator.v9 v9.31.0 xorm.io/core v0.7.3 xorm.io/xorm v1.2.5 ) ` _tplMain = `package main import ( "errors" "fmt" "os" "{{.ModuleName}}/app/console" "{{.ModuleName}}/app/http/routes" "{{.ModuleName}}/app/jobs" "{{.ModuleName}}/bootstrap" "{{.ModuleName}}/config" _ "{{.ModuleName}}/docs" _ "github.com/go-sql-driver/mysql" _ "github.com/qit-team/snow-core/cache/rediscache" "github.com/qit-team/snow-core/kernel/server" _ "github.com/qit-team/snow-core/queue/redisqueue" ) // @title Swagger Example API // @version 1.0 // @description This is a sample server celler server. // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email <EMAIL> // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:8080 // @BasePath / // @securityDefinitions.basic BasicAuth // @securityDefinitions.apikey ApiKeyAuth // @in header // @name Authorization // @securitydefinitions.oauth2.application OAuth2Application // @tokenUrl https://example.com/oauth/token // @scope.write Grants write access // @scope.admin Grants read and write access to administrative information // @securitydefinitions.oauth2.implicit OAuth2Implicit // @authorizationUrl https://example.com/oauth/authorize // @scope.write Grants write access // @scope.admin Grants read and write access to administrative information // @securitydefinitions.oauth2.password <PASSWORD> // @tokenUrl https://example.com/oauth/token // @scope.read Grants read access // @scope.write Grants write access // @scope.admin Grants read and write access to administrative information // @securitydefinitions.oauth2.accessCode OAuth2AccessCode // @tokenUrl https://example.com/oauth/token // @authorizationUrl https://example.com/oauth/authorize // @scope.admin Grants read and write access to administrative information func main() { //解析启动命令 opts := config.GetOptions() if opts.ShowVersion { fmt.Printf("%s\ncommit %s\nbuilt on %s\n", server.Version, server.BuildCommit, server.BuildDate) os.Exit(0) } handleCmd(opts) err := startServer(opts) if err != nil { fmt.Printf("server start error, %s\n", err) os.Exit(1) } } //执行(status|stop|restart)命令 func handleCmd(opts *config.Options) { if opts.Cmd != "" { pidFile := opts.GenPidFile() err := server.HandleUserCmd(opts.Cmd, pidFile) if err != nil { fmt.Printf("Handle user command(%s) error, %s\n", opts.Cmd, err) } else { fmt.Printf("Handle user command(%s) succ \n ", opts.Cmd) } os.Exit(0) } } func startServer(opts *config.Options) (err error) { //加载配置 conf, err := config.Load(opts.ConfFile) if err != nil { return } //引导程序 err = bootstrap.Bootstrap(conf) if err != nil { return } pidFile := opts.GenPidFile() //根据启动命令行参数,决定启动哪种服务模式 switch opts.App { case "api": err = server.StartHttp(pidFile, conf.Api, routes.RegisterRoute) case "cron": err = server.StartConsole(pidFile, console.RegisterSchedule) case "job": err = server.StartJob(pidFile, jobs.RegisterWorker) case "command": err = server.ExecuteCommand(opts.Command, console.RegisterCommand) default: err = errors.New("no server start") } return } ` _tplEnv = `# toml配置文件 # Wiki:https://github.com/toml-lang/toml ServiceName = "snow" Debug = true Env = "local" # local-本地 develop-开发 beta-预发布 production-线上 PrometheusCollectEnable = true SkyWalkingOapServer = "127.0.0.1:11800" [Log] Handler = "file" Dir = "./logs" Level = "info" [Db] Driver = "mysql" [Db.Option] MaxConns = 128 MaxIdle = 32 IdleTimeout = 180 # second Charset = "utf8mb4" ConnectTimeout = 3 # second [Db.Master] Host = "127.0.0.1" Port = 3306 User = "root" Password = "<PASSWORD>" DBName = "test" [[Db.Slaves]] # 支持多个从库 Host = "127.0.0.1" Port = 3306 User = "root" Password = "<PASSWORD>" DBName = "test" [Api] Host = "0.0.0.0" Port = 8080 [Cache] Driver = "redis" [Redis.Master] Host = "127.0.0.1" Port = 6379 #Password = "" #DB = 0 #[Redis.Option] #MaxIdle = 64 #MaxConns = 256 #IdleTimeout = 180 # second #ConnectTimeout = 1 #ReadTimeout = 1 #WriteTimeout = 1 [AliMns] Url = "" AccessKeyId = "" AccessKeySecret = "" ` _tplLog = `* !.gitignore ` ) <file_sep>package main import ( "errors" "fmt" "github.com/urfave/cli/v2" "os" ) var ( d *docs ) type docs struct { Path string //项目目录 } func init() { d = new(docs) } // generate swag doc func runDoc(ctx *cli.Context) (err error) { if d.Path == "" { d.Path, _ = os.Getwd() } else { if !isDirExist(d.Path) { return errors.New("project directory is not exist") } } err = runSwagInit(d.Path) if err == nil { fmt.Println("snow generate doc success!") } else { fmt.Println("snow generate doc error:", err) } return err } <file_sep>package main import ( "fmt" "github.com/urfave/cli/v2" "os" ) func main() { app := cli.NewApp() app.Name = "snow" app.Usage = "snow工具集" app.Version = Version app.Commands = cli.Commands{ { Name: "new", Aliases: []string{"n"}, Usage: "create new project", Flags: []cli.Flag{ &cli.StringFlag{ Name: "path, p", Value: "", Usage: "directory for create project, default: current position", Destination: &p.Path, }, &cli.StringFlag{ Name: "module, m", Usage: "project module name, for go mod init", Destination: &p.ModuleName, }, }, Action: runNew, }, { Name: "model", Aliases: []string{"m"}, Usage: "create new model", Flags: []cli.Flag{ &cli.StringFlag{ Name: "path, p", Value: "", Usage: "project directory, default: current position", Destination: &m.Path, }, &cli.StringFlag{ Name: "table, t", Value: "", Usage: "table name for new model, default: model name", Destination: &m.Table, }, &cli.StringFlag{ Name: "dsn, d", Value: "", Usage: "database dsn config, default: GetEnv('SNOW_DSN') or 'root:123456@tcp(localhost:3306)/test'", Destination: &m.DSN, }, &cli.StringFlag{ Name: "db, b", Value: "", Usage: "database name, will replace dsn's database", Destination: &m.DB, }, &cli.StringFlag{ Name: "driver, r", Value: "", Usage: "driver type, default: mysql", Destination: &m.DB, }, }, Action: runModel, }, { Name: "version", Aliases: []string{"v"}, Usage: "snow version", Action: func(c *cli.Context) error { fmt.Println(getVersion()) return nil }, }, { Name: "upgrade", Usage: "snow self-upgrade", Action: upgradeAction, }, { Name: "doc", Aliases: []string{"d"}, Usage: "generate doc", Flags: []cli.Flag{ &cli.StringFlag{ Name: "path, p", Value: "", Usage: "project directory, default: current position", Destination: &d.Path, }, }, Action: runDoc, }, } err := app.Run(os.Args) if err != nil { panic(err) } }
8cb7e96eefbd20b7b61d05dd936243eb06eb1110
[ "Go Module", "Go" ]
6
Go
52lemon/snow
5222ad8231a375fbc82060b1a3b2b0a7d55035f5
d23f4fb42c84393fcd94ea080388911feaf7bd6d
refs/heads/master
<file_sep>import datetime def DiaSemana (aa, mm, dd): x = datetime.date (aa, mm, dd) return (x.weekday()) arq = open('produtos.txt', 'r') S = arq.readlines() x = 0 Codigo = [] Unidade = [] Estoque = [] Custo = [] Margem = [] P = [] while len(S) > x: L = S[x].split(';') Cod = int (L[0]) Unid = str (L[1]) Estoq = float (L[2]) Cust = float (L[3]) Marg = float (L[4]) Codigo.append (Cod) Unidade.append (Unid) Estoque.append (Estoq) Custo.append (Cust) Margem.append (Marg) x = x + 1 print ("") x = 0 while x == 0: Mes = int(input("Selecione o mês desejado (1 a 12): ")) print ("") if Mes >12 or Mes <= 0: print ("*************************Valor inválido, tente novamente*************************") print (" O mês deve estar no intervalo de 1 a 12 - Por favor digite novamente") print ("") else: if Mes == 1: NomeMes = "Janeiro" elif Mes == 2: NomeMes = "Fevereiro" elif Mes == 3: NomeMes = "Março" elif Mes == 4: NomeMes = "Abril" elif Mes == 5: NomeMes = "Maio" elif Mes == 6: NomeMes = "Junho" elif Mes == 7: NomeMes = "Julho" elif Mes == 8: NomeMes = "Agosto" elif Mes == 9: NomeMes = "Setembro" elif Mes == 10: NomeMes = "Outubro" elif Mes == 11: NomeMes = "Novembro" else: NomeMes = "Dezembro" print (" O mês Escolhido foi: %s" % NomeMes) print ("") x = 1 while x == 1: Ano = int(input("Selecione o ano desejado com 4 digitos (a partir de 2015): ")) print ("") if Ano != 2015 and Ano != 2016 and Ano != 2017 : print ("*************************Valor inválido, tente novamente*************************") print (" O ano deve estar no formato 20xx e ser de 2015 a 2017") print ("") else: x = 2 QtdeVendasDia = 0 while QtdeVendasDia <= 0: QtdeVendasDia = int(input("Digite a média de vendas por dia no mês de %s de %d: " % (NomeMes, Ano))) print("") if QtdeVendasDia <= 0: print ("*************************Valor inválido, tente novamente*************************") print (" A quantidade de vendas por dia deve ser maior que 0!") print ("") else: if Mes == 1 or Mes == 3 or Mes == 5 or Mes == 7 or Mes == 8 or Mes == 10 or Mes == 12: NDiasMes = 31 elif Mes == 4 or Mes == 6 or Mes == 9 or Mes == 11: NDiasMes = 30 else: NDiasMes = 28 Dia = 1 NDiasVenda = 0 while Dia <= NDiasMes: a = DiaSemana (Ano, Mes, Dia) if a != 6: NDiasVenda = NDiasVenda + 1 Dia = Dia + 1 QtdeVendidaMes = QtdeVendasDia * NDiasVenda arquivo = open ('RelVendas.txt', 'w') from random import randint cont = 1 Dia = 1 while cont <= QtdeVendidaMes: r = randint (0,14) Cod = Codigo[r] Estoq = Estoque[r] PrecoVenda = Custo[r]*Margem[r] texto1 = ("{Ano};".format(Ano=Ano)) texto2 = ("{Mes:02d};".format(Mes=Mes)) texto3 = ("{Dia:02d};".format(Dia=Dia)) texto4 = ("{Cod};".format(Cod=Cod)) texto5 = ("{Estoq};".format(Estoq=Estoq)) texto6 = ("{PrecoVenda:.2f};".format(PrecoVenda=PrecoVenda)) arquivo.write(texto1) arquivo.write(texto2) arquivo.write(texto3) arquivo.write(texto4) arquivo.write(texto5) arquivo.write(texto6) if (QtdeVendidaMes - cont) > 0: arquivo.write("\n") if (cont % QtdeVendasDia) == 0: Dia = Dia + 1 if a == 6: Dia = Dia + 1 cont = cont + 1 arquivo.close()
0c96d5f8b7636d7d7a9f657b38892bb72290ae13
[ "Python" ]
1
Python
RenanGuedesDePinho/Projeto-com-dados-para-controle-de-vendas
1e0a1e021a4e699dc7facdbb8576d2a8322136bf
8de8298e8e6ddc7de0193ef672c315d2c5b50e4b
refs/heads/master
<file_sep>package utils import ( "encoding/json" "fmt" "net/http" ) func ResponseJson(w http.ResponseWriter, p interface{}) { ubahkeByte, err := json.Marshal(p) if err!=nil { http.Error(w,err.Error(), http.StatusInternalServerError) return } w.Header().Set(`content-type`,`application/json`) w.WriteHeader(200) w.Write(ubahkeByte) } func IsError(w http.ResponseWriter, err error) bool { if err != nil { http.Error(w,err.Error(), http.StatusInternalServerError) fmt.Println(err) return true } return false } <file_sep>package config import ( "database/sql" "fmt" _ `github.com/go-sql-driver/mysql` ) const ( username = `user1` password = `<PASSWORD>` database = `db_apigo` ) var dsn = fmt.Sprintf(`%s:%s@/%s`,username,password,database) func Mysql() (db *sql.DB,err error) { db, err = sql.Open(`mysql`,dsn) if err != nil { fmt.Println(err) } return } <file_sep>package main import ( "be3gomy/config" "be3gomy/mahasiswa" "be3gomy/model" "be3gomy/utils" "database/sql" "encoding/json" "fmt" "log" "net/http" ) const addr = `:7000` type Server struct { db *sql.DB ViewDir string } type handler func(w http.ResponseWriter, r *http.Request) func InitServer() *Server { db, err := config.Mysql() if err != nil { log.Fatal(err) } return &Server{ db: db, ViewDir: `views/`, } } func (s *Server) Listen() { log.Println(`listen at `+addr) http.HandleFunc(`/mahasiswa`, s.Mahasiswa()) http.HandleFunc(`/mahasiswa/create`,s.MahasiswaCreate()) http.HandleFunc(`/mahasiswa/update`,s.MahasiswaUpdate()) http.HandleFunc(`/mahasiswa/delete`,s.MahasiswaDelete()) err := http.ListenAndServe(addr,nil) if err != nil { fmt.Println(err) } } func (s *Server) Mahasiswa() handler { return func(w http.ResponseWriter, r *http.Request) { mahasiswas, err := mahasiswa.SelectAll(s.db) if utils.IsError(w,err) { return } utils.ResponseJson(w, mahasiswas) } } func (s *Server) MahasiswaCreate() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == `GET` { http.ServeFile(w,r,s.ViewDir+`mahasiswa_create.html`) return } m := model.Mahasiswa{} err := json.NewDecoder(r.Body).Decode(&m) if utils.IsError(w,err) { return } err = mahasiswa.Insert(s.db,&m) if utils.IsError(w,err) { return } utils.ResponseJson(w, m) } } func (s *Server) MahasiswaUpdate() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == `GET` { http.ServeFile(w,r,s.ViewDir+`mahasiswa_update.html`) return } m := model.Mahasiswa{} err := json.NewDecoder(r.Body).Decode(&m) if utils.IsError(w,err) { return } affected, err := mahasiswa.Update(s.db,&m) if utils.IsError(w,err) { return } res := map[string]interface{}{} res[`affected`] = affected utils.ResponseJson(w, res) } } func (s *Server) MahasiswaDelete() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == `GET` { http.ServeFile(w,r,s.ViewDir+`mahasiswa_delete.html`) return } m := model.Mahasiswa{} err := json.NewDecoder(r.Body).Decode(&m) if utils.IsError(w,err) { return } ok, err := mahasiswa.Delete(s.db,&m) if utils.IsError(w,err) { return } res := map[string]interface{}{} res[`deletedRecord`] = m res[`berhasil`] = ok utils.ResponseJson(w, res) } } func main() { server := InitServer() server.Listen() } <file_sep>CREATE DATABASE db_apigo; CREATE USER `user1`@`localhost` IDENTIFIED BY '1234567890'; USE db_apigo; GRANT ALL PRIVILEGES ON db_apigo.* TO `user1`@`localhost`; FLUSH PRIVILEGES; CREATE TABLE `mahasiswa` ( `id` INT AUTO_INCREMENT NOT NULL PRIMARY KEY, `nim` INT NOT NULL, `name` VARCHAR(64) NOT NULL, `semester` SMALLINT NOT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL ); -- https://pastebin.com/dNaT8fHG <file_sep>package model import "time" type Mahasiswa struct { ID int `json:"id"` NIM int `json:"nim"` Name string `name:"name"` Semester int `json:"semester"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } <file_sep>package mahasiswa import ( "be3gomy/model" "database/sql" "fmt" "time" ) const table = `mahasiswa` const dateformat = `2006-01-02 15:04:05` func SelectAll(db *sql.DB) (mahasiswas []model.Mahasiswa,err error) { sql := fmt.Sprintf(`SELECT * FROM %s ORDER BY id DESC`, table) rows, err := db.Query(sql) if err != nil { return nil, err } defer rows.Close() mahasiswas = []model.Mahasiswa{} for rows.Next() { m := model.Mahasiswa{} createdAt, updatedAt := ``, `` err = rows.Scan(&m.ID, &m.NIM, &m.Name, &m.Semester, &createdAt, &updatedAt) m.CreatedAt, _ = time.Parse(dateformat,createdAt) m.UpdatedAt, _ = time.Parse(dateformat,updatedAt) if err !=nil { return nil, err } mahasiswas = append(mahasiswas, m) } return } func Insert(db *sql.DB, m *model.Mahasiswa) (err error) { sql := fmt.Sprintf(`INSERT INTO %v (nim, name, semester, created_at, updated_at) VALUES(?,?,?,?,?)`, table) now := time.Now() res, err := db.Exec(sql,m.NIM,m.Name,m.Semester,now,now) if err != nil { return err } lastId, err := res.LastInsertId() if err != nil { return err } m.ID = int(lastId) m.CreatedAt = now m.UpdatedAt = now return } func Update(db *sql.DB, m *model.Mahasiswa) (aff int64, err error) { sql := fmt.Sprintf(`UPDATE %v SET name=?, nim=?, semester=?, updated_at=? WHERE id =?`, table) now := time.Now() res, err := db.Exec(sql,m.Name,m.NIM,m.Semester,now,m.ID) if err != nil { return 0,err } ra, err := res.RowsAffected() if err != nil { return 0, err } aff = ra return } func Delete(db *sql.DB, m *model.Mahasiswa) (ok bool, err error) { sql := fmt.Sprintf(`SELECT * FROM %v WHERE id = ? `, table) rows, err := db.Query(sql, m.ID) if err != nil { return false, err } defer rows.Close() if rows.Next() { createdAt, updatedAt := ``, `` err = rows.Scan(&m.ID, &m.NIM, &m.Name, &m.Semester, &createdAt, &updatedAt) m.CreatedAt, _ = time.Parse(dateformat,createdAt) m.UpdatedAt, _ = time.Parse(dateformat,updatedAt) if err !=nil { return false, err } // really delete sql = fmt.Sprintf(`DELETE FROM %v WHERE id = ?`,table) res, err := db.Exec(sql,m.ID) if err != nil { return false, err } n, err := res.RowsAffected() return n > 0, err } return false, err } <file_sep># be3gomy Latihan untuk kelas Backend 03, Go plain, MySQL plain, no framework
31db244e837df7666fbb8c6de282e27038c0b04f
[ "Markdown", "SQL", "Go" ]
7
Go
kokizzu/be3gomy
534a032dd008888c7d36161b1c7ed4e08c4575b0
9cc9741bcb3e74aae69a789fddf098824fa2d307
refs/heads/master
<file_sep>// Made by <NAME> #pragma once #include "CoreMinimal.h" #include "SimpleShooterGameModeBase.h" #include "KillEmAllGameMode.generated.h" /** * */ UCLASS() class SIMPLESHOOTER_API AKillEmAllGameMode : public ASimpleShooterGameModeBase { GENERATED_BODY() public: virtual void PawnKilled(APawn* PawnKilled) override; private: void EndGame(bool bPlayerWon); }; <file_sep>// Made by <NAME> #include "ShooterAIController.h" #include "Characters/ShooterCharacter.h" #include "Kismet/GameplayStatics.h" #include "BehaviorTree/BlackboardComponent.h" bool AShooterAIController::IsDead() const { AShooterCharacter* ControlledCharacter = Cast<AShooterCharacter>(GetPawn()); if (ControlledCharacter) { return ControlledCharacter->IsDead(); } return true; } void AShooterAIController::BeginPlay() { Super::BeginPlay(); if (AIBehavior) { RunBehaviorTree(AIBehavior); GetBlackboardComponent()->SetValueAsVector(TEXT("StartLocation"), GetPawn()->GetActorLocation()); } } void AShooterAIController::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
84d91624095e8b6e7d2df680940be906075a9c24
[ "C++" ]
2
C++
alexjobe/ue4-shooter
1e38aaeac8fa17649439ce3f2ad6dc203f058df0
9d9cddd3bffda15d10d38d036fa9cc3e231edd9f
refs/heads/master
<repo_name>HimanshiChauhan/Job-Scrapper<file_sep>/README.md # Job-Scrapper It is a standalone application that access and extact information of various types of jobs from different websites. The extracted details are then stored in a CSV file through which the Job Scrapper allow its users to search and query the saved findings. <file_sep>/timesjob_code.py from tkinter import * from bs4 import BeautifulSoup from ShowResult import ShowResult import tkinter as tk from tkinter import messagebox import requests import csv class times_job: def __init__(self,url): self.url=url #print(soup.prettify()) def retrive_jobs(self): rows=[] rows.append(["Job Title","Organization","Posted","Description","Location"]) page = requests.get(self.url) soup = BeautifulSoup(page.content, 'html.parser') all_jobs = soup.find_all('li', class_='clearfix job-bx wht-shd-bx') i=0 print("length of all_jobs : "+ str(len(all_jobs))) for job in all_jobs: row=[] i=i+1 job_title = "" job_loc = "" job_org = "" job_posted = "" job_desc = "" if(i==5):break t = job.find('header',class_='clearfix') if t is not None: job_title = t.find('a').getText().strip() t = job.find('ul',class_='list-job-dtl clearfix') if t is not None: job_desc = t.find('li').getText().strip() job_desc = job_desc.replace('\n', ' ') job_desc = job_desc.replace('\t', ' ') job_desc = job_desc.replace('\r', ' ') job_desc = job_desc.replace('"', ' ') job_desc = job_desc.strip() loc = job_desc.find("Job Description:") if(loc!=-1): job_desc = job_desc[loc+len("Job Description:"):] t = job.find('ul',class_='top-jd-dtl clearfix') if t is not None: job_loc = t.find('span').getText().strip() t = job.find('h3',class_='joblist-comp-name') if t is not None: job_org = t.getText().strip() t = job.find('span',class_='sim-posted') if t is not None: job_posted = t.find('span').getText().strip() row.append(job_title) row.append(job_org) row.append(job_posted) row.append(job_desc) row.append(job_loc) rows.append(row) print("******************************** " , i," ********************************") print("\n",job_title) print("**********************************************************************") print("\n\t Location: ",job_loc) print("\n\t Posted: ",job_posted) print("\n\t Org: ",job_org) print("\n\t Description: ",job_desc) if (len(rows)-1)>0: #store in csv file csv.register_dialect('myDialect', delimiter = ',') with open('scrapResult.csv', 'w') as f: writer = csv.writer(f, dialect='myDialect') writer.writerows(rows) f.close() root=Tk() s = ShowResult(root,"scrapResult.csv",self.url) s.mainloop() else: tk.messagebox.showinfo("Job Scrapper","No matching jobs found") if __name__ == '__main__': a=times_job("https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearch&from=submit&txtKeywords=Software+Developer&txtLocation=Cochin%2F+Kochi%2F+Ernakulam") a.retrive_jobs() <file_sep>/GovtJobs.py from tkinter import * from tkinter import ttk from tkinter import messagebox from govt_indeed_code import Indeed class GovtJobs(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("Job Scrapper [Government Jobs]") img=PhotoImage(file="image\Logo.gif") lblLogo = Label(self.master, image=img, bg='white') lblLogo.image=img lblLogo.grid(row=0, column=0,columnspan=4,sticky=E+W) lbl = Label(self.master, text=' ......a python scrapper', bg='orange', fg='blue', borderwidth = 0,font=3) lbl.grid(row=1, column=0, columnspan=4 ,sticky=E+W) l1=Label(self.master,text="Title",bg="white",padx='2',pady='4', font = 5) l1.grid(row=2,column=0,columnspan=2) self.d1=ttk.Combobox(self.master,state="readonly",values=["Railway","Bank","Teacher","Police"], font = 5) self.d1.current(0) self.d1.grid(row=2,column=2,columnspan=2) b2=Button(self.master,text="Find Jobs",command=self.find_job,padx=2,pady=5, fg= 'dark blue', width=10, borderwidth = 1,font=5, activebackground='grey', activeforeground='white') b2.grid(row=5,column=3) self.master.grid_rowconfigure(5,weight=5) lblFooter1 = Label(self.master, text='Why JobScrapper for government jobs ....', bg='orange', fg='blue',width=50, borderwidth = 0,font=3) lblFooter1.grid(row=6, column=0, columnspan=4 ,sticky=E+W) msg = "Opportunities in Central Government Jobs, State Government Jobs, Public Sector Companies, Public Sector Banks, Indian Railway, Army, Navy, Air Force and Government organizing Institutions, Organizations and Universities. Everyday 24X7, Job scrapper updating Free Govt Jobs Alert of Centraland State Govt Vacancies and Public Sector Jobs for all type of Job Seekers. \n\n Job Scrapper every day updating the Latest Govt Jobs, Govt Recruitment Vacancies in this application. 8th Pass, 10th Pass, 12th Pass, ITI, Diploma, MA, M.Com, MSW, MBA, MCA, ME, M.Tech etc.) and all other educational qualified Indian Citizens find your Qualification/ Eligibility wise Latest Govt Jobs 2019-20 and Upcoming Government Jobs 2019 Notifications listed in this applicatoin." lblFooter = Label(self.master, text=msg, bg='green', fg='white',width=50, borderwidth = 7,font=3,padx="0",wraplength=450 ) lblFooter.grid(row=7, column=0, columnspan=4 ,sticky=E+W) def find_job(self): title = self.d1.current() tA0 = 'https://www.indeed.co.in/jobs?q=railway&l=' tB0 = 'https://www.indeed.co.in/jobs?q=Government+Bank&l=' tC0 = 'https://www.indeed.co.in/jobs?q=government+teacher&l=' tD0 = 'https://www.indeed.co.in/jobs?q=government+police&l=' govtindeedjobs=[tA0,tB0,tC0,tD0] url = govtindeedjobs[title] a=Indeed(url) a.retrive_jobs() <file_sep>/JobScrapper.py import tkinter as tk from tkinter import ttk from tkinter import messagebox from PrivateJobs import PrivateJobs from GovtJobs import GovtJobs def scrapp(): top=tk.Toplevel() top["bg"] = "white" p = PrivateJobs(top) p.mainloop() def scrapg(): top=tk.Toplevel() top["bg"] = "white" g = GovtJobs(top) g.mainloop() def aboutus(): tk.messagebox.showinfo("About Us","Prepared By: <NAME>") def quit(): top.destroy() top = tk.Tk() top.title("Job Scrapper") top["bg"] = "white" img1 = tk.PhotoImage(file='image\Logo.gif') img = tk.PhotoImage(file='image\Benefits.gif') lblLogo = tk.Label(top, image=img1, bg='white') lblLogo.grid(row=0, column=0,columnspan=4,sticky=tk.E+tk.W) lbl = tk.Label(top, text=' ......a python scrapper', bg='orange', fg='blue', borderwidth = 0,font=3) lbl.grid(row=1, column=0, columnspan=4 ,sticky=tk.E+tk.W) btnPrivate = tk.Button(top, text='Private Jobs', command = scrapp, fg= 'dark blue', width=10, borderwidth = 1,font=10, activebackground='grey', activeforeground='white') btnPrivate.grid(row=2, column=0,sticky=tk.E+tk.W) btnGovt = tk.Button(top, text='Govt Jobs', command = scrapg, fg= 'dark blue', width=10, borderwidth = 1,font=10, activebackground='grey', activeforeground='white') btnGovt.grid(row=2, column=1,sticky=tk.E+tk.W) btnAboutUs = tk.Button(top, text='About Us', command = aboutus, fg= 'dark blue', width=10, borderwidth = 1,font=10, activebackground='grey', activeforeground='white') btnAboutUs.grid(row=2, column=2,sticky=tk.E+tk.W) btnQuit = tk.Button(top, text='Quit', command = quit, fg= 'dark blue', width=10, borderwidth = 1,font=10, activebackground='grey', activeforeground='white') btnQuit.grid(row=2, column=3,sticky=tk.E+tk.W) lblimg = tk.Label(top, image=img, bg='white') lblimg.grid(row=3, column=0,columnspan=4) lblFooter1 = tk.Label(top, text='About Web Scrapping...... concept used in Job Scrapper', bg='orange', fg='blue',width=50, borderwidth = 0,font=3) lblFooter1.grid(row=4, column=0, columnspan=4 ,sticky=tk.E+tk.W) msg = "Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites.Web scrapping is the process of automatically mining data or collecting information from the World wide Web. \n\nIt is the field of active developments sharing a common goal with the semantic web vision, an ambitious initiative that still requires breakthroughs in text processing, semantic understanding, artificial intelligence and human-computer interactions." lblFooter = tk.Label(top, text=msg, bg='green', fg='white',width=50, borderwidth = 7,font=3,padx="0",wraplength=450 ) lblFooter.grid(row=5, column=0, columnspan=4 ,sticky=tk.E+tk.W) top.mainloop()
304c9acb2e7271abc1dc0b592dcb6cc4db2661ca
[ "Markdown", "Python" ]
4
Markdown
HimanshiChauhan/Job-Scrapper
dddcd49ec35a5e7d1dc0af07aa16089072fb0460
2b2b13450ac83e40a3e5945b6ba9b6c371ee9ed8
refs/heads/master
<file_sep>package ia.practica; public class Prueba { public static void main(String[] args) { // Estaciones int id = 0; //Linea 1 Estacion Talleres = new Estacion(id++, "Talleres", true, 25.754006, -100.365281, new int[] {1}); Estacion SBernabe = new Estacion(id++, "<NAME>", true, 25.748407, -100.361720, new int[] {1}); Estacion UModelo = new Estacion(id++, "Unidad Modelo", true, 25.741914, -100.354793, new int[] {1}); Estacion Aztlan = new Estacion(id++, "Aztlán", true, 25.732372, -100.347389, new int[] {1}); Estacion Penitenciaria = new Estacion(id++, "Penitenciaría", true, 25.723265, -100.342576, new int[] {1}); Estacion Alfonso = new Estacion(id++, "A<NAME>", true, 25.716040, -100.342585, new int[] {1}); Estacion Mitras = new Estacion(id++, "Mitras", true, 25.706002, -100.342491, new int[] {1}); Estacion SBolivar = new Estacion(id++, "<NAME>", true, 25.699065, -100.343278, new int[] {1}); Estacion Hospital = new Estacion(id++, "Hospital", true, 25.692156, -100.344188, new int[] {1}); Estacion Edison = new Estacion(id++, "Edison", true, 25.687138, -100.333614, new int[] {1}); Estacion Central = new Estacion(id++, "Central", true, 25.687217, -100.324428, new int[] {1}); Estacion Cuauhtemoc = new Estacion(id++, "Cuauhtémoc", true, 25.686382, -100.317309, new int[] {1, 2}); Estacion delGolfo = new Estacion(id++, "Del Golfo", true, 25.685128, -100.306619, new int[] {1}); Estacion Felix = new Estacion(id++, "<NAME>", true, 25.683959, -100.296814, new int[] {1, 2}); Estacion Parque = new Estacion(id++, "<NAME>", true, 25.683783, -100.288231, new int[] {1}); Estacion Y = new Estacion(id++, "Y Griega", true, 25.683333, -100.279645, new int[] {1}); Estacion Eloy = new Estacion(id++, "<NAME>", true, 25.680082, -100.264251, new int[] {1}); Estacion Lerdo = new Estacion(id++, "<NAME>", true, 25.679813, -100.252317, new int[] {1}); Estacion Expo = new Estacion(id++, "Exposición", true, 25.679525, -100.245584, new int[] {1}); //Linea 2 Estacion Sendero = new Estacion(id++, "Sendero", true, 25.768611, -100.292885, new int[] {2}); Estacion Tapia = new Estacion(id++, "Tapia", true, 25.759205, -100.295694, new int[] {2}); Estacion SNicolas = new Estacion(id++, "San Nicolás", true, 25.752723, -100.298012, new int[] {2}); Estacion Anahuac = new Estacion(id++, "Anahuac", true, 25.739769, -100.302719, new int[] {2}); Estacion Universidad = new Estacion(id++, "Universidad", true, 25.724372, -100.308243, new int[] {2}); Estacion nHeroes = new Estacion(id++, "Niños heroes", true, 25.717017, -100.310901, new int[] {2}); Estacion Regina = new Estacion(id++, "Regina", true, 25.708288, -100.314140, new int[] {2}); Estacion GAnaya = new Estacion(id++, "General Anaya", true, 25.697163, -100.316637, new int[] {2}); // Cuauhtemoc Estacion Alameda = new Estacion(id++, "Alameda", true, 25.677052, -100.318131, new int[] {2}); Estacion Fundadores = new Estacion(id++, "Fundadores", true, 25.672488, -100.319105, new int[] {2}); Estacion PMier = new Estacion(id++, "<NAME>", true, 25.668607, -100.315457, new int[] {2}); Estacion GZarag = new Estacion(id++, "<NAME>", true, 25.667736, -100.310236, new int[] {2, 3}); //Linea 3 //<NAME> Estacion SLucia = new Estacion(id++, "Santa Lucía", false, 25.670347, -100.298597, new int[] {3}); Estacion Adolfo = new Estacion(id++, "<NAME>", false, 25.677850, -100.297642, new int[] {3}); // <NAME> Estacion Conchello = new Estacion(id++, "Conchello", false, 25.691054, -100.295765, new int[] {3}); Estacion Violeta = new Estacion(id++, "Violeta", false, 25.701991, -100.290287, new int[] {3}); Estacion Ruiz = new Estacion(id++, "<NAME>", false, 25.703667, -100.287933, new int[] {3}); Estacion Angeles = new Estacion(id++, "Los Ángeles", false, 25.708078, -100.281677, new int[] {3}); Estacion Metropolitano = new Estacion(id++, "Hospital Metropolitano", false, 25.713538, -100.273747, new int[] {3}); // Conexiones Metro metrorrey = new Metro(id); // Linea 1 metrorrey.addVecinos(Talleres, new Estacion[] {SBernabe}); metrorrey.addVecinos(SBernabe, new Estacion[] {Talleres, UModelo}); metrorrey.addVecinos(UModelo, new Estacion[] {SBernabe, Aztlan}); metrorrey.addVecinos(Aztlan, new Estacion[] {UModelo, Penitenciaria}); metrorrey.addVecinos(Penitenciaria, new Estacion[] {Aztlan, Alfonso}); metrorrey.addVecinos(Alfonso, new Estacion[] {Mitras, Penitenciaria}); metrorrey.addVecinos(Mitras, new Estacion[] {Alfonso, SBolivar}); metrorrey.addVecinos(SBolivar, new Estacion[] {Mitras, Hospital}); metrorrey.addVecinos(Hospital, new Estacion[] {SBolivar, Edison}); metrorrey.addVecinos(Edison, new Estacion[] {Hospital, Central}); metrorrey.addVecinos(Central, new Estacion[] {Edison, Cuauhtemoc}); metrorrey.addVecinos(Cuauhtemoc, new Estacion[] {Central, delGolfo, GAnaya, Alameda}); metrorrey.addVecinos(delGolfo, new Estacion[] {Cuauhtemoc, Felix}); metrorrey.addVecinos(Felix, new Estacion[] {delGolfo, Parque, Conchello, Adolfo}); metrorrey.addVecinos(Parque, new Estacion[] {Felix, Y}); metrorrey.addVecinos(Y, new Estacion[] {Parque, Eloy}); metrorrey.addVecinos(Eloy, new Estacion[] {Y, Lerdo}); metrorrey.addVecinos(Lerdo, new Estacion[] {Eloy, Expo}); metrorrey.addVecinos(Expo, new Estacion[] {Lerdo}); // Linea 2 metrorrey.addVecinos(Sendero, new Estacion[] {Tapia}); metrorrey.addVecinos(Tapia, new Estacion[] {Sendero, SNicolas}); metrorrey.addVecinos(SNicolas, new Estacion[] {Tapia, Anahuac}); metrorrey.addVecinos(Anahuac, new Estacion[] {SNicolas, Universidad}); metrorrey.addVecinos(Universidad, new Estacion[] {Anahuac, nHeroes}); metrorrey.addVecinos(nHeroes, new Estacion[] {Universidad, Regina}); metrorrey.addVecinos(Regina, new Estacion[] {nHeroes, GAnaya}); metrorrey.addVecinos(GAnaya, new Estacion[] {Regina, Cuauhtemoc}); // Cuauhtemoc metrorrey.addVecinos(Alameda, new Estacion[] {Cuauhtemoc, Fundadores}); metrorrey.addVecinos(Fundadores, new Estacion[] {Alameda, PMier}); metrorrey.addVecinos(PMier, new Estacion[] {Fundadores, GZarag}); metrorrey.addVecinos(GZarag, new Estacion[] {PMier, SLucia}); // Linea 3 metrorrey.addVecinos(Metropolitano, new Estacion[] {Angeles}); metrorrey.addVecinos(Angeles, new Estacion[] {Metropolitano, Ruiz}); metrorrey.addVecinos(Ruiz, new Estacion[] {Angeles, Violeta}); metrorrey.addVecinos(Violeta, new Estacion[] {Ruiz, Conchello}); metrorrey.addVecinos(Conchello, new Estacion[] {Violeta, Felix}); // Felix metrorrey.addVecinos(Adolfo, new Estacion[] {Felix, SLucia}); metrorrey.addVecinos(SLucia, new Estacion[] {Adolfo, GZarag}); // GZarag //Print //System.out.println(metrorrey); Algoritmo A = new Algoritmo(metrorrey); // Con transbordos System.out.print("Ruta con transbordo: "); System.out.println(A.AestrellaConT(GAnaya, SLucia)); // Sin transbordos System.out.print("Ruta sin transbordo: "); System.out.println(A.AestrellaSinT(GAnaya, SLucia)); } } <file_sep>package ia.practica; import java.util.LinkedList; import java.util.List; public class Algoritmo { private List<Nodo> Abierta; private List<Nodo> Cerrada; private Metro metro; private int lineaActual; private static final int TRANSBORDO = 300; public Algoritmo(Metro metro) { Abierta = new LinkedList<Nodo>(); Cerrada = new LinkedList<Nodo>(); this.metro = metro; } public List<Estacion> AestrellaConT(Estacion origen, Estacion destino) { // Si el origen y el destino son el mismo if (origen.equals(destino)) return getRuta(new Nodo(origen)); // Establecemos la linea actual if (origen.sizeLineas() == 1) lineaActual = origen.getLineas()[0]; // si origen solo tiene una linea partimos de esa else { // Si no, vemos si origen y destino tienen una línea en común for (int lo : origen.getLineas()) for (int ld : origen.getLineas()) if (lo == ld) lineaActual = lo; // Si la linea actual sigue siendo null if (lineaActual == 0) lineaActual = origen.getLineas()[0]; // cogemos cualquiera } // añadimos el nodo origen a la lista abierta Abierta.add(new Nodo(origen)); // mientras que la lista abierta no este vacia while(!Abierta.isEmpty()) { // Lista donde se almacenan nodos hijos List<Nodo> hijos = new LinkedList<Nodo>(); // Nodo auxiliar Nodo aux = null; // buscamos el nodo con menor f en la lista abierta for(Nodo n : Abierta) if (aux == null || n.getF() < aux.getF()) aux = n; // Sacar el nodo de la lista abierta Abierta.remove(Abierta.indexOf(aux)); // Actualizamos la linea en la que nos encontramos if (aux.getEstacion().sizeLineas()== 1) lineaActual = aux.getEstacion().getLineas()[0]; // Generamos sus nodos hijos y ponemos que su nodo padre es q // Los guardamos en la lista hijos for (Estacion e : metro.getVecinos(aux.getEstacion().getId())) hijos.add(new Nodo(e, aux)); // Para cada hijo for (Nodo n : hijos) { // Actualizamos g, h y f de cada nodo hijo // Si hay transbordo lo sumamos if (n.getEstacion().sizeLineas() == 1 && n.getEstacion().getLineas()[0] != lineaActual) n.setG(aux.getG() + aux.getEstacion().distancia(n.getEstacion()) + TRANSBORDO ); else n.setG(aux.getG() + aux.getEstacion().distancia(n.getEstacion())); n.setH(n.getEstacion().distancia(destino)); n.setF(n.getG() + n.getH()); // si el nodo es el destino, se para la búsqueda if (n.getEstacion().equals(destino)) return getRuta(n); // Si ya hay un nodo en la lista abierta igual pero con f menor no hacemos nada if (Abierta.contains(n) && Abierta.get(Abierta.indexOf(n)).getF() < n.getF()) ; // EOC si ya hay un nodo en la lista cerrada con f menor no hacemos nada else if (Cerrada.contains(n) && Cerrada.get(Cerrada.indexOf(n)).getF() < n.getF()) ; // EOC añadimos el nodo a la lista abierta else Abierta.add(n); } // Añadimos el nodo a la lista cerrada Cerrada.add(aux); } return new LinkedList<Estacion>(); // Lista vacia } public List<Estacion> AestrellaSinT(Estacion origen, Estacion destino) { // Si el origen y el destino son el mismo if (origen.equals(destino)) return getRuta(new Nodo(origen)); // añadimos el nodo origen a la lista abierta Abierta.add(new Nodo(origen)); // mientras que la lista abierta no este vacia while(!Abierta.isEmpty()) { // Lista donde se almacenan nodos hijos List<Nodo> hijos = new LinkedList<Nodo>(); // Nodo auxiliar Nodo aux = null; // buscamos el nodo con menor f en la lista abierta for(Nodo n : Abierta) if (aux == null || n.getF() < aux.getF()) aux = n; // Sacar el nodo de la lista abierta Abierta.remove(Abierta.indexOf(aux)); // Generamos sus nodos hijos y ponemos que su nodo padre es q // Los guardamos en la lista hijos for (Estacion e : metro.getVecinos(aux.getEstacion().getId())) hijos.add(new Nodo(e, aux)); // Para cada hijo for (Nodo n : hijos) { // actualizamos g, h y f de cada nodo hijo n.setG(aux.getG() + aux.getEstacion().distancia(n.getEstacion())); n.setH(n.getEstacion().distancia(destino)); n.setF(n.getG() + n.getH()); // si el nodo es el destino, se para la búsqueda if (n.getEstacion().equals(destino)) return getRuta(n); // Si ya hay un nodo en la lista abierta igual pero con f menor no hacemos nada if (Abierta.contains(n) && Abierta.get(Abierta.indexOf(n)).getF() < n.getF()) ; // EOC si ya hay un nodo en la lista cerrada con f menor no hacemos nada else if (Cerrada.contains(n) && Cerrada.get(Cerrada.indexOf(n)).getF() < n.getF()) ; // EOC añadimos el nodo a la lista abierta else Abierta.add(n); } // Añadimos el nodo a la lista cerrada Cerrada.add(aux); } return new LinkedList<Estacion>(); // Lista vacia } private List<Estacion> getRuta(Nodo n) { LinkedList<Estacion> ruta = new LinkedList<Estacion>(); Nodo nodo = n; while (nodo.hasPadre()) { ruta.addFirst(nodo.getEstacion()); nodo = nodo.getPadre(); } ruta.addFirst(nodo.getEstacion()); return ruta; } } <file_sep># Metrorrey Proyecto de la asignatura de Inteligencia Artificial del grado de Ingeniería Informática de la UPM. El proyecto consiste en diseñar una aplicación para hallar el trayecto óptimo entre dos estaciones del metro de Monterrey. Para el cálculo del mejor camino se ha utilizado el algoritmo de búsqueda A\*. Además se ha escrito una simple interfaz donde se muestra el recorrido.
8d65fcd13bcfe98c0cc95ee6274cdf4b698b7191
[ "Markdown", "Java" ]
3
Java
bautisflow/Metrorrey
21de8bb6f90c620467d2a225c0f4d0fbbf97f855
29def9b128f7703f9000da047049c6900dd8e12f
refs/heads/master
<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Login_B : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(IsPostBack) { LoginModel loginModel = new LoginModel(); if(loginModel.login(username.Text, password.Text)) { User user = new User(); user.userId = username.Text; user.password = <PASSWORD>; Session["user"] = user; Response.Redirect("Home_B.aspx"); } else { status.Text = "Invalid credentials."; } } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { string username = Request.Form["username"]; string password = Request.Form["password"]; LoginModel model = new LoginModel(); if (model.login(username, password)) { if (rememberMe.Checked == true) { HttpCookie userInfoObject = new HttpCookie("user"); userInfoObject.Values["username"] = username; userInfoObject.Values["password"] = <PASSWORD>; userInfoObject.Expires = DateTime.Now.AddDays(14); Response.Cookies.Add(userInfoObject); } else { Session["username"] = username; Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1); } Response.Redirect("Home.aspx"); } else { status.Text = "Invalid user."; } } else { if (Request.Cookies["user"] != null) { HttpCookie userInfoObject = Request.Cookies["user"]; username.Text = userInfoObject.Values["username"]; password.Text = userInfoObject.Values["password"]; } } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Login_C : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Session["user"] = null; if (IsPostBack) { LoginModel loginModel = new LoginModel(); if (loginModel.login(username.Text, password.Text)) { User user = new User(); user.userId = username.Text; user.password = <PASSWORD>; Session["user"] = user; Response.Redirect("Home_C.aspx"); } else { status.Text = "Invalid credentials."; } } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Home_B : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { User user = (User)Session["user"]; user = new LoginModel().findById(user.userId); if (user != null) { firstname.Text = user.firstName; lastName.Text = user.lastName; userId.Text = user.userId; password.Text = <PASSWORD>; email.Text = user.email; question.Text = user.question; answer.Text = user.answer; Session["user"] = user; } else { Response.Redirect("Login_B.aspx"); } } catch(Exception exception) { Response.Redirect("Login_B.aspx"); } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Search_D : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(IsPostBack) { string s = search.Text; string p = param.SelectedValue; List<User> searchResults = new LoginModel().search(s, p); StringBuilder table = new StringBuilder(); table.Append("<table class='table'><thead><th>User Id</th><th>First Name</th>"); table.Append("<th>Last Name</th><th>Password</th><th>Email</th>"); table.Append("<th>Question</th><th>Answer</th></thead>"); try { for (int i = 0; i < searchResults.Count; i++) { table.Append("<tr>"); table.Append("<td>" + searchResults[i].userId + "</td>"); table.Append("<td>" + searchResults[i].firstName + "</td>"); table.Append("<td>" + searchResults[i].lastName + "</td>"); table.Append("<td>" + searchResults[i].password + "</td>"); table.Append("<td>" + searchResults[i].email + "</td>"); table.Append("<td>" + searchResults[i].question + "</td>"); table.Append("<td>" + searchResults[i].answer + "</td>"); table.Append("</tr>"); } } catch (Exception exception) { } table.Append("</table>"); PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() }); } } } }<file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Web; namespace Assignment5.model { public class LoginModel { internal List<User> search(string s, string p) { SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true"); try { dbConnection.Open(); dbConnection.ChangeDatabase("sktokka_ConservationSchool"); } catch (SqlException exception) { throw new Exception("Something went wrong."); } finally { Console.Write("Successfully selected the database"); } try { StringBuilder SQLString = new StringBuilder(); if(p.Equals("all")) { SQLString.Append("SELECT * from users where userID LIKE '%" + s + "%' OR firstName LIKE '%" + s + "%' "); SQLString.Append("OR lastName LIKE '%" + s + "%' OR password LIKE '%" + s + "%' OR email LIKE '%" + s + "%'"); } else { SQLString.Append("SELECT * from users where " + p + " LIKE '%" + s + "%'"); } SqlCommand sqlCommand = new SqlCommand(SQLString.ToString(), dbConnection); SqlDataReader reader = sqlCommand.ExecuteReader(); if (reader.HasRows) { List<User> results = new List<User>(); while (reader.Read()) { User user = new User(); user.userId = reader.GetString(0); user.firstName = reader.GetString(1); user.lastName = reader.GetString(2); user.password = reader.GetString(3); user.email = reader.GetString(4); user.question = reader.GetString(5); user.answer = reader.GetString(6); results.Add(user); } return results; } else { return null; } } catch (SqlException exception) { Console.WriteLine(exception.GetBaseException()); return null; } } public User updateUserDetails(User user) { SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true"); try { dbConnection.Open(); dbConnection.ChangeDatabase("sktokka_ConservationSchool"); } catch (SqlException exception) { throw new Exception("Something went wrong."); } finally { Console.Write("Successfully selected the database"); } try { string SQLString = "UPDATE users SET userID = '"+user.userId+"', firstname = '"+user.firstName+"', "+ "lastname = '"+user.lastName+"', password = '"+<PASSWORD>+"', email = '"+user.email+"', "+ "question = '"+user.question+"', answer = '"+user.answer+ "' WHERE userID = '" + user.userId + "'"; SqlCommand sqlCommand = new SqlCommand(SQLString, dbConnection); sqlCommand.ExecuteNonQuery(); return user; } catch (SqlException exception) { Console.WriteLine(exception.GetBaseException()); return null; } } public User findById(string userId) { SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true"); try { dbConnection.Open(); dbConnection.ChangeDatabase("sktokka_ConservationSchool"); } catch (SqlException exception) { throw new Exception("Something went wrong."); } finally { Console.Write("Successfully selected the database"); } try { string SQLString = "SELECT * FROM users WHERE userID = '" + userId + "'"; SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection); SqlDataReader reader = checkIDTable.ExecuteReader(); if (reader.HasRows) { User user = new User(); while (reader.Read()) { user.userId = reader.GetString(0); user.firstName = reader.GetString(1); user.lastName = reader.GetString(2); user.password = reader.GetString(3); user.email = reader.GetString(4); user.question = reader.GetString(5); user.answer = reader.GetString(6); } return user; } else { return null; } } catch (SqlException exception) { Console.WriteLine(exception.GetBaseException()); return null; } } public bool login(string username, string password) { SqlConnection dbConnection = new SqlConnection("Data Source=itksqlexp8;Integrated Security=true"); try { dbConnection.Open(); dbConnection.ChangeDatabase("sktokka_ConservationSchool"); } catch (SqlException exception) { if (exception.Number == 911) { SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE sktokka_ConservationSchool", dbConnection); sqlCommand.ExecuteNonQuery(); dbConnection.ChangeDatabase("sktokka_ConservationSchool"); } else throw new Exception("Something went wrong."); } finally { Console.Write("Successfully selected the database"); } try { string SQLString = "SELECT * FROM loginPartC WHERE userId = '" + username + "' AND password = '" + <PASSWORD> + "'"; SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection); SqlDataReader loginRecord = checkIDTable.ExecuteReader(); if (loginRecord.HasRows) { return true; } else { return false; } } catch (SqlException exception) { Console.WriteLine(exception.GetBaseException()); return false; } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Home_C : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { answer.Text = "Deasync, Express, Node-inspector, Mongodb, Lodash, Colors, Request, dateFormat, Cheero, Winston"; answer.Visible = false; loginLink.Visible = false; Label1.Visible = false; logout.Visible = false; User user = (User)Session["user"]; if(user != null) { answer.Visible = true; userId.Text = "Hello "+user.userId; logout.Visible = true; } else { loginLink.Visible = true; Label1.Visible = true; } } } }<file_sep>using Assignment5.model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Assignment5 { public partial class Update_B : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(IsPostBack) { User user = new User(Request.Form["firstname"], Request.Form["lastname"], Request.Form["userId"], Request.Form["password"], Request.Form["email"], Request.Form["question"], Request.Form["answer"]); user = new LoginModel().updateUserDetails(user); Session["user"] = user; Response.Redirect("Home_B.aspx"); } else { try { User user = (User)Session["user"]; if (user != null) { firstname.Text = user.firstName; lastname.Text = user.lastName; userId.Text = user.userId; password.Text = <PASSWORD>; email.Text = user.email; question.Text = user.question; answer.Text = user.answer; } else { Response.Redirect("Login_B.aspx"); } } catch (Exception exception) { Response.Redirect("Login_B.aspx"); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Assignment5.model { public class User { public string firstName; public string lastName; public string userId; public string password; public string email; public string question; public string answer; public User(string firstName, string lastName, string userId, string password, string email, string question, string answer) { this.firstName = firstName; this.lastName = lastName; this.userId = userId; this.password = <PASSWORD>; this.email = email; this.question = question; this.answer = answer; } public User() { } } }
abe37e8f4f633840e48a31725fcb66690e1e4bc9
[ "C#" ]
9
C#
sumittokkar/it485_5
6ec27f64df3a7a53548ddec215839f7a08beb5b6
d12a3ae97ed857b1492e6fdff5cff91db696035b
refs/heads/master
<file_sep> [package] name = "webscrap" version = "0.1.0" authors = ["linhuiju"] edition = "2018" [dependencies] reqwest = "0.9.22" scraper = "0.11.0" <file_sep>extern crate reqwest; extern crate scraper; use scraper::{Html, Selector}; fn main(){ println!("The Delhi Capitals are doing great this season as their results lately are the following:"); scrape_team_data("https://www.iplt20.com/teams/delhi-capitals/results"); } fn scrape_team_data(url:&str){ let mut req = reqwest::get(url).unwrap(); assert!(req.status().is_success()); let doc_body = Html::parse_document(&req.text().unwrap()); let team = Selector::parse(".result__outcome").unwrap(); for team in doc_body.select(&team){ let teams = team.text().collect::<Vec<_>>(); println!("{}", teams[0]); } }
8c8d043431b2bd7a427fdde7019a16e8f7622eff
[ "TOML", "Rust" ]
2
TOML
Coding-Runner/Rust-web-scrapping
fc61a98040bd9156a2336ce022fcdb617af38b34
686b1aaabba92eb85248672fa4146c697524fad0
refs/heads/main
<file_sep>import React from 'react'; import './SidebarSearch.css'; import SmartLogo from './SmartLogo.png'; function SidebarSearch() { return ( <div className="sidebarSearch"> <div className="sidebarSearch__categories"> <h1>Podkategorie</h1> <h2>Allegro</h2> <h3>popularne</h3> <p>Sport i turystyka</p> <div className="sidebarSearch__categoriesRow"> <p>trening siłowy</p> <p>4223</p> </div> <div className="sidebarSearch__categoriesRow"> <p>Sztangi</p> <p>23</p> </div> <div className="sidebarSearch__categoriesRow"> <p>Hantle</p> <p>167</p> </div> <div className="sidebarSearch__categoriesRow"> <p>ławki</p> <p>13</p> </div> <h3>wszystkie</h3> <div className="sidebarSearch__categoriesRow"> <p>Dom i Ogród</p> <p>637</p> </div> <div className="sidebarSearch__categoriesRow"> <p>Dziecko</p> <p>457</p> </div> <p className="sidebarSearch__more">Więcej</p> </div> <div className="sidebarSearch__filters"> <h2>Filtry</h2> <h3>Allegro Smart!</h3> <div className="sidebarSearch__filtersRowSmart"> <input type="checkBox" /> <p> Darmowa dostawa <img src={SmartLogo} /> </p> </div> <h3>stan</h3> <div className="sidebarSearch__filtersRow"> <div className="sidebarSerch__filterLeft"> <input type="checkBox" /> <p>nowe</p> </div> <p>12009</p> </div> <div className="sidebarSearch__filtersRow"> <div className="sidebarSerch__filterLeft"> <input type="checkBox" /> <p>używane</p> </div> <p>609</p> </div> </div> <div className="sidebarSearch__cities"> <h2>Popularne miasta</h2> <p>Warszawa</p> <p>Kraków</p> <p>Wrocław</p> <p>Poznań</p> <p>Katowice</p> <p>Gdańsk</p> </div> </div> ); } export default SidebarSearch; <file_sep>import React from 'react'; import './FashionRow.css'; import Product from './Product'; function FashionRow() { return ( <div className="fashionRow"> <p>Modowe okazje</p> <div className="fashionRow__container"> <Product imgUrl="https://membranarapgra.pl/pol_pl_Kurtka-Pitbull-Spinnaker-czarna-27556_5.jpg" discount="-33%" oldPrice="99,99 zł" price={69.99} description="Kutka PitBull Jesień" /> <Product imgUrl="https://img.pakamera.net/i1/7/371/kurtki-12374614_5908084371.jpg" discount="-25%" oldPrice="199,99 zł" price={149.99} description="Kurtka Fio Zielona" /> <Product imgUrl="https://www.uniformshop.pl/!uploads/products/b_851-spodnie-medyczne-damskie-vena-cygaretki-biale-1.jpg" discount="-50%" oldPrice="299,99 zł" price={149.99} description="Spodnie medyczne damskie" /> <Product imgUrl="https://www.symbiosis.com.pl/media/cache/gallery/rc/hlqajeoi/tommy-hilfiger-czapka-zimowa-tommy-chevr-damskie-czapki-multicolor-aw0aw04275413.jpg" discount="-25%" oldPrice="99,99 zł" price={75.99} description="Czapka <NAME>" /> <Product imgUrl="https://moodo.pl/pol_pl_Kurtka-jeansowa-10189_1.jpg" discount="-40%" oldPrice="199,99 zł" price={119.99} description="Kurtka jeansowa" /> </div> </div> ); } export default FashionRow; <file_sep>import React from 'react'; import './Hits.css'; import ProductRow from './ProductRow'; function Hits() { return ( <div className="hits"> <h2>Hity cenowe</h2> <div className="hits__container"> <ProductRow imgUrl="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRb5ingvbb4psEPa9CXbMs_7TxttYW7Aj2_NA&usqp=CAU" price={59.99} description="Adidas piłka nożna World Cup Telstar" bought="135" /> <ProductRow imgUrl="https://www.mediaexpert.pl/media/cache/gallery/product/1/810/215/579/pncunsbd/images/20/2007893/Smartfon-APPLE-iPhone-11--Purple-Front-Tyl.jpg" price={2859.99} description="Iphone 11 128 GB" bought="109" /> <ProductRow imgUrl="https://allegro.stati.pl/AllegroIMG/PRODUCENCI/DELL/Latitude-5401/Dell-Latitude-5401_4.jpg" price={3089.99} description="Dell latitude 5401 i7-9850H" bought={5291} /> </div> <div className="hits__footer">Zobacz więcej</div> </div> ); } export default Hits; <file_sep>import React, { useState } from 'react'; import Footer from '../Components/Footer'; import './Register.css'; import { useHistory } from 'react-router-dom'; import { auth } from '../firebase'; function Register() { const history = useHistory(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const register = (e) => { e.preventDefault(); auth .createUserWithEmailAndPassword(email, password) .then((auth) => { history.push('/login'); }) .catch((e) => alert()); }; return ( <div className="register"> <div className="register__container"> <h1>Utwórz konto</h1> <div className="register__choice"> <p>English version</p> <div class="register__choiceContainer"> <ul> <li> <input type="radio" id="f-option" name="selector" /> <label for="f-option">Konto Zwykłe</label> <p> Konto do zakupów (także dla firm) oraz sporadycznej sprzedaży </p> <div class="check"></div> </li> <li> <input type="radio" id="s-option" name="selector" /> <label for="s-option">Konto Firma</label> <p> Konto dla osób, które zamierzają sprzedawać w ramach prowadzonej działalności gospodarczej. </p> <div class="check"> <div class="inside"></div> </div> </li> </ul> </div> </div> <div className="register__data"> <div className="register__dataContainer"> <div className="register__dataInputs"> <div className="register__dataInput"> <input placeholder="E-mail" value={email} onChange={(event) => setEmail(event.target.value)} type="email" /> <p> Na ten adres będziesz otrzymywać wszystkie wiadomości od Allegro. </p> </div> <div className="register__dataInput"> <input placeholder="Hasło" value={password} onChange={(event) => setPassword(event.target.value)} type="password" /> <p>Użyj: 8 znaków, 1 wielkiej litery, 1 cyfry.</p> </div> <div className="register__dataInputsBirth"> <p>Data urodzenia</p> <input inputMode="numeric" min="1" max="31" placeholder="dzień" type="number" /> <select name="month" id=""> <option value="" selected="selected" hidden=""> miesiąc </option> <option value="1">stycznia</option> <option value="2">lutego</option> <option value="3">marca</option> <option value="4">kwietnia</option> <option value="5">maja</option> <option value="6">czerwca</option> <option value="7">lipca</option> <option value="8">sierpnia</option> <option value="9">września</option> <option value="10">października</option> <option value="11">listopada</option> <option value="12">grudnia</option> </select> <input placeholder="rok" type="number" inputMode="numeric" min="1900" max="2020" /> <p className="register__birthDescription"> Datę urodzenia potrzebujemy, żeby móc pokazać Ci oferty odpowiednie dla Ciebie. </p> </div> </div> <div className="register__dataCheckBoxes"> <div className="register__dataCheckBox"> <input type="checkbox" /> <p> Oświadczam, że znam i akceptuję postanowienia <span> Regulaminu Allegro</span> </p> </div> <div className="register__dataCheckBox"> <input type="checkbox" /> <p> Wyrażam zgodę na przetwarzanie moich danych osobowych w celach marketingowych i otrzymywanie informacji handlowych od Allegro z wykorzystaniem telekomunikacyjnych urządzeń końcowych (m.in. telefon) oraz środków komunikacji elektronicznej (m.in. SMS, e-mail). <span className="register__optional"> (opcjonalnie)</span> <span className="register__more">rozwiń</span> </p> </div> <div className="register__dataCheckBox"> <input type="checkbox" /> <p> Wyrażam zgodę na przetwarzanie moich danych osobowych w celach marketingowych i otrzymywanie informacji handlowych od podmiotów współpracujących z Allegro z wykorzystaniem telekomunikacyjnych urządzeń końcowych (m.in. telefon) oraz środków komunikacji elektronicznej (m.in. SMS, e-mail). <span className="register__optional"> (opcjonalnie)</span> <span className="register__more">rozwiń</span> </p> </div> </div> <button onClick={register} className="register__button"> zakładam konto </button> </div> </div> <p className="register__rules"> Administratorem Twoich danych osobowych jest Allegro.pl sp. z o.o. z siedzibą w Poznaniu (60-166), przy ul. Grunwaldzkiej 182. Twoje dane osobowe będą przetwarzane w szczególności w celu wykonania umowy zawartej z Tobą, w tym do umożliwienia świadczenia usługi drogą elektroniczną oraz pełnego korzystania z platformy handlowej Allegro, w tym dokonywania transakcji na naszej platformie. Gwarantujemy spełnienie wszystkich Twoich praw wynikających z ogólnego rozporządzenia o ochronie danych, tj. prawo dostępu, sprostowania oraz usunięcia Twoich danych, ograniczenia ich przetwarzania, prawo do ich przenoszenia, niepodlegania zautomatyzowanemu podejmowaniu decyzji, w tym profilowaniu, a także prawo wyrażenia sprzeciwu wobec przetwarzania Twoich danych osobowych (więcej na temat przetwarzania Twoich danych osobowych znajdziesz w <span> Polityce ochrony prywatności</span>). </p> </div> <Footer /> </div> ); } export default Register; <file_sep>import React from 'react'; import './ProductsCategories.css'; function ProductsCategories() { return ( <div className="productsCategories"> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/12c995/6ad566fe43a6814783543df54483" alt="" /> <div className="productsCategories__columnTitle">Praca z drewnem</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/120e5e/ee0e34c048b183e356fb15a5e75e" alt="" /> <div className="productsCategories__columnTitle">Strefa Fachowca</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/120a8f/af3109194151854ec26e17da4113" alt="" /> <div className="productsCategories__columnTitle">Strefa Mechanika</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/12f47a/c53f744341e68309738a7bb77e92" alt="" /> <div className="productsCategories__columnTitle">Zestawy XXL</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/12c26e/5b96bb40466db4810fce55f65dfd" alt="" /> <div className="productsCategories__columnTitle"> <NAME> </div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/124f14/a0268c2c4bd09cd8f33217de76d6" alt="" /> <div className="productsCategories__columnTitle"> Wszystkich Świętych </div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/128f09/25f01c6c4c659e36aa9a24f1f011" alt="" /> <div className="productsCategories__columnTitle"> Wszystko do majsterkowania </div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/128866/29d6dc6641be92341a782771094e" alt="" /> <div className="productsCategories__columnTitle"> Wielopaki w promocji </div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/122c90/b9d253fc46e391a745649fcb8007" alt="" /> <div className="productsCategories__columnTitle">Redmi Note 9 Pro</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/123deb/a27e7ee84f229737cf3b900b3762" alt="" /> <div className="productsCategories__columnTitle">Sypialnia</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/12effe/4c89f57a4f17b33546db6d1a9707" alt="" /> <div className="productsCategories__columnTitle">Domowe biuro</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/12079a/ca96f9044e83807a43ee06bf2687" alt="" /> <div className="productsCategories__columnTitle"> Hulajnogi elektryczne </div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/1220c9/00ce125b40adb114ec0722e9bde1" alt="" /> <div className="productsCategories__columnTitle">Opony zimowe</div> </div> <div className="productsCategories__column"> <img src="https://a.allegroimg.com/original/127ddc/1d639c394874b92d51bfd3d7cb75" alt="" /> <div className="productsCategories__columnTitle">Moda Plus Size</div> </div> </div> ); } export default ProductsCategories; <file_sep>import React from 'react'; import './Banner.css'; import Product from './Product'; function Banner() { return ( <div className="banner"> <p>Fotowoltaika</p> <div className="banner__container"> <img src="https://ozeprojekt.pl/wp-content/uploads/2019/10/fotowoltaika-stock2.png" alt="" /> <div className="banner__products"> <div className="bannerProducts__container"> <Product imgUrl="https://botland.com.pl/blog/wp-content/uploads/2020/06/paneleslonecznemaly-300x229.png" discount="-10%" oldPrice="199,99 zł" price={179.99} description="ogniwo fotowoltaiczne" /> <Product imgUrl="https://www.multiproject.com.pl/images/Foto/Fotowoltaika/03395.jpg" discount="-40%" oldPrice="1999,99 zł" price={1099.99} description="Panel Fotowoltaiczny" /> <Product imgUrl="https://www.mc-sklep.pl/images/solare/4sun/panel-elastyczny-4sun-flex-etfe-m-150w-24v-prestige.jpg" discount="-10%" oldPrice="2499,99 zł" price={2249.99} description="Panel fotowoltaiczny Flex" /> </div> <div className="bannerProducts__more">Zobacz więcej</div> </div> </div> </div> ); } export default Banner; <file_sep>import React, { useEffect, useState } from 'react'; import Footer from '../Components/Footer'; import './ProfilePage.css'; import Monets from '../Components/Monets.png'; import SmartPurple from '../Components/SmartPurple.png'; import YourProduct from '../Components/YourProduct'; import { useStateValue } from '../StateProvider'; import { storage, firebase, auth, db } from '../firebase'; function ProfilePage() { const [{ user }] = useStateValue(); const [description, setDescription] = useState(''); const [price, setPrice] = useState(0); const [progress, setProgress] = useState(0); const [auctions, setAuctions] = useState([]); const [imageUrl, setImageUrl] = useState(''); const handleUpload = (e) => { e.preventDefault(); // db stuff db.collection('auctions').add({ description: description, timestamp: firebase.firestore.FieldValue.serverTimestamp(), price: price, username: user.email, imgUrl: imageUrl, }); // restet setDescription(''); setImageUrl(''); setPrice(0); }; const logOut = () => { auth.signOut(); }; useEffect(() => { db.collection('auctions') // .orderBy("timestamp", "desc") .onSnapshot((snapshot) => setAuctions( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })) ) ); console.log('>>>>>>>>>>', auctions); }, []); return ( <div className="profilePage"> <div className="profilePage__container"> <div className="profilePage__containerSettings"> <div className="profilePage__left"> <div className="profilePage__description"> <h1>Dzień dobry!</h1> <p>{user?.email}</p> <img src={Monets} alt="" /> <img src={SmartPurple} alt="" /> <button onClick={logOut}>Wyloguj</button> </div> <img src="https://a.allegroimg.com/original~ovwcolormcolorgreen300/1d930d/02e3f098419fb04e881a8cda8d76" alt="" /> </div> <div className="profilePage__right"> <h1>Wystaw produkt</h1> <div className="profilePage__upload"> <progress className="profilePage__uploadProgress" value={progress} max="100" /> <input type="text" placeholder="Opis produktu" onChange={(event) => setDescription(event.target.value)} value={description} /> <input type="number" placeholder="Cena całkowita, bez przecinka" onChange={(event) => setPrice(event.target.value)} value={price} /> <p className="profilePage__priceDescription"> Cena produktu, w pełnych złotych </p> <input type="text" placeholder="adres www zdjęcia" onChange={(event) => setImageUrl(event.target.value)} value={imageUrl} /> <button onClick={handleUpload} className="profilePage__uploadButton"> Wstaw </button> </div> </div> </div> <div className="profilePage__containerProducts"> <h1>Ostatnio wstawione produkty</h1> <div className="profilePage__products"> {auctions.map((auction) => ( <YourProduct key={auction.id} imgUrl={auction.data.imgUrl} description={auction.data.description} price={auction.data.price} user={user?.email} /> ))} </div> </div> </div> <Footer /> </div> ); } export default ProfilePage; <file_sep>import React from 'react'; import './Occassions.css'; import Product from './Product'; function Occassions() { return ( <div className="ocassions"> <h2>Okazja dnia</h2> <div className="ocassions__container"> <Product imgUrl="https://przemax.pl/10575-home_default/rea-milan-zestaw-natryskowy-z-deszczownica-i-bateria-termostatyczna-chrom.jpg" discount="-10%" oldPrice="99,99 zł" price={89} description="Deszczownica zestaw natryskowy" /> </div> <div className="ocassions__more">Przejdź do strefy okazji</div> </div> ); } export default Occassions; <file_sep>import React from 'react'; import Footer from '../Components/Footer'; import './PaymentPage.css'; import { useStateValue } from '../StateProvider'; import { Link } from 'react-router-dom'; function PaymentPage() { const [{ amount, buyNow }, dispatch] = useStateValue(); return ( <div className="paymentPage"> <p className="paymentPage__title">Dostawa i płatność</p> <div className="paymentPage__container"> <div className="paymentPage__left"> <h2>Dane odbiorcy przesyłki</h2> <p>Na ten adres zostanie wysłana Twoja przesyłka</p> <p> Dane wpisane przy pierwszym zakupie zachowamy w Twoim profilu, abyś nie musiał powtarzać tego w przyszłości. </p> <div className="paymentPage__inputContainer"> <input placeholder="Imię" type="text" /> <input placeholder="Nazwisko" type="text" /> <input placeholder="Firma" type="text" /> <p>Opcjonalnie</p> <input placeholder="Adres" type="text" /> <p>Podaj nazwę ulicy wraz z numerem domu.</p> <input placeholder="Kod pocztowy" type="text" /> <input placeholder="Miasto" type="text" /> <input placeholder="Nr telefonu" type="text" /> <p> Podaj nr telefonu. Ułatwi to kontakt ze sprzedającym i kurierem. </p> </div> </div> <div className="paymentPage__right"> <h2>Podsumowanie</h2> <div className="paymentPage__productPrice"> <p>Wartość przedmiotów</p> {amount?.map((item) => ( <p>{item.price} zł</p> ))} {buyNow?.map((item) => ( <p>{item.price * item.items} zł</p> ))} </div> <div className="paymentPage__postman"> <p>Dostawa</p> <p>0,00 zł</p> </div> <div className="paymentPage__sum"> <p>Do zapłaty</p> <b> {amount?.map((item) => ( <p>{item.price} zł</p> ))} {buyNow?.map((item) => ( <p>{item.price * item.items} zł</p> ))} </b> </div> <Link to="/bought"> {' '} <button className="paymentPage__buttonBuy">Kupuję i płacę</button> </Link> <p> Klikając w ten przycisk potwierdzasz zakup. Sprzedawca otrzyma twoje zamówienie. </p> </div> </div> <Footer /> </div> ); } export default PaymentPage; <file_sep>import React from 'react'; import './Slider.css'; function Slider() { return ( <div className="slider"> <img className="slider__image" src="https://a.allegroimg.com/original/125808/958819ac42489210cb54c6943b39" alt="" /> <div className="slider__description"> <div className="slider__descriptionTitle">Pranie do -53%</div> <div className="slider__descriptionTitle">Płać kartą</div> <div className="slider__descriptionTitle">Kup na zapas do -48%</div> <div className="slider__descriptionTitle">PyrkONline</div> <div className="slider__descriptionTitle slider__descriptionTitle--active"> Pilarki łańcuchowe </div> </div> </div> ); } export default Slider; <file_sep>import React, { useState, useRef } from 'react'; import './Promo.css'; // import PromoVideo from './PromoVideo.mp4'; import PromoImg from './PromoImg.jpg'; function Promo({ imgUrl }) { // const [play, setPlay] = useState(false); // const videoRef = useRef(null); // const onVideoPress = () => { // if (play) { // videoRef.current.pause(); // setPlay(false); // } else { // videoRef.current.play(); // setPlay(true); // } // }; return ( <div className="promo"> <img src={imgUrl} alt="" className="promo__img" /> {/* <p>Zima za pasem, wyposaż się na białe szaleństwo</p> <video ref={videoRef} onClick={onVideoPress} loop src={PromoVideo}></video> */} </div> ); } export default Promo; <file_sep>import React from 'react'; import './YourProduct.css'; function YourProduct({ user, imgUrl, description, price }) { return ( <div className="yourProduct"> <img src={imgUrl} alt="" /> <div className="yourProduct__description"> <p>{description}</p> <b> <span>Stan: </span> nowy </b> <div className="yourProduct__price"> <p className="yourProduct__priceAmount">{price} zł</p> </div> </div> </div> ); } export default YourProduct; <file_sep>import React, { useState } from 'react'; import './Login.css'; import { Link } from 'react-router-dom'; function Login() { const [user, setUser] = useState(false); return ( <div className="login"> <div className="login__row"> <img src="https://a.allegroimg.com/original/12316d/2268070d49aaab12c8e5983855b0" alt="" /> <div className="login__rowTitle">Darmowe dostawy z Allegro Smart!</div> </div> <div className="login__row"> <img src="https://a.allegroimg.com/original/12092f/c3813a694866ac18da107e5fa5e0" alt="" /> <div className="login__rowTitle"><NAME></div> </div> <div className="login__row"> <img src="https://a.allegroimg.com/original/126037/31bef5314fee997dbfbd66142ee7" alt="" /> <div className="login__rowTitle">Oceń produkty</div> </div> {!user ? ( <Link to="/login"> <button className="login__button">Zaloguj się</button> </Link> ) : ( <button className="login__button">Wyloguj się</button> )} </div> ); } export default Login; <file_sep>import React from 'react'; import './Searched.css'; import SmartLogo from './SmartLogo.png'; import { Link } from 'react-router-dom'; import { useStateValue } from '../StateProvider'; function Searched({ id, imgUrl, price, description, bought, username }) { const [{ product }, dispatch] = useStateValue(); const openProduct = () => { dispatch({ type: 'OPEN_PRODUCT', item: { id: id, description: description, imgUrl: imgUrl, price: price, }, }); }; return ( <Link onClick={openProduct} to="/product" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="searched"> <img src={imgUrl} alt="" /> <div className="searched__description"> <p>{description}</p> <b> <span>Stan: </span> nowy </b> <hr /> <b> <span>Sprzedający: </span> {username} </b> <div className="searched__price"> <p className="searched__priceAmount"> {price} <span>,00 zł</span> </p> <div className="searched__smartLogo"> <img src={SmartLogo} alt="" /> <p>z kurierem</p> </div> </div> <div className="searched__offerBought">{bought} osób kupiło</div> <Link to="/cart" style={{ textDecoration: 'none', color: 'inherit' }}></Link> </div> </div> </Link> ); } export default Searched; <file_sep>import React from 'react'; import './ButtonBuy.css'; import { useStateValue } from '../StateProvider'; function ButtonBuy({ amount }) { const [{}, dispatch] = useStateValue(); const buyProduct = () => { dispatch({ type: 'BUY_PRODUCT', item: { price: amount, }, }); console.log(amount); }; return ( <div className="buttonBuy"> <button onClick={buyProduct} className="cartPage__buttonBuy"> Dostawa i płatność </button> </div> ); } export default ButtonBuy; <file_sep>import React from 'react'; import './Add.css'; function Add({ imgUrl }) { return ( <div className="add"> <img src={imgUrl} alt="" /> </div> ); } export default Add; <file_sep>import React from 'react'; import './Choosen.css'; import SmartLogo from './SmartLogo.png'; import { Link } from 'react-router-dom'; import { useStateValue } from '../StateProvider'; function Choosen({ id, imgUrl, discount, oldPrice, price, description }) { const [{ product }, dispatch] = useStateValue(); const openProduct = () => { dispatch({ type: 'OPEN_PRODUCT', item: { id: id, description: description, imgUrl: imgUrl, price: price, discount: discount, oldPrice: oldPrice, }, }); }; return ( <div className="choosen"> <div className="choosen__title">Okazja wybrana dla Ciebie</div> <div className="choosen__offer"> <Link onClick={openProduct} to="/product" style={{ textDecoration: 'none', color: 'inherit' }}> <img className="choosen__offerImage" src={imgUrl} alt="" /> </Link> <div className="choosen__offerDescription"> <div className="choosen__offerDiscount"> <div className="choosen__offerPercentage">{discount}</div> <div className="choosen__offerOld">{oldPrice}</div> </div> <div className="choosen__price"> <div className="choosen__offerPrice"> {price},<span>99 zł</span> </div> <img src={SmartLogo} alt="" className="choosen__offerPriceImage" /> </div> <div className="choosen__offerProduct">{description}</div> <div className="choosen__offerBought">3089 osób kupiło</div> </div> </div> <div className="choosen__footer">Zobacz więcej okazji</div> </div> ); } export default Choosen; <file_sep>import React from 'react'; import './SearchPage.css'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import SidebarSearch from '../Components/SidebarSearch'; import Footer from '../Components/Footer'; import Sponsored from '../Components/Sponsored'; import SearchResults from '../Components/SearchResults'; import { useStateValue } from '../StateProvider'; function SearchPage() { const [{ searchedPhrase }] = useStateValue(); return ( <div className="searchPage"> <div className="searchPage__container"> <div className="searchPage__header"> <h1> szukasz{' '} {searchedPhrase.map((item) => ( <p className="searchPage__searchedPhrase"> {item.searchedPhrase} </p> ))} <span>(12 098 ofert)</span> </h1> <p> <StarBorderIcon /> Obserwuj wyszukiwanie </p> </div> <div className="searchPage__body"> <SidebarSearch /> <div className="searchPage__bodyMain"> <Sponsored /> <SearchResults /> </div> </div> </div> <Footer /> </div> ); } export default SearchPage; <file_sep>import firebase from 'firebase'; const firebaseConfig = { apiKey: '<KEY>', authDomain: 'allegro-clone-bc495.firebaseapp.com', databaseURL: 'https://allegro-clone-bc495.firebaseio.com', projectId: 'allegro-clone-bc495', storageBucket: 'allegro-clone-bc495.appspot.com', messagingSenderId: '18707238689', appId: '1:18707238689:web:17984a77148644e4a6b860', }; const firebaseApp = firebase.initializeApp(firebaseConfig); const db = firebaseApp.firestore(); const auth = firebase.auth(); const storage = firebase.storage(); const provider = new firebase.auth.GoogleAuthProvider(); export { db, auth, storage, provider, firebase }; <file_sep>import React from 'react'; import RowOfProducts from './RowOfProducts'; import './OcassionsForYou.css'; function OcassionsForYou({ title }) { return ( <div className="ocassionsForYou"> <p>{title}</p> <RowOfProducts /> </div> ); } export default OcassionsForYou; <file_sep>import React, { useState } from 'react'; import Footer from '../Components/Footer'; import ProductCart from '../Components/ProductCart'; import './CartPage.css'; import { Link } from 'react-router-dom'; import { useStateValue } from '../StateProvider'; import { getBasketTotal } from '../reducer'; import CurrencyFormat from 'react-currency-format'; import ButtonBuy from '../Components/ButtonBuy'; function CartPage() { const [{ basket }, dispatch] = useStateValue(); console.log({ basket }); return ( <div className="cartPage"> <p className="cartPage__title">Twój koszyk</p> <div className="cartPage__container"> <div className="cartPage__containerLeft"> {basket?.length === 0 ? ( <div> <h2>Twój kosz jest pusty</h2> <p> Nie masz żadnych przedmiotów w koszu, jeśli chcesz kupić dany przedmiot, to kliknij "dodaj do koszyka", lub "Kup teraz" </p> </div> ) : ( basket?.map((item) => ( <ProductCart id={item.id} imgUrl={item.image} title={item.title} price={item.price} items={item.items} /> )) )} </div> {basket.length > 0 && ( <div className="cartPage__containerRight"> <div className="cartPage__amount"> <p>Do zapłaty</p> <div className="cartPage__amountPrice"> <p> <CurrencyFormat decimalScale={2} value={getBasketTotal(basket)} displayType={'text'} thousandSeparator={true} prefix={'zł '} /> </p> <b>+ dostawa</b> </div> </div> <div className="cartPage__buttons"> <button className="cartPage__buttonZero">Kup na raty zero</button> <Link to="/payment"> {/* <button className="cartPage__buttonBuy"> Dostawa i płatność </button> */} <ButtonBuy amount={getBasketTotal(basket)} /> </Link> <Link to="/"> <button className="cartPage__buttonContinue"> Kontynuuj zakupy </button> </Link> </div> </div> )} </div> <Footer /> </div> ); } export default CartPage; <file_sep>import React, { useEffect, useState } from 'react'; import Searched from './Searched'; import './SearchResults.css'; import { useStateValue } from '../StateProvider'; import { storage, firebase, auth, db } from '../firebase'; function SearchResults() { const [{ user }] = useStateValue(); const [auctions, setAuctions] = useState([]); useEffect(() => { db.collection('auctions') // .orderBy("timestamp", "desc") .onSnapshot((snapshot) => setAuctions( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() })) ) ); }, []); return ( <div className="searchResults"> {auctions.map((auction) => ( <Searched key={auction.id} imgUrl={auction.data.imgUrl} description={auction.data.description} price={auction.data.price} bought={0} username={auction.data.username && auction.data.username} /> ))} <Searched imgUrl="https://image.ceneostatic.pl/data/products/73912279/i-gorilla-sports-zestaw-sztanga-obciazenia-38kg-winyl.jpg" description="Sztanga 38kg HIT" price={210} bought="3068" /> <Searched imgUrl="https://nordicsklep.pl/96254-thickbox_default/hg-pro-9-kg-hantle-gumowane-hms.jpg" description="Hantle 9kg" price={110} bought="358" /> <Searched imgUrl="https://sapphire-sport.com/wp-content/uploads/2017/11/hantle-zeliwne-xylo-2x20kg-1.jpg" description="Hantle regulowane, żeliwne 5-30kg" price={290} bought="12" /> <Searched imgUrl="https://contents.mediadecathlon.com/p875975/k229df48a8f19114737b33e5acb331d96/875975_default.jpg?format=auto&quality=60&f=800x0" description="Hantle 1kg, to też ciężar!" price={10} bought="8" /> <Searched imgUrl="https://m.zdrowyzwierzak.pl/pol_pl_Matatabi-sztanga-zabawka-kota-gryzak-czysci-zeby-3021_1.jpg" description="Sztanga gryzak, idealna dla psa" price={15} bought="98" /> <Searched imgUrl="https://sportplus.pl/9778/hantle-stale-3-55-kg-hektor-sport.jpg" description="Hantle 10-35kg stojak" price={1990} bought="78068" /> </div> ); } export default SearchResults; <file_sep>import React from 'react'; import './Categories.css'; import { Link } from 'react-router-dom'; function Categories() { return ( <div className="categories"> <div className="categories__header"> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__headerLeft"> <h2>DZIAŁY</h2> </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> {' '} <div className="categories__headerRight"> <h2>KORZYŚCI</h2> </div> </Link> </div> <div className="categories__body"> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/house-and-tree-3d644b1630.svg" alt="" /> Elektronika </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/dress-c001e8d7f1.svg" alt="" /> Moda </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/house-and-tree-3d644b1630.svg" alt="" /> Dom i Ogród </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/basket-f6c9c75c2a.svg" alt="" /> Supermarket </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/baby-58992b9d89.svg" alt="" /> Dziecko </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/lipstick-974cf1db4e.svg" alt="" /> Uroda </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/first-aid-0c601a56cb.svg" alt="" /> Zdrowie </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/book-58344d0822.svg" alt="" /> Kultura i rozrywka </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/ball-f1f0883cc6.svg" alt="" /> Sport i turystyka </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/car-0b4e0bbc3b.svg" alt="" /> Motoryzacja </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/house-and-magnifying-glass-7d24599ece.svg" alt="" /> Nieruchomości </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/stamp-d912af3b1c.svg" alt="" /> Kolekcje i sztuka </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/skyscraper-1989b66d12.svg" alt="" /> Firma i usługi </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://assets.allegrostatic.com/metrum/icon/tickets-b3e077f330.svg" alt="" /> eBilet </div> </Link> <Link to="/demo" style={{ textDecoration: 'none', color: 'inherit' }}> <div className="categories__row"> <img src="https://a.allegroimg.com/original/128d44/a65b526446de941d12f9faa1337f" alt="" /> Allegro Lokalnie </div> </Link> </div> <div className="categories__all">Wszystkie kategorie</div> </div> ); } export default Categories; <file_sep>import React from 'react'; import Product from './Product'; import './RowOfProducts.css'; function RowOfProducts() { return ( <div className="rowOfProducts"> <Product imgUrl="https://sklepkoszykarski.pl/environment/cache/images/500_500_productGfx_209b59710065b1d591d7fcccde6ce9d4.jpg" discount="-33%" oldPrice="299,99 zł" price={199.99} description="Piłka do koszykówki Spalding NBA" /> <Product imgUrl="https://matrixnarzedzia.pl/data/gfx/pictures/medium/7/7/5377_12.jpg" discount="-25%" oldPrice="1999,99 zł" price={1499.99} description="Kosiarka UR-LS48 Spalinowa" /> <Product imgUrl="https://ecsmedia.pl/c/macbeth-b-iext52538660.jpg" discount="-50%" oldPrice="39,99 zł" price={19.99} description="<NAME>" /> <Product imgUrl="https://ansel.frgimages.com/chicago-bulls/michael-jordan-signed-jersey-1984-85-red-rookie-mitchell-and-ness-framed-upper-deck_ss2_p-11048448+u-xc8rn5x72btuhoyld4wp+v-086c36c40af240d5ae4220323eb9cd68.jpg?_hv=1&w=900" discount="-20%" oldPrice="1999,99 zł" price={1599.99} description="Jersey <NAME>" /> <Product imgUrl="https://3.allegroimg.com/s512/03acbf/83a0f87748e9aeedd4d8981aa653/KOSZ-NA-SMIECI-biurowy-z-siatki-SIATKA-metalowa19L" discount="-40%" oldPrice="49.99 zł" price={29.99} description="Kosz na śmieci" /> </div> ); } export default RowOfProducts; <file_sep>import React from 'react'; import './Footer.css'; function Footer() { return ( <div className="footer"> <div className="footer__container"> <div className="footer__columnContainer"> <div className="footer__column"> <h3>Allegro</h3> <p>O nas</p> <p>Reklama</p> <p>Allegro Ads</p> <p>Allegro API</p> <p>Praca w Allegro</p> <p>Społeczna Odpowiedzialność</p> <p>Allegro Polecam</p> <p>Mapa strony</p> </div> <div className="footer__column"> <h3>Centrum pomocy</h3> <p>Pomoc</p> <p>Spytaj Społeczność</p> <p>Kupuj na Allegro</p> <p>Dla sprzedających</p> <p>Sprzedawaj na Allegro</p> <p>Polityka plików "cookies"</p> <p>Regulamin</p> <p>Dopasowanie reklam</p> <p>Udostępnianie lokalizacji</p> </div> <div className="footer__column"> <h3>Serwisy</h3> <p>Allegro Smart!</p> <p>Strefa marek</p> <p>Artykuły</p> <p>Archiwum Allegro</p> <p>Monety Allegro</p> <p>Karty podarunkowe Allegro</p> <p>Akademia Allegro</p> <p>Allegro lokalnie</p> <p>Allegro Charytatywni</p> </div> <div className="footer__column"> <h3>Allegro in English</h3> <p>Sell on Allegro</p> <p>Help Center</p> <p>Terms and Conditions</p> </div> </div> <div className="footer__logos"> <div className="footer__downloads"> <img src="https://assets.allegrostatic.com/metrum/icon/appstore-1bc3bc3c06.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/playstore-d44c743ccc.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/appgallery-e4b87bbf17.svg" alt="" /> </div> <div className="footer__socialMedia"> <img src="https://assets.allegrostatic.com/metrum/icon/facebook-a2b92f9dcb.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/linkedin-cd6807318a.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/instagram-95464778fb.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/pinterest-d8d9e5a8f6.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/youtube-dca5fff408.svg" alt="" /> <img src="https://assets.allegrostatic.com/metrum/icon/charity-7610bf9ae4.svg" alt="" /> </div> </div> </div> <div className="footer__rules"> <p> Korzystanie z serwisu oznacza akcpetację <span>regulaminu</span> </p> <img src="https://a.allegroimg.com/original/126b6e/bf09245243ef947800dfb73121cb" alt="" /> </div> </div> ); } export default Footer; <file_sep>import React from 'react'; import './Sponsored.css'; import SmartLogo from './SmartLogo.png'; import OfferSearchPage from './OfferSearchPage'; function Sponsored() { return ( <div className="sponsored"> <div className="sponsored__row"> <OfferSearchPage img="https://www.komputronik.pl/informacje/wp-content/uploads/2020/03/ps5_premiera.jpg" discount="20" priceOld="2499" price={1999} description="Playstation 5" bought="3089" /> <OfferSearchPage img="https://stat-m2.ms-online.pl/media/cache/gallery_1090_800/images/20/20982520/apple-iphone-11-zielony-3.jpg" discount="10" priceOld="2999" price={2699} description="iphone 11" bought="86379" /> </div> </div> ); } export default Sponsored; <file_sep>import React, { useState } from 'react'; import './LoginPage.css'; import { Link, useHistory } from 'react-router-dom'; import { auth, provider } from '../firebase'; import { useStateValue } from '../StateProvider'; function LoginPage() { // login & register const history = useHistory(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [state, dispatch] = useStateValue(); const login = (e) => { e.preventDefault(); auth .signInWithEmailAndPassword(email, password) .then((auth) => { history.push('/'); }) .catch((e) => alert('Błędne hasło lub login')); }; const signIn = () => { // sign in auth .signInWithPopup(provider) .then((result) => { dispatch({ user: result.user, }); console.log(result); }) .catch((error) => alert(error.message)); }; // const register = (e) => { // e.preventDefault(); // auth // .createUserWithEmailAndPassword(email, password) // .then((auth) => { // history.push('/'); // }) // .catch((e) => alert()); // }; return ( <div className="loginPage"> <div className="loginPage__loginContainer"> <div className="loginPage__login"> <h1>Zaloguj się</h1> <input value={email} onChange={(event) => setEmail(event.target.value)} type="email" placeholder="e-mail" /> <input placeholder="Hasło" value={password} onChange={(event) => setPassword(event.target.value)} type="password" /> <div className="loginPage__loginButtons"> <p>Nie pamiętasz hasła?</p> <button onClick={login}>Zaloguj się</button> </div> <div className="loginPage__divider"> <hr /> <span>lub</span> <hr /> </div> <div className="loginPage__socialButtons"> <button onClick={signIn} className="loginPage__facebookButton"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Facebook_Circle.svg/1024px-Facebook_Circle.svg.png" alt="" /> Zaloguj się przez Facebook </button> <button onClick={signIn} className="loginPage__googleButton"> <img src="http://pngimg.com/uploads/google/google_PNG19635.png" alt="" /> Zaloguj się przez Google </button> </div> </div> <div className="loginPage__register"> <h3>Nie masz konta?</h3> <Link style={{ color: 'inherit', textDecoration: 'none' }} to="/register"> <p className="loginPage__registerButton">Zarejestruj się</p> </Link> </div> </div> <div className="loginPage__rules"> <p> Logując się do Allegro akceptujesz <span>Regulamin</span> w aktualnym brzmieniu obowiązującym od dnia 2020-09-04. Informacje o planowanych oraz archiwalnych zmianach Regulaminu są dostępne na <span> stronie</span> </p> </div> <div className="loginPage__chooses"> <div className="loginPage__choose"> <img src="https://assets.allegrostatic.com/metrum/icon/wow-offer-a8cea65e64.svg" alt="" /> <div className="loginPage__chooseDescription"> <h2>Najlepsze ceny</h2> <p>100 tysięcy sklepów konkuruje o Twoją uwagę.</p> </div> </div> <div className="loginPage__choose"> <img src="https://assets.allegrostatic.com/metrum/icon/much-offer-e1755ea681.svg" alt="" /> <div className="loginPage__chooseDescription"> <h2>Największy wybór</h2> <p>95 milionów produktów w jednym miejscu.</p> </div> </div> <div className="loginPage__choose"> <img src="https://assets.allegrostatic.com/metrum/icon/such-safe-d7c304b8d6.svg" alt="" /> <div className="loginPage__chooseDescription"> <h2>Zawsze bezpiecznie</h2> <p>Zwrot zakupów i ochrona Kupującego dla każdego.</p> </div> </div> </div> <div className="loginPage__footer"> <p> Korzystanie z serwisu oznacza akcpetację <span>regulaminu</span> </p> <img src="https://a.allegroimg.com/original/126b6e/bf09245243ef947800dfb73121cb" alt="" /> </div> </div> ); } export default LoginPage; <file_sep>import React, { useEffect } from 'react'; import './App.css'; import Categories from './Components/Categories'; import Header from './Components/Header'; import Slider from './Components/Slider'; import WorthSeeing from './Components/WorthSeeing'; import Choosen from './Components/Choosen'; import Login from './Components/Login'; import Add from './Components/Add'; import Occassions from './Components/Occassions'; import Hits from './Components/Hits'; import FourProducts from './Components/FourProducts'; import ProductsCategories from './Components/ProductsCategories'; import OcassionsForYou from './Components/OcassionsForYou'; import Promo from './Components/Promo'; import WinterRow from './Components/WinterRow'; import MotoRow from './Components/MotoRow'; import FashionRow from './Components/FashionRow'; import ElectronicsRow from './Components/ElectronicsRow'; import Banner from './Components/Banner'; import Footer from './Components/Footer'; import PromoImg from './Components/PromoImg.jpg'; import SolarPower from './Components/SolarPower.jpg'; import LoginPage from './Pages/LoginPage'; import Register from './Pages/Register'; import ProductPage from './Pages/ProductPage'; import SearchPage from './Pages/SearchPage'; import CartPage from './Pages/CartPage'; import PaymentPage from './Pages/PaymentPage'; import ProfilePage from './Pages/ProfilePage'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import ScrollToTop from './ScrollToTop'; import { auth } from './firebase'; import { useStateValue } from './StateProvider'; import BoughtPage from './Pages/BoughtPage'; import Demo from './Pages/Demo'; function App() { const [{ user }, dispatch] = useStateValue(); useEffect(() => { const unsubscribe = auth.onAuthStateChanged((authUser) => { if (authUser) { dispatch({ type: 'SET_USER', user: authUser, }); } else { dispatch({ type: 'SET_USER', user: null, }); } }); return () => { unsubscribe(); }; }, []); return ( <Router> <ScrollToTop /> <div className="app"> <Header /> <Switch> {/* Other Pages */} <Route path="/cart"> <CartPage /> </Route> <Route path="/login"> <LoginPage /> </Route> <Route path="/payment"> <PaymentPage /> </Route> <Route path="/product"> <ProductPage /> </Route> <Route path="/profile"> <ProfilePage /> </Route> <Route path="/register"> <Register /> </Route> <Route path="/search"> <SearchPage /> </Route> <Route path="/bought"> <BoughtPage /> </Route> <Route path="/demo"> <Demo /> </Route> {/* Home */} <Route path="/"> <div className="app__homePage"> <div className="app__body"> <Categories /> <Slider /> <WorthSeeing /> <Login /> <Choosen id="432" imgUrl="https://www.komputronik.pl/informacje/wp-content/uploads/2020/03/ps5_premiera.jpg" discount="-20%" oldPrice="2499,99 zł" price={1999} description="Playstation 5" /> </div> <Add imgUrl="https://a.allegroimg.com/original/128847/ac7639004c2ca4c582f001ed20fc" /> <div className="app__products"> <Occassions /> <Hits /> <FourProducts /> <ProductsCategories /> </div> <OcassionsForYou title="Okazje dla Ciebie" /> <Promo imgUrl={PromoImg} /> <WinterRow /> <Add imgUrl="https://a.allegroimg.com/original/1203c9/ce3dc4834e7b95ce9b768dd049b1" /> <FashionRow /> <MotoRow /> <ElectronicsRow /> <Promo imgUrl={SolarPower} /> <Banner /> <Footer /> </div> </Route> </Switch> </div> </Router> ); } export default App; <file_sep>import React from 'react'; import './WinterRow.css'; import Product from './Product'; function WinterRow() { return ( <div className="winterRow"> <p>Zimowe szaleństwo</p> <div className="winterRow__container"> <Product imgUrl="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSRSlDwgpe6lmxcgNqFkOaU2YoZz39iRfSUWg&usqp=CAU" discount="-33%" oldPrice="2999,99 zł" price={1999.99} description="Narty Nowe Fischer" /> <Product imgUrl="https://ski4you.pl/wp-content/uploads/2018/10/buty-narciarskie-head-vector-rs-130-s-2019.jpg" discount="-25%" oldPrice="1999,99 zł" price={1499.99} description="Buty narciarskie Head" /> <Product imgUrl="https://ridestore.imgix.net/catalog/product//d/s/dsc03866-2_3.jpg?fit=max&q=90&dpr=1&usm=15&auto=format&w=589" discount="-50%" oldPrice="999,99 zł" price={499.99} description="Bluza snowboardowa Dope" /> <Product imgUrl="https://www.zawojski.pl/dane/source/a/api1ac61a366b6b446983ebbbd2b76f1971.jpg" discount="-25%" oldPrice="999,99 zł" price={749.99} description="Kask Redbull Małysz Morgenstern " /> <Product imgUrl="https://www.sportmoda.pl/45128-large_default/reusch-rekawice-narciarskie-henrik-kristoffersen.jpg" discount="-40%" oldPrice="199,99 zł" price={119.99} description="Rękawice narciarskie Reusch" /> </div> </div> ); } export default WinterRow; <file_sep>import React from 'react'; import './Demo.css'; function Demo() { return ( <div className="demo"> <h1> To jest klon platformy allegro, zrobiony na potrzeby prywatnego projektu. Dana usługa jest niedostępna. </h1> </div> ); } export default Demo;
c37e94ca1068a024c24ba1f16739d435d310f399
[ "JavaScript" ]
30
JavaScript
Kacper-Hernacki/allegro-clone
fbacc8f6c7d0550f16e798492a02df151375bf05
c1f106822091b22ab8fc6e202c44ab87ff99f5ff
refs/heads/master
<repo_name>jsardinha/intro_cpp<file_sep>/README.md intro_cpp ========= <file_sep>/population.cc #include <iostream> #include <iomanip> // pour setprecision() #include <cmath> // pour exp() using namespace std; int main() { // réduire le format d'affichage cout << setprecision(4); constexpr double population_initiale(7.0); // population initiale, en milliard d'humains constexpr int annee_depart(2011); // année initiale double taux(1.2); // taux de croissance, en % int annee(annee_depart); // année de calcul double population(population_initiale); // population mondiale pour l'année 'annee' cout << "====---- PARTIE 1 ----====" << endl; cout << "Population en " << annee << " : " << population << endl; /***************************************************** * Compléter le code à partir d'ici *****************************************************/ // ===== PARTIE 1 ===== do { cout << "Quelle année (> 2011 ?) "; cin >> annee; } while (annee <= annee_depart); population = population * exp((annee - annee_depart) * (taux / 100)); cout << "Population en " << annee << " : " << population << endl; // ===== PARTIE 2 ===== cout << endl << "====---- PARTIE 2 ----====" << endl; double cible(0.0); do { cout << "Combien de milliards (> " << population_initiale << ") ? "; cin >> cible; } while ( cible <= population_initiale); population = population_initiale; for (int i(annee_depart + 1); population <= cible ; ++i) { population = population_initiale * exp((i - annee_depart) * (taux / 100)); cout << "Population en " << i << " : " << population << endl; } // ===== PARTIE 3 ===== cout << endl << "====---- PARTIE 3 ----====" << endl; population = population_initiale; annee = annee_depart; double population_init(population); double population_double(population_initiale * 2.0); for (int i(annee + 1); population <= cible; ++i) { population = population_init * exp((i - annee) * (taux / 100)); if (population >= population_double) { annee = i; population_init = population; population_double *= 2; taux = taux /2.0; } cout << "Population en " << i << " : " << population << " ; " << "taux de croissance : " << taux << " %" << endl; } /******************************************* * Ne rien modifier après cette ligne. *******************************************/ return 0; } <file_sep>/population.cpp #include <iostream> #include <iomanip> // pour setprecision() #include <cmath> // pour exp() using namespace std; int main() { // réduire le format d'affichage cout << setprecision(4); constexpr double population_initiale(7.0); // population initiale, en milliard d'humains constexpr int annee_depart(2011); // année initiale double taux(1.2); // taux de croissance, en % int annee(annee_depart); // année de calcul double population(population_initiale); // population mondiale pour l'année 'annee' cout << "====---- PARTIE 1 ----====" << endl; cout << "Population en " << annee << " : " << population << endl; /***************************************************** * Compléter le code à partir d'ici *****************************************************/ // ===== PARTIE 1 ===== // ===== PARTIE 2 ===== cout << endl << "====---- PARTIE 2 ----====" << endl; // ===== PARTIE 3 ===== cout << endl << "====---- PARTIE 3 ----====" << endl; /******************************************* * Ne rien modifier après cette ligne. *******************************************/ return 0; }
0593f119c36e6801e1d55caafa84e4c6b5c40f8e
[ "Markdown", "C++" ]
3
Markdown
jsardinha/intro_cpp
af3db244942c0b71d5168635b27f8bcabb5f731b
07e40e026e3c658ca173fc220681f9ab6e5ad325
refs/heads/main
<repo_name>Tielinen/alien-invasion<file_sep>/screen_functions.js export function updateScreen(screen, button, settings, ship, aliens, bullets) { clearScreen(screen); screen.scoreBoard.draw(settings, screen, ship); ship.draw(screen); aliens.forEach(function(alien) { alien.draw(screen); }); bullets.forEach(function(bullet) { bullet.draw(screen); }); button.toggle(settings); toggleCursor(screen, settings); } function clearScreen(screen) { screen.context.fillStyle = screen.bgColor; screen.context.fillRect( 0, 0, screen.width, screen.height); }; function toggleCursor(screen, settings) { if (settings.gameStats.gameActive === true) screen.style.cursor = 'none'; else screen.style.cursor = 'auto'; }; <file_sep>/game_functions.js 'use strict'; import * as jtGame from './jt_game.js'; import * as af from './alien_functions.js'; import {Bullet} from './bullet.js'; export function updateBullets(settings, bullets) { bullets.forEach(function(bullet, index) { bullet.update(settings, bullets, index); }); } export function fireBullet(settings, ship, bullets) { if (isBulletAllowed(settings, bullets)) { bullets.push(new Bullet(settings, ship)); } } function isBulletAllowed(settings, bullets) { return bullets.length < settings.bullet.allowed && settings.gameStats.gameActive === true; } export function processHits(screen, ship, bullets, aliens) { if (jtGame.isHit(bullets, aliens)) { jtGame.tagHits(bullets, aliens); countScores(screen, ship, aliens); jtGame.removeHits(bullets, aliens); } } export function processFleet(settings, screen, ship, bullets, aliens) { if (aliens.length === 0) settings.levelUp(); if (jtGame.isHit([ship], aliens) || af.isAlienBottom(screen, aliens)) { alienHitShip(settings, screen, ship, bullets, aliens); }; } function countScores(screen, ship, aliens) { aliens.forEach(function(alien) { if (alien.isHit) { screen.scoreBoard.score = Math.round( screen.scoreBoard.score + alien.points, ); screen.scoreBoard.updateHiScore(); } } ); } function alienHitShip(settings, screen, ship, bullets, aliens) { if (settings.gameStats.ships > 1) { newShip(settings, screen, ship, bullets, aliens); } else { resetGame(settings, screen, ship, bullets, aliens); } } function newShip(settings, screen, ship, bullets, aliens) { settings.gameStats.ships -= 1; clearBullets(bullets); af.clearAliens(aliens); ship.center(screen); af.updateAliensFleet(settings, screen, ship, aliens); jtGame.sleep(1000); } function resetGame(settings, screen, ship, bullets, aliens) { settings.gameStats.gameActive = false; settings.gameStats.ships = settings.ship.count; ship.center(screen); clearBullets(bullets); af.clearAliens(aliens); settings.resetSpeed(); af.updateAliensFleet(settings, screen, ship, aliens); jtGame.sleep(1000); // Button event listener resets score and level. } function clearBullets(bullets) { bullets.length = 0; } <file_sep>/jt_game.js 'use strict'; export function getRect(soucre) { return { x: 0, y: 0, width: soucre.width, height: soucre.height, // sides get top() { return this.y; }, set top(value) { this.y = value; }, get right() { return this.x + this.width; }, set right(value) { this.x = value - this.length; }, get bottom() { return this.y + this.height; }, set bottom(value) { this.y = value - this.height; }, get left() { return this.x; }, set left(value) { this.x = value; }, // center get centerX() { return this.x + (this.width /2); }, set centerX(value) { this.x = value - (this.width /2); }, get centerY() { return this.y + (this.height /2); }, set centerY(value) { this.y = value - (this.height /2); }, get center() { return [this.centerX, this.centerY]; }, set center(valuesXY) { this.x = valuesXY[0] - (this.width /2); this.y = valuesXY[1] - (this.height /2); }, get edges() { const topEdge = []; for (let x = this.left; x < this.right; x++) { topEdge.push([x, this.top]); } const rightEdge = []; for (let y = this.top; y < this.bottom; y++) { rightEdge.push([this.right, y]); } const bottomEdge = []; for (let x = this.left; x < this.right; x++) { topEdge.push([x, this.bottom]); } const leftEdge = []; for (let y = this.top; y < this.bottom; y++) { rightEdge.push([this.left, y]); } return [...topEdge, ...rightEdge, ...bottomEdge, ...leftEdge]; }, }; }; export function tagHits(objects1, objects2) { objects1.forEach(function(object1, object1Index) { objects2.forEach(function(object2, object2Index) { if (isCollision(object1, object2)) { object1.isHit = true; object2.isHit = true; } }); } ); } export function removeHits(...arrays) { arrays.forEach(function(objects) { const objectsCopy = [...objects]; objects.length = 0; objectsCopy.forEach(function(object) { if (object.isHit === false) { objects.push(object); } }); }); } export function isCollision(object1, object2) { return ( object1.rect.left <= object2.rect.right && object1.rect.right >= object2.rect.left && object1.rect.top <= object2.rect.bottom && object1.rect.bottom >= object2.rect.top ); } export function isHit(objects1, objects2) { return objects1.some(function(object1) { return objects2.some(function(object2) { return isCollision(object1, object2); }); }); } export function sleep(milliseconds) { const date = Date.now(); let currenDate = null; do { currenDate = Date.now(); } while (currenDate - date < milliseconds); } <file_sep>/main.js /* *** TODOS *** |1| relearn this, arrow functions. |2| Learn async. |3| relearn classes. || Wait until images are loaded. || style button || rect to object || can context be in every class? || empty lines after functions. || let user choose window size || delete zip from github */ /* eslint-disable no-unused-vars */ 'use strict'; import * as gf from './game_functions.js'; import * as af from './alien_functions.js'; import * as sf from './screen_functions.js'; import {Ship} from './ship.js'; import {Settings} from './settings.js'; import {initScreen} from './screen.js'; import {initButton} from './button.js'; import {eventListeners} from './event_listeners.js'; function runGame() { // Load images // Initialize settings and screen object. const settings = new Settings; const screen = initScreen(settings); const button = initButton(screen); // Make a ship, a array of bullets and a array for aliens. const ship = new Ship(settings, screen); const bullets = []; const aliens = []; // Create fleet of aliens. af.createFleet(settings, screen, aliens); // Check events eventListeners(screen, settings, ship, bullets); // Start the main loop for the game. window.setInterval(function() { sf.updateScreen(screen, button, settings, ship, aliens, bullets); if (settings.gameStats.gameActive === true) { ship.update(settings, screen); af.updateAliensFleet(settings, screen, ship, aliens); gf.updateBullets(settings, bullets, aliens); gf.processHits(screen, ship, bullets, aliens); gf.processFleet(settings, screen, ship, bullets, aliens); } }, 1/100); }; runGame(); <file_sep>/settings.js 'use strict'; export class Settings { // A class to store all settings for Alien Invasion. constructor() { // Sreen settings this.speedUpScale = 1.1, this.screen = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, bgColor: 'rgb(230, 230, 230)', textColor: 'rgb(30, 30, 30)', fontSize: 36, font: 'Gugi', }; // Ships settings this.ship = { startSpeed: 1, count: 3, }; // Alien settings this.alien = { startSpeed: 1.0, dropSpeed: 10, direction: 1, points: 50, pointsScale: 1.1, }; // Bullet settings this.bullet = { startSpeed: 3, allowed: 3, width: 3, height: 15, color: 'rgb(60, 60, 60)', }; this.gameStats = { gameActive: false, level: 1, ships: this.ship.count, }; this.resetSpeed(); } speedUp() { this.ship.speedFactor *= 1.1; this.bullet.speedFactor *= 1.1; this.alien.speedFactor *= 1.15; this.alien.points *= this.alien.pointsScale; } resetSpeed() { this.ship.speedFactor = this.ship.startSpeed; this.bullet.speedFactor = this.bullet.startSpeed; this.alien.speedFactor = this.alien.startSpeed; } levelUp() { this.gameStats.level++; this.speedUp(); } } <file_sep>/screen.js import * as jtGame from './jt_game.js'; import {ScoreBoard} from './scoreboard.js'; export function initScreen(settings) { const screen = document.querySelector('.js-screen'); // Settings Object.entries(settings.screen).forEach(function(setting) { screen[setting[0]] = setting[1]; }, ); screen.setAttribute('width', screen.width); screen.setAttribute('height', screen.height); screen.context = screen.getContext('2d'); screen.rect = jtGame.getRect(screen); screen.scoreBoard = new ScoreBoard(settings); screen.button = document.querySelector('.js-button'); return screen; } <file_sep>/bullet.js 'use strict'; import * as jtGame from './jt_game.js'; export class Bullet { // A class to manage bullets fired from ship. constructor(settings, ship) { // Bullet settings Object.entries(settings.bullet).forEach((setting) => { this[setting[0]] = setting[1]; this.isHit = false; }, ); // create bullet rect at (0,0) and then set correct position. this.rect = jtGame.getRect(this); this.rect.centerX = ship.rect.centerX; this.rect.bottom = ship.rect.top; } draw(screen) { // Draw the bullet up to the screen screen.context.fillStyle = this.color; screen.context.fillRect( this.rect.x, this.rect.y, this.width, this.height); }; update(settings, bullets, index) { // Move the bullet up the screen. this.rect.y -= settings.bullet.speedFactor; // remove bullets that are out of screen. if (this.rect.bottom <= 0) { bullets.splice(index, 1); } }; } <file_sep>/scoreboard.js import * as jtGame from './jt_game.js'; export class ScoreBoard { constructor() { this.score = 0; this.hiScore = 0; } draw(settings, screen, ship) { // common screen.context.fillStyle = screen.textColor; screen.context.font = `${screen.fontSize}px ${screen.font}`, this.drawScore(screen); this.drawHiScore(screen); this.drawLevel(settings, screen); this.drawShips(settings, screen, ship); } drawScore(screen) { this.getTextSize(screen, this.score); screen.context.fillText( this.text, screen.rect.right -this.rect.right -20, 50, ); } drawHiScore(screen) { this.getTextSize(screen, this.hiScore); this.rect.centerX = screen.rect.centerX; screen.context.fillText( this.text, this.rect.centerX, 50, ); } drawLevel(settings, screen) { this.getTextSize(screen, settings.gameStats.level); screen.context.fillText( this.text, screen.rect.right -this.rect.right -20, screen.fontSize + 65, ); } getTextSize(screen, text) { this.text = text.toLocaleString(); this.width = screen.context.measureText(this.text).width; this.rect = jtGame.getRect(this); } drawShips(settings, screen, ship) { for (let count = 1; count < settings.gameStats.ships; count++) { const x = ship.rect.width * count -1; screen.context.drawImage(ship.image, x, 0); } } updateHiScore() { if (this.score >= this.hiScore) this.hiScore = this.score; } } <file_sep>/event_listeners.js import {fireBullet} from './game_functions.js'; export function eventListeners(screen, settings, ship, bullets) { document.addEventListener('keydown', (event) => { // Move the ship to right. if (event.key === 'ArrowRight') { ship.movingRight = true; } // Move the ship to left. if (event.key === 'ArrowLeft') { ship.movingLeft = true; } // Fire bullet if (event.key === ' ' ) { fireBullet(settings, ship, bullets); } if (event.key === 'p') { } }); document.addEventListener('keyup', (event) => { // Stop moving the ship to right. if (event.key === 'ArrowRight') { ship.movingRight = false; } // Stop moving the ship to left. if (event.key === 'ArrowLeft') { ship.movingLeft = false; } }); document.addEventListener('touchstart', (event) => { if (event.touches[0].screenX > ship.rect.centerX) ship.movingRight = true; if (event.touches[0].screenX < ship.rect.centerX) ship.movingLeft = true; ship.screenX = event.touches[0].screenX; if (event.touches.length > 1) fireBullet(settings, ship, bullets); console.log(event.touches.length); }); document.addEventListener('touchend', (event) => { if (event.touches.length === 0) { ship.movingRight = false; ship.movingLeft = false; } }); screen.button.addEventListener('click', () => { screen.scoreBoard.score = 0; settings.gameStats.gameActive = true; settings.gameStats.level = 1; }); } <file_sep>/ship.js 'use strict'; import * as jtGame from './jt_game.js'; export class Ship { constructor(settings, screen) { // Initialize the ship and set its starting position. // Load the ship image and get its rect this.image = this.image = document.getElementById('js-ship-img'); this.rect = jtGame.getRect(this.image); // Start each new ship at the bottom center of the screen. this.rect.bottom = screen.rect.bottom; this.rect.centerX = screen.rect.centerX; // Movement flags this.movingRight = false; this.movingLeft = false; this.isHit = false; } draw(screen) { screen.context.drawImage(this.image, this.rect.x, this.rect.y); }; update(settings, screen) { // Update ships position based on movement flag. // Move right if can console.log(this.screenX); if (this.rect.right >= screen.width || this.rect.centerX > this.screenX) { this.movingRight = false; } if (this.movingRight) { this.rect.x += settings.ship.speedFactor; } // Move left if (this.rect.left <= 0 || this.rect.centerX < this.screenX) { this.movingLeft = false; } if (this.movingLeft) { this.rect.x -= settings.ship.speedFactor; } } center(screen) { this.rect.centerX = screen.rect.centerX; } } <file_sep>/alien.js 'use strict'; import * as jtGame from './jt_game.js'; export class Alien { constructor(settings) { // Initialize the aliens and set its starting position. // Alien settings Object.entries(settings.alien).forEach((setting) => { this[setting[0]] = setting[1]; }, ); // Load the alien image an set it's rect attribute. this.image = document.getElementById('js-alien-img'); this.rect = jtGame.getRect(this.image); // Start each new alien near at the top left of of the screen. this.rect.x = this.rect.width; this.rect.y = this.rect.height; this.isHit = false; } draw(screen) { screen.context.drawImage(this.image, this.rect.x, this.rect.y); }; update(settings) { // Move alien right this.rect.x += settings.alien.speedFactor * this.direction; } checkEdges(settings) { return this.rect.right >= settings.screen.width || this.rect.left <= 0; } changeDirection() { this.direction *= -1; this.rect.y += this.dropSpeed; }; }
2947e0ab5d224120544021c132ba174e243b6925
[ "JavaScript" ]
11
JavaScript
Tielinen/alien-invasion
835adb0408591e8f1614bd84b262c8bdd56dadf0
0fb08f3f82b390c02335becdaa821dee163ecfa6
refs/heads/master
<repo_name>VulilnM/IT80g2017-DO-Projekat<file_sep>/IT 80-2017 Milan Vulin/src/drawing/DlgLine.java package drawing; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JPanel; import geometry.Line; import geometry.Point; import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class DlgLine extends JDialog { private JTextField txtFirstX; private JTextField txtFirstY; private JTextField txtSecondX; private JTextField txtSecondY; private Line line = null; private Color edgeColor = null, innerColor = null; /** * Create the dialog. */ public DlgLine() { setResizable(false); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setModal(true); setBounds(100, 100, 300, 210); setLocationRelativeTo(null); getContentPane().setLayout(new BorderLayout(0, 0)); { JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(new GridLayout(5, 2, 0, 0)); { JLabel lblNewLabel_1 = new JLabel("Prva X koordinata", SwingConstants.CENTER); panel.add(lblNewLabel_1); } { txtFirstX = new JTextField(); panel.add(txtFirstX); txtFirstX.setColumns(10); } { JLabel lblNewLabel = new JLabel("Prva Y koordinata"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); panel.add(lblNewLabel); } { txtFirstY = new JTextField(); panel.add(txtFirstY); txtFirstY.setColumns(10); } { JLabel lblNewLabel_2 = new JLabel("Druga X koordinata"); lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER); panel.add(lblNewLabel_2); } { txtSecondX = new JTextField(); panel.add(txtSecondX); txtSecondX.setColumns(10); } { JLabel lblNewLabel_2 = new JLabel("Druga Y koordinata"); lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER); panel.add(lblNewLabel_2); } { txtSecondY = new JTextField(); panel.add(txtSecondY); txtSecondY.setColumns(10); } { JButton btnEdgeColor = new JButton("Boja ivice"); btnEdgeColor.setHorizontalAlignment(SwingConstants.CENTER); btnEdgeColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { edgeColor = JColorChooser.showDialog(null, "Izaberite boju ivice", edgeColor); if (edgeColor == null) edgeColor = Color.BLACK; } }); panel.add(btnEdgeColor); } { JButton btnInnerColor = new JButton("Boja unutrasnjosti"); btnInnerColor.setHorizontalAlignment(SwingConstants.CENTER); btnInnerColor.setEnabled(false); panel.add(btnInnerColor); } } { JPanel panel = new JPanel(); getContentPane().add(panel, BorderLayout.SOUTH); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); { JButton btnOk = new JButton("Potvrdi"); btnOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int newFirstX = Integer.parseInt(txtFirstX.getText()); int newFirstY = Integer.parseInt(txtFirstY.getText()); int newSecondX = Integer.parseInt(txtSecondX.getText()); int newSecondY = Integer.parseInt(txtSecondY.getText()); if(newFirstX < 0 || newFirstY < 0 || newSecondX < 0 || newSecondY < 0) { JOptionPane.showMessageDialog(null, "Uneli ste pogresne podatke!", "Greska!", JOptionPane.ERROR_MESSAGE); return; } line = new Line(new Point(newFirstX, newFirstY), new Point(newSecondX, newSecondY), edgeColor); dispose(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Uneli ste pogresne podatke!", "Greska!", JOptionPane.ERROR_MESSAGE); } } }); panel.add(btnOk); } { JButton btnNotOk = new JButton("Odustani"); btnNotOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); panel.add(btnNotOk); } } } public Line getLine() { return line; } public void setLine(Line line) { txtFirstX.setText("" + line.getStartPoint().getX()); txtFirstY.setText("" + line.getStartPoint().getY()); txtSecondX.setText("" + line.getEndPoint().getX()); txtSecondY.setText("" + line.getEndPoint().getY()); edgeColor = line.getEdgeColor(); } } <file_sep>/IT 80-2017 Milan Vulin/src/drawing/FrmDrawing.java package drawing; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToggleButton; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.border.TitledBorder; import drawing.DlgCircle; import drawing.DlgDonut; import drawing.DlgLine; import drawing.DlgPoint; import drawing.DlgRectangle; import geometry.Circle; import geometry.Donut; import geometry.Line; import geometry.Point; import geometry.Rectangle; import geometry.Shape; import stack.DlgStack; import javax.swing.UIManager; import java.awt.Color; import java.awt.Dimension; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import java.awt.Component; import javax.swing.border.LineBorder; import java.awt.SystemColor; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.awt.Cursor; public class FrmDrawing extends JFrame { private final int OPERATION_DRAWING = 1; private final int OPERATION_EDIT_DELETE = 0; private int activeOperation = OPERATION_DRAWING; private PnlDrawing pnlDrawing = new PnlDrawing(); private ButtonGroup btnsOperation = new ButtonGroup(); private ButtonGroup btnsShapes = new ButtonGroup(); private JToggleButton btnOperationDrawing = new JToggleButton("Crtanje"); private JToggleButton btnOperationEditOrDelete = new JToggleButton("Selektuj"); private JButton btnActionEdit = new JButton("Izmeni"); private JButton btnActionDelete = new JButton("Obrisi"); private JToggleButton btnShapePoint = new JToggleButton("Tacka"); private JToggleButton btnShapeLine = new JToggleButton("Linija"); private JToggleButton btnShapeRectangle = new JToggleButton("Pravougaonik"); private JToggleButton btnShapeCircle = new JToggleButton("Krug"); private JToggleButton btnShapeDonut = new JToggleButton("Krofna"); private JButton btnColorEdge = new JButton("Boja linije"); private JButton btnColorInner = new JButton("Boja unutrasnjosti"); private Color edgeColor = Color.BLACK, innerColor = Color.WHITE; private boolean lineWaitingForSecondPoint = false; private Point lineFirstPoint; private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FrmDrawing frame = new FrmDrawing(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public FrmDrawing() { setTitle("IT-80/2017"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1100, 700); setLocationRelativeTo(null); setMinimumSize(new Dimension(1100, 700)); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(0, 0, 0, 0)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); pnlDrawing.addMouseListener(pnlDrawingClickListener()); contentPane.add(pnlDrawing, BorderLayout.CENTER); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.WEST); panel_1.setLayout(new GridLayout(4, 0, 0, 0)); JPanel panel_2 = new JPanel(); panel_1.add(panel_2); panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.Y_AXIS)); btnOperationDrawing.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setOperationDrawing(); } }); btnOperationDrawing.setAlignmentX(Component.CENTER_ALIGNMENT); btnsOperation.add(btnOperationDrawing); panel_2.add(btnOperationDrawing); btnOperationEditOrDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setOperationEditDelete(); } }); btnOperationEditOrDelete.setAlignmentX(Component.CENTER_ALIGNMENT); btnsOperation.add(btnOperationEditOrDelete); panel_2.add(btnOperationEditOrDelete); JPanel panel_3 = new JPanel(); panel_1.add(panel_3); btnActionEdit.addActionListener(btnActionEditClickListener()); btnActionEdit.setAlignmentX(Component.CENTER_ALIGNMENT); panel_3.add(btnActionEdit); btnActionDelete.addActionListener(btnActionDeleteClickListener()); btnActionDelete.setAlignmentX(Component.CENTER_ALIGNMENT); panel_3.add(btnActionDelete); JPanel panel_4 = new JPanel(); panel_1.add(panel_4); panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.Y_AXIS)); btnShapePoint.setAlignmentX(Component.CENTER_ALIGNMENT); btnsShapes.add(btnShapePoint); panel_4.add(btnShapePoint); btnShapeLine.setAlignmentX(Component.CENTER_ALIGNMENT); btnsShapes.add(btnShapeLine); panel_4.add(btnShapeLine); btnShapeRectangle.setAlignmentX(Component.CENTER_ALIGNMENT); btnsShapes.add(btnShapeRectangle); panel_4.add(btnShapeRectangle); btnShapeCircle.setAlignmentX(Component.CENTER_ALIGNMENT); btnsShapes.add(btnShapeCircle); panel_4.add(btnShapeCircle); btnShapeDonut.setAlignmentX(Component.CENTER_ALIGNMENT); btnsShapes.add(btnShapeDonut); panel_4.add(btnShapeDonut); btnOperationDrawing.setSelected(true); setOperationDrawing(); btnShapePoint.setSelected(true); JPanel panel_5 = new JPanel(); panel_1.add(panel_5); btnColorEdge = new JButton("Boja ivice"); btnColorEdge.addActionListener(btnColorEdgeClickListener()); btnColorEdge.setAlignmentX(Component.CENTER_ALIGNMENT); panel_5.add(btnColorEdge); btnColorInner = new JButton("Boja unutrasnjosti"); btnColorInner.addActionListener(btnColorInnerClickListener()); btnColorInner.setAlignmentX(Component.CENTER_ALIGNMENT); panel_5.add(btnColorInner); } private MouseAdapter pnlDrawingClickListener() { return new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Point mouseClick = new Point(e.getX(), e.getY()); pnlDrawing.deselect(); if (!btnShapeLine.isSelected()) lineWaitingForSecondPoint = false; if (activeOperation == OPERATION_EDIT_DELETE) { pnlDrawing.select(mouseClick); return; } if (btnShapePoint.isSelected()) { pnlDrawing.addShape(new Point(mouseClick.getX(), mouseClick.getY(), edgeColor)); return; } else if (btnShapeLine.isSelected()) { if (lineWaitingForSecondPoint) { pnlDrawing.addShape(new Line(lineFirstPoint, mouseClick, edgeColor)); lineWaitingForSecondPoint = false; return; } lineFirstPoint = mouseClick; lineWaitingForSecondPoint = true; return; } else if (btnShapeRectangle.isSelected()) { DlgRectangle dlgRectangle = new DlgRectangle(); dlgRectangle.setPoint(mouseClick); dlgRectangle.setColors(edgeColor, innerColor); dlgRectangle.setVisible(true); if(dlgRectangle.getRectangle() != null) pnlDrawing.addShape(dlgRectangle.getRectangle()); return; } else if (btnShapeCircle.isSelected()) { DlgCircle dlgCircle = new DlgCircle(); dlgCircle.setPoint(mouseClick); dlgCircle.setColors(edgeColor, innerColor); dlgCircle.setVisible(true); if(dlgCircle.getCircle() != null) pnlDrawing.addShape(dlgCircle.getCircle()); return; } else if (btnShapeDonut.isSelected()) { DlgDonut dlgDonut = new DlgDonut(); dlgDonut.setPoint(mouseClick); dlgDonut.setColors(edgeColor, innerColor); dlgDonut.setVisible(true); if(dlgDonut.getDonut() != null) pnlDrawing.addShape(dlgDonut.getDonut()); return; } } }; } private ActionListener btnActionEditClickListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { int index = pnlDrawing.getSelected(); if (index == -1) return; Shape shape = pnlDrawing.getShape(index); if (shape instanceof Point) { DlgPoint dlgPoint = new DlgPoint(); dlgPoint.setPoint((Point)shape); dlgPoint.setVisible(true); if(dlgPoint.getPoint() != null) { pnlDrawing.setShape(index, dlgPoint.getPoint()); pnlDrawing.repaint(); } } else if (shape instanceof Line) { DlgLine dlgLine = new DlgLine(); dlgLine.setLine((Line)shape); dlgLine.setVisible(true); if(dlgLine.getLine() != null) { pnlDrawing.setShape(index, dlgLine.getLine()); pnlDrawing.repaint(); } } else if (shape instanceof Rectangle) { DlgRectangle dlgRectangle = new DlgRectangle(); dlgRectangle.setRectangle((Rectangle)shape); dlgRectangle.setVisible(true); if(dlgRectangle.getRectangle() != null) { pnlDrawing.setShape(index, dlgRectangle.getRectangle()); pnlDrawing.repaint(); } }else if (shape instanceof Donut) { DlgDonut dlgDonut = new DlgDonut(); dlgDonut.setDonut((Donut)shape); dlgDonut.setVisible(true); if(dlgDonut.getDonut() != null) { pnlDrawing.setShape(index, dlgDonut.getDonut()); pnlDrawing.repaint(); } } else if (shape instanceof Circle) { DlgCircle dlgCircle = new DlgCircle(); dlgCircle.setCircle((Circle)shape); dlgCircle.setVisible(true); if(dlgCircle.getCircle() != null) { pnlDrawing.setShape(index, dlgCircle.getCircle()); pnlDrawing.repaint(); } } } }; } private ActionListener btnActionDeleteClickListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { if (pnlDrawing.isEmpty()) return; if (JOptionPane.showConfirmDialog(null, "Da li zaista zelite da obrisete selektovane oblike?", "Potvrda", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) pnlDrawing.removeSelected(); } }; } private ActionListener btnColorEdgeClickListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { edgeColor = JColorChooser.showDialog(null, "Izaberite boju ivice", edgeColor); if (edgeColor == null) edgeColor = Color.BLACK; } }; } private ActionListener btnColorInnerClickListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { innerColor = JColorChooser.showDialog(null, "Izaberite boju unutrasnjosti", innerColor); if (innerColor == null) innerColor = Color.WHITE; } }; } private void setOperationDrawing() { activeOperation = OPERATION_DRAWING; pnlDrawing.deselect(); btnActionEdit.setEnabled(false); btnActionDelete.setEnabled(false); btnShapePoint.setEnabled(true); btnShapeLine.setEnabled(true); btnShapeRectangle.setEnabled(true); btnShapeCircle.setEnabled(true); btnShapeDonut.setEnabled(true); btnColorEdge.setEnabled(true); btnColorInner.setEnabled(true); } private void setOperationEditDelete() { activeOperation = OPERATION_EDIT_DELETE; btnActionEdit.setEnabled(true); btnActionDelete.setEnabled(true); btnShapePoint.setEnabled(false); btnShapeLine.setEnabled(false); btnShapeRectangle.setEnabled(false); btnShapeCircle.setEnabled(false); btnShapeDonut.setEnabled(false); btnColorEdge.setEnabled(false); btnColorInner.setEnabled(false); } }
bec2ed633372d202e302abf9acc50d3aa96aa2ce
[ "Java" ]
2
Java
VulilnM/IT80g2017-DO-Projekat
b77789e10db5644293baf93e32c7864cee8a8c5e
98c295e9146aba8eede7126be7cc5f5d24e6aa71
refs/heads/master
<repo_name>JamesWClark/Layouts-and-Pump-Fakes<file_sep>/sites/calculator/main.js ;(function() { var memory; var operator; var nextClear = false; var lcd = document.getElementById('main-panel'); var top = document.getElementById('top-panel'); var buttons = document.getElementsByClassName('numeric'); for(var i = 0; i < buttons.length; i++) { buttons[i].onclick = function() { if(nextClear) { lcd.innerHTML = '' + this.innerHTML; nextClear = false; } else { lcd.append(this.innerHTML); } }; } document.getElementById('clear').onclick = function() { lcd.innerHTML = ''; memory = null; }; document.getElementById('equals').onclick = function() { if(memory) { lcd.innerHTML = getResult(); top.innerHTML = ''; memory = null; nextClear = true; } }; var operators = document.getElementsByClassName('operator'); for(var i = 0; i < operators.length; i++) { operators[i].onclick = function() { operator = this.innerHTML; if(!memory) { memory = Number(lcd.innerHTML); lcd.innerHTML = ''; top.innerHTML = Number(memory) + ' ' + operator; } else { memory = null; } }; } function getResult() { var a = memory; var b = Number(lcd.innerHTML); switch(operator) { case '+': return a + b; case '-': return a - b; case 'x': return a * b; case '÷': return a / b; } } })();<file_sep>/sites/pandora/assets/scripts/main.js var music = []; var currentTrack = {}; var pausePlayState = 'play'; var songCount = 0; var updateProgress = function() { var currentTime = convertDuration(currentTrack.audio.currentTime); var endTime = convertDuration(currentTrack.audio.duration - currentTrack.audio.currentTime); $('#audio-progress').attr('value',currentTrack.audio.currentTime); $('#current-time').text(currentTime); $('#end-time').text('-' + endTime); }; //http://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript var convertDuration = function(seconds) { var h = parseInt(seconds / 3600 ) % 24; var m = parseInt(seconds / 60 ) % 60; var s = seconds % 60; s = Math.floor(s); return m + ":" + (s < 10 ? "0" + s : s); }; var nextTrack = function() { var data = music[songCount++]; currentTrack = data; $('.song-name').text(data.song); $('.artist-name').text(data.artist); $('.album-name').text(data.album); $('#album-mini-cover').attr('src', data.art); $('#album-covers').prepend('<div class="inline"><img class="album-cover" src="' + data.art + '"></div>'); if(!currentTrack.audio.duration) { currentTrack.audio.onloadedmetadata = function() { var time = convertDuration(currentTrack.audio.duration); $('#end-time').text(time); $('#audio-progress').attr('max', currentTrack.audio.duration); }; } else { var time = convertDuration(currentTrack.audio.duration); $('#end-time').text(time); $('#audio-progress').attr('max', currentTrack.audio.duration); } currentTrack.audio.play(); currentTrack.audio.ontimeupdate = updateProgress; currentTrack.audio.onended = nextTrack; }; var loadMusicData = function(csv) { var lines = csv.split(/\r\n|\n/); for(var i = 1; i < lines.length; i++) { var values = lines[i].split(','); var m = { song: values[0], artist: values[1], album: values[2], art: '/assets/albums/' + values[3], audio: new Audio('/assets/tracks/' + values[4]) }; music.push(m); } }; var init = function() { $.get('/data/music.csv', function(data) { loadMusicData(data); nextTrack(); }); $('#pause-play').click(function() { if(pausePlayState === 'play') { currentTrack.audio.pause(); pausePlayState = 'pause'; $('#pause-play > img').attr('src', '/assets/icons/btn_play.png'); } else { currentTrack.audio.play(); pausePlayState = 'play'; $('#pause-play > img').attr('src', '/assets/icons/btn_pause.png'); } }); $('#skip').click(function() { currentTrack.audio.pause(); currentTrack.audio.currentTime = 0; nextTrack(); }); }; $(document).ready(init);
1e5732db379432708aff98267efb2e7407399823
[ "JavaScript" ]
2
JavaScript
JamesWClark/Layouts-and-Pump-Fakes
2d03cd4d0875f75b0dc9cc53a713bce6cfbe3d63
0d0b5af6af470264a5e9bf10459f3fc34a1eef82
refs/heads/master
<repo_name>generation-alive/webapp-kinder-steckbrief-haiti<file_sep>/js/scripts.js /*jshint esversion: 6*/ import React from "react"; import ReactDOM from "react-dom"; import Layout from "./components/Layout"; const app = document.getElementById('app'); const button = document.getElementById('button'); loadJSON('data/children.json'); function loadJSON(file) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("application/json"); xobj.open('GET', file, true); xobj.onreadystatechange = function () { if (xobj.readyState == 4 && xobj.status == "200") { var data = JSON.parse(xobj.responseText); ReactDOM.render(<Layout data={data}/>, app); } }; xobj.send(null); } <file_sep>/js/components/steckbrief/Steckbrief.js /*jshint esversion: 6*/ import React from "react"; export default class Steckbrief extends React.Component { render() { var data = this.props.data; var asideImages = []; for (var i=0; i<data.pictures.length; i++) { asideImages[i] = <figure key={i} class="sb-aside__image"> <img src={data.pictures[i].url} alt={i} /> <figcaption>{data.pictures[i].figcaption}</figcaption> </figure>; } var style = { backgroundImage: "url('"+data.avatar+"')" }; if (data.gender === "male") { data.gender = "Junge"; if(data.pate.gender != "family") { data.possessivPronomen = "dein"; data.pronomen = "du"; data.verb = "kennenlernst"; } else { data.possessivPronomen = "euer"; data.pronomen = "ihr"; data.verb = "kennenlernt"; } } else if (data.gender === "female") { data.gender = "Mädchen"; if(data.pate.gender != "family") { data.possessivPronomen = "deine"; data.pronomen = "du"; data.verb = "kennenlernst"; } else { data.possessivPronomen = "eure"; data.pronomen = "ihr"; data.verb = "kennenlernt"; } } //var birthday = data.birthday.split("."); var birthday = ["1995"]; var theAge; if (birthday.length == 1) { theAge = new Date(birthday[0], 0, 0, 0, 0, 0, 0); } else { theAge = new Date(birthday[2], birthday[1], birthday[0], 0, 0, 0, 0); } var ageDifMs = Date.now() - theAge.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch data.theAge = Math.abs(ageDate.getUTCFullYear() - 1970); const hobbiesRendered = data.hobbies.map((hobby, index) => <span key={index}>{hobby}, </span> ); const familyRendered = data.family.map((member, index) => <span key={index}>{member},<br/></span> ); hobbiesRendered[hobbiesRendered.length-1] = <span key={data.hobbies.length-1}>{data.hobbies[data.hobbies.length-1]}</span>; familyRendered[familyRendered.length-1] = <span key={data.family.length-1}>{data.family[data.family.length-1]}</span>; return ( <article class="inv-invoice__paper"> <header class="sb2-header"> <section class="sb2-avatar"> <div class="sb2-avatar__img" style={style}> </div> <img src="gfx/v2/avatar_hefter.png" class="sb2-avatar__hefter" alt="Hefter" /> </section> <section class="sb2-headlines"> <h1>Hallo {data.pate.firstname}!</h1> <div class="introduction"> <p>Ich bin's, {data.possessivPronomen}</p> <h2>{data.name}<br/>{data.birthday}</h2> </div> </section> <img src="gfx/v2/header_pfeil.png" class="sb2-header__pfeil" alt="pfeil"/> </header> <main class="sb2-main"> <h3>Damit {data.pronomen} mich besser {data.verb}, möchte ich mich gerne vorstellen!</h3> <img src="gfx/v2/headline_pen.png" class="sb2-main__pen" alt="Pen" /> <div class="sb2-main__content"> <section class="sb2-main__steckbrief"> <h4 class="sb2-main__topic">Ich heiße:</h4> <p class="sb2-inline-data">{data.name}</p> <h4 class="sb2-main__topic">Ich bin heute:</h4> <p class="sb2-inline-data">{data.theAge} Jahre</p> <h4 class="sb2-main__topic">Meine Hobbys sind:</h4> <p class="sb2-inline-data">{hobbiesRendered}</p> <h4 class="sb2-main__topic">Das ist meine Familie:</h4> <p class="sb2-inline-data">{familyRendered}</p> <h4 class="sb2-main__topic">Das ist meine Schule:</h4> <p class="sb2-inline-data">{data.school.name} ({data.school.location})</p> </section> <section class="sb2-main__story"> <h4 class="sb2-main__topic">Was ich dir gerne erzählen möchte:</h4> <p class="sb2-text"> {data.information} </p> </section> <img src="gfx/v2/content_items.png" class="sb2-main__content-items" alt="Content-Items" /> </div> </main> <div class="sb2-donations"> <h2 class="sb2-donations__headline">GIVE HOPE -<br/>SHARE SMILE</h2> <span class="sb2-donations__mail"><EMAIL></span> <span class="sb2-donations__patenschaftsnummer">Patenschaftsnummer:</span> <span>{data.id}</span> </div> <footer class="sb2-footer"> <img src="gfx/v2/footer_logo.png" class="sb2-footer__logo" alt="Generation Alive" /> </footer> </article> ); } } <file_sep>/js/components/Layout.js /*jshint esversion: 6*/ import React from "react"; import Steckbriefe from "./steckbrief/Steckbriefe"; export default class Layout extends React.Component { render() { return ( <Steckbriefe data={this.props.data}/> ); } } <file_sep>/js/components/steckbrief/Steckbriefe.js /*jshint esversion: 6*/ import React from "react"; import Steckbrief from "./Steckbrief"; export default class Steckbriefe extends React.Component { render() { var steckbriefe = []; for (var i=0; i<this.props.data.length; i++) { steckbriefe[i] = <Steckbrief key={i} data={this.props.data[i]} />; } return ( <div> {steckbriefe} </div> ); } }
8dfd6a22dab70d5e6f82ff0f51b00c453c22fd9b
[ "JavaScript" ]
4
JavaScript
generation-alive/webapp-kinder-steckbrief-haiti
c7200f54550eb9c44fa2531c56b80a63457e81ff
76ebbe84e34886fd91426c77b79c64a8fe6bfe09
refs/heads/master
<file_sep>declare namespace CSS { export type PropertyDefinition = { name: string; syntax?: string; inherits: boolean; initialValue?: string; }; export function registerProperty(definition: PropertyDefinition): void; interface PaintWorklet { devicePixelRatio: number; registerPaint(name: string, factory: typeof Worklet): void; addModule(moduleUrl: string, options?: Request): Promise<void>; } export const paintWorklet: PaintWorklet; } type CSSUnit = "em" | "px" | "rem" | "deg" | "percent"; declare interface CSSUnitValue<Unit extends CSSUnit = CSSUnit> { value: number; unit: Unit; } declare interface CSSKeywordValue { value: string; toString(): string; } declare interface CSSStyleValue { toString(): string; } declare var CSSUnitValue: { new <T extends CSSUnit = CSSUnit>(value: number, unit: T): CSSUnitValue<T>; }; declare type CSSProperty = CSSUnitValue | CSSStyleValue | CSSKeywordValue; declare type CSS = { [key in CSSUnit]: (value: number) => CSSUnitValue<key>; }; declare function registerPaint(name: string, clz: Function): void; type PaintFunc = | "arc" | "arcTo" | "beginPath" | "bezierCurveTo" | "clearRect" | "clip" | "closePath" | "createLinearGradient" | "createPattern" | "drawImage" | "ellipse" | "fill" | "fillRect" | "fillStyle" | "filter" | "getLineDash" | "getTransform" | "globalAlpha" | "globalCompositeOperation" | "imageSmoothingEnabled" | "isPointInPath" | "isPointInStroke" | "lineCap" | "lineDashOffset" | "lineJoin" | "lineTo" | "lineWidth" | "miterLimit" | "moveTo" | "quadraticCurveTo" | "rect" | "resetTransform" | "restore" | "rotate" | "save" | "scale" | "setLineDash" | "setTransform" | "shadowBlur" | "shadowColor" | "shadowOffsetX" | "shadowOffsetY" | "stroke" | "strokeRect" | "strokeStyle" | "transform" | "translate"; // declare type PaintRenderingContext2D = typeof PaintRenderingContext2D; declare type PaintRenderingContext2D = { [key in PaintFunc]: CanvasRenderingContext2D[key]; }; // declare interface PaintRenderingContext2D extends CanvasRenderingContext2D {} declare var PaintRenderingContext2D: { prototype: PaintRenderingContext2D; new (): PaintRenderingContext2D; }; // declare class PaintRenderingContext2D implements PaintRenderingContext2D {} type ReadonlyPropertyMap< K extends string | number | symbol = string, V extends CSSProperty = CSSProperty > = { get(key: K): V; getAll(key: K): V[]; has(key: K): boolean; size: number; }; declare interface StylePropertyMap { size: number; append(property: string, value: string | CSSProperty): void; clear(): void; delete(property: string): void; set(property: string, value: string | CSSProperty): void; } declare interface HTMLElement { attributeStyleMap: StylePropertyMap; } <file_sep>import { Plugin } from "vite"; import { readdirSync, copyFileSync } from "fs"; export default (): Plugin => { let srcRoot = "./src"; let outRoot = "./dist"; return { name: "vite:global-declare-file-collector", apply: "build", enforce: "post", closeBundle() { readdirSync(srcRoot) .filter((file) => file.endsWith(".d.ts") && file !== "vite-env.d.ts") .forEach((file) => { copyFileSync(`${srcRoot}/${file}`, `${outRoot}/${file}`); }); }, }; }; <file_sep>import { define_properties } from "../../src"; import { IsKeywordValue, IsStyleValue } from "../../src/utils/properties-utils"; import { get_current_path } from "../../src/utils/url-utils"; export enum Properties { ROUND = "--lilith-test-round", NAME = "--lilith-test-name", COLOR = "--lilith-test-color", } export const properties = define_properties({ [Properties.ROUND]: { name: Properties.ROUND, inherits: false, }, [Properties.COLOR]: { name: Properties.COLOR, inherits: false, syntax: "<color>", initialValue: "#000", ...IsStyleValue, }, [Properties.NAME]: { name: Properties.NAME, inherits: false, ...IsKeywordValue, }, }); export function useTest() { (Reflect.ownKeys(properties) as (keyof typeof properties)[]).forEach( (key) => { console.log( `registrer property -> ${properties[key].name}: ${ (properties[key] as any).syntax }` ); CSS.registerProperty(properties[key]); } ); CSS.paintWorklet.addModule( `${get_current_path(import.meta.url)}/runner/test-runner.js` ); } <file_sep>type TrimStart<K extends string, P extends string> = K extends `${P}${infer R}` ? TrimStart<R, P> : K; type Replace<K extends string, S extends string, T extends string> = K extends `${infer L}${S}${infer R}` ? Replace<`${L}${T}${R}`, S, T> : K; type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never; <file_sep># LILITH-PAINTER --- ### WHAT LILITH-PAINTER is an easy tool for Paint API (Houdini APIs). Use this module to easy register paint and worklet with typescript. ### WHY When I ready to try Paint API with typescript, something is holding me back – Houdini APIs missing type definitions. I'm searching type definitions on `google`, `stack-overflow`, `github`and `npmjs` but never result. So I thought, why don't I write something to help myself? So, It's LILITH-PAINTER, declare Houdini APIs' type (in file `src/houdini.d.ts`) but not all, just a part of I will need. If you want other, welcome to complete the part that you need, thank you very much! *Ah, If anybody know where I can found the type definitions, say to me please.* ### HOW #### FOR USER 1. Install LILITH-PAINTER: ```sh npm install lilith-painter ``` 2. Use typescript, like this: ```typescript import { register, IsStyleValue } from "lilith-painter"; register( "lilith-transition", { name: "--lilith-transition-color", inherits: true, syntax: "<color>", initialValue: "#000", ...IsStyleValue, }, (ctx, geom, properties) => { // draw something... }); ``` And you can get this: ![image-20210617232633945](README.assets/image-20210617232633945.png) And other example in folder `example/` or see this repository: [LILITH-TRANSITION](https://github.com/juergenie/lilith-transition). #### FOR DEVELOPER 1. fork this repository 2. clone your fork to local 3. run: `cd lilith-transition` `yarn` `yarn dev` open web page: `http://127.0.0.1:4000` 4. build: `yarn build` 5. create a merge request, from your branch to this repository's preview branch and notify me with [mail](mailto://<EMAIL>), thanks 😀. ##### DEVELOPER TIPS - use project's default lint. - use kebab-case when you create file or style-class. - use snake_case when you create function or variable or parameter. <file_sep>export function get_current_path(source: string) { return source.substring(0, source.lastIndexOf("/")); } export async function get_text(url: string) { return await fetch(url).then((res) => res.text()); } <file_sep>import { PropertyDefinitions } from "./utils/properties-utils"; type ValueTypeMap = { is_style_value: CSSStyleValue; is_unit_value: CSSUnitValue; is_keyword_value: CSSKeywordValue; }; type MapToType<P extends CSS.PropertyDefinition, K extends keyof P = keyof P> = Extract<K, keyof ValueTypeMap> extends never ? CSSProperty : { [key in Extract<K, keyof ValueTypeMap>]: ValueTypeMap[key]; } extends { [key in Extract<K, keyof ValueTypeMap>]: infer R } ? R : never; type PropertyGetter< P extends PropertyDefinitions, K extends keyof P = keyof P > = { [key in K]: (k: key) => MapToType<P[key]>; }[K]; type Area = { width: number; height: number; }; export type PropertyMap< P extends PropertyDefinitions, K extends keyof P = keyof P > = { get: UnionToIntersection<PropertyGetter<P, K>> }; type PaintRunner<P extends PropertyDefinitions> = ( ctx: PaintRenderingContext2D, geom: Area, properties: PropertyMap<P> ) => void; export function register<P extends PropertyDefinitions>( name: string, properties: P, paint: PaintRunner<P> ) { const input_properties = Reflect.ownKeys(properties); const InnerClass = class { static get inputProperties() { return input_properties; } paint?: PaintRunner<P>; }; InnerClass.prototype.paint = paint; registerPaint(name, InnerClass); } <file_sep>/// <reference path="./global.d.ts" /> /// <reference path="./houdini.d.ts" /> import { register } from "./registry"; import * as url_utils from "./utils/url-utils"; import * as enum_utils from "./utils/enum-utils"; export { register, url_utils, enum_utils }; export * from "./utils/properties-utils"; <file_sep>import { defineConfig } from "vite"; import dts from "vite-plugin-dts"; import dfc from "./plugins/global-declare-file-collector"; import path from "path"; function resolve(...paths: string[]) { return path.resolve(__dirname, ...paths); } export default defineConfig({ server: { port: 4000, proxy: { // rewrite js request to ts request, for vite. "^((/src)|(/example))/.*\\.js(\\?.*)?": { target: "http://localhost:4000", rewrite(path) { console.log("rewrite", path, "->", path.replace(".js", ".ts")); return path.replace(".js", ".ts"); }, }, }, }, build: { lib: { entry: resolve("src/index.ts"), name: "LilithPainter", }, sourcemap: true, }, plugins: [ // generate type definitions file. dts({ compilerOptions: { noEmit: false, }, exclude: ["example"], beforeWriteFile(filePath: string, content: string) { if (filePath.startsWith(resolve("dist/src"))) { return { filePath: filePath.replace(resolve("dist/src"), resolve("dist")), content, }; } }, }), // copy global scope type definitions file. dfc(), ], }); <file_sep>console.log("init!"); import { register } from "../../../src"; import { Properties, properties } from "../test"; try { register("test-runner", properties, (ctx, geom, properties) => { console.log("paint!", geom, properties.get(Properties.COLOR)); const t = properties.get(Properties.COLOR); properties.get(Properties.NAME).value; ctx.fillStyle = t.toString(); ctx.fillRect(0, 0, geom.width, geom.height); }); } catch (e) { console.error(e); } <file_sep>import "./style.css"; import { useTest } from "./test/test"; useTest(); <file_sep>export type IsStyleValue = { is_style_value: boolean }; export const IsStyleValue = { is_style_value: true }; export type IsUnitValue = { is_unit_value: boolean }; export const IsUnitValue = { is_unit_value: true }; export type IsKeywordValue = { is_keyword_value: boolean }; export const IsKeywordValue = { is_keyword_value: true }; export type PropertyDefinitions<K extends string = string> = { [key in K]: CSS.PropertyDefinition; }; /** * support define properties, with typed-system. * @param input properties define. * @returns */ export function define_properties< P extends PropertyDefinitions<K>, K extends keyof P = keyof P >(input: P): P { return input as P; } export function register_properties(input: PropertyDefinitions) { Object.keys(input).forEach((key) => { CSS.registerProperty(input[key]); }); } // type AnalyzedProperty< // P extends PropertyDefinition<K>, // K extends keyof P = keyof P // > = { // [key in Replace<TrimStart<K, "--">, "-", "_">]: P[K] extends IsStyleValue & // IsUnitValue // ? CSSProperty // : P[K] extends IsStyleValue // ? CSSStyleValue // : CSSUnitValue; // }[Replace<TrimStart<K, "--">, "-", "_">]; // type AnalyzedProperties< // P extends PropertyDefinition<K>, // K extends keyof P = keyof P // > = { // [key in Replace<TrimStart<K, "--">, "-", "_">]: AnalyzedProperty<P, K>; // }; // export function analyze_properties< // P extends PropertyDefinition<K>, // M extends PropertyMap<P>, // K extends keyof P = keyof P // >(properties: M): AnalyzedProperties<P> { // const result = {} as any; // (Reflect.ownKeys(properties) as (keyof P)[]).forEach((key) => { // const property_name = key.substr(2).replace(/-/g, "_"); // const val = properties.get(key); // result[property_name] = { // source: val, // value: "value" in val ? val.value : val.toString(), // }; // }); // return result as AnalyzedProperties<P>; // } <file_sep>export function get_values(e: any): string[] { return Object.keys(e).map((key) => e[key]); }
877d6e8bf709595827e0eda909ce954349428893
[ "Markdown", "TypeScript" ]
13
TypeScript
JuerGenie/lilith-painter
f1933069c00631d883419622c081405b82d585c0
138e407521a8ae15dcbd1517a448b37749cac0a0
refs/heads/master
<file_sep>/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using strange.extensions.injector.api; using strange.extensions.listBind.api; using strange.framework.api; using strange.framework.impl; using System; using System.Collections.Generic; namespace strange.extensions.listBind.impl { public class ListBinding : Binding, IListBinding { private readonly List<IInjectionBinding> bindings = new List<IInjectionBinding>(); private readonly IInjectionBinder injectionBinder; public ListBinding(Binder.BindingResolver resolver, IInjectionBinder injectionBinder) : base(resolver) { this.injectionBinder = injectionBinder; } public Type ListType { get; set; } public Type ListItemType { get { return ListType.GetGenericArguments()[0]; } } public List<IInjectionBinding> Bindings { get { return this.bindings; } } public new IInjectionBinding To<T>() { var binding = injectionBinder.Bind(ListItemType).To<T>().ToName(typeof(T).ToString()); bindings.Add(binding); return binding; } public IInjectionBinding ToValue(object o) { var binding = injectionBinder.GetBinding(o.GetType(), o.ToString()); if (binding == null) { binding = injectionBinder.Bind(ListItemType).ToValue(o).ToName(o.ToString()); } bindings.Add(binding); return binding; } public IListBinding ToSingleton() { var listBinding = injectionBinder.GetBinding(ListType); listBinding.ToSingleton(); return this; } } } <file_sep>using NUnit.Framework; using strange.extensions.context.impl; using strange.extensions.listBind.api; using strange.extensions.listBind.impl; using System.Collections.Generic; namespace strange.unittests { [TestFixture] public class TestListBinder { private MockContext context; private IListBinder binder; private object contextView; [SetUp] public void SetUp() { Context.firstContext = null; contextView = new object(); context = new MockContext(contextView, true); context.Start(); binder = context.listBinder; } [Test] public void TestInjectListWithValues() { binder.Bind<string>().ToValue("a"); binder.Bind<string>().ToValue("b"); binder.Bind<string>().ToValue("c"); var strings = context.injectionBinder.GetInstance<IList<string>>(); Assert.AreEqual(3, strings.Count); Assert.AreEqual("a", strings[0]); Assert.AreEqual("b", strings[1]); Assert.AreEqual("c", strings[2]); } [Test] public void TestInjectListWithDuplicateValues() { binder.Bind<string>().ToValue("a"); binder.Bind<string>().ToValue("b"); binder.Bind<string>().ToValue("a"); var strings = context.injectionBinder.GetInstance<IList<string>>(); Assert.AreEqual(3, strings.Count); Assert.AreEqual(strings[0], strings[2]); } [Test] public void TestInjectTypesToList() { binder.Bind<IListItem>().To<ListItemA>(); binder.Bind<IListItem>().To<ListItemB>(); var list = context.injectionBinder.GetInstance<IList<IListItem>>(); Assert.AreEqual(2, list.Count); Assert.IsAssignableFrom(typeof(ListItemA), list[0]); Assert.IsAssignableFrom(typeof(ListItemB), list[1]); } [Test] public void TestInjectListWithSingletonItems() { binder.Bind<IListItem>().To<ListItemA>().ToSingleton(); binder.Bind<IListItem>().To<ListItemB>(); var list1 = context.injectionBinder.GetInstance<IList<IListItem>>(); var list2 = context.injectionBinder.GetInstance<IList<IListItem>>(); Assert.AreNotEqual(list1, list2); // Singleton Assert.AreEqual(list1[0], list2[0]); // New instance Assert.AreNotEqual(list1[1], list2[1]); } [Test] public void TestInjectListWithMixedValuesAndTypes() { binder.Bind<IListItem>().ToValue(new ListItemA()); binder.Bind<IListItem>().To<ListItemB>(); var list1 = context.injectionBinder.GetInstance<IList<IListItem>>(); var list2 = context.injectionBinder.GetInstance<IList<IListItem>>(); Assert.AreNotEqual(list1, list2); // Bound by value Assert.AreEqual(list1[0], list2[0]); // New instance Assert.AreNotEqual(list1[1], list2[1]); } [TestCase] public void TestInjectListAsSingleton() { binder.Bind<IListItem>().ToSingleton(); binder.Bind<IListItem>().ToValue(new ListItemA()); binder.Bind<IListItem>().To<ListItemB>(); var list1 = context.injectionBinder.GetInstance<IList<IListItem>>(); var list2 = context.injectionBinder.GetInstance<IList<IListItem>>(); // No matter how list items were bound they are all equal between // list1 and list2 because the list itself is bound as a singleton Assert.AreEqual(list1, list2); Assert.AreEqual(list1[0], list2[0]); Assert.AreEqual(list1[1], list2[1]); } } public interface IListItem { } public class ListItemA : IListItem { } public class ListItemB: IListItem { } } <file_sep>/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using strange.extensions.injector.api; using strange.extensions.listBind.api; using strange.framework.api; using strange.framework.impl; using System; using System.Collections.Generic; namespace strange.extensions.listBind.impl { public class ListBinder : Binder, IListBinder { private readonly Dictionary<Type, IListBinding> listTypes = new Dictionary<Type, IListBinding>(); private IInjectionBinder _injectionBinder; [Inject] public IInjectionBinder injectionBinder { get { return this._injectionBinder; } set { this._injectionBinder = value; _injectionBinder.injector.listBinder = this; } } public IListBinding GetListBinding(Type type) { if (!listTypes.ContainsKey(type)) { return null; } return listTypes[type]; } public override IBinding GetRawBinding() { return new ListBinding(resolver, _injectionBinder) as IBinding; } public new IListBinding Bind<T>() { IListBinding binding = null; if (listTypes.ContainsKey(typeof(T))) { binding = listTypes[typeof(T)]; } else { binding = base.Bind<T>() as IListBinding; binding.ListType = typeof(IList<T>); listTypes[typeof(T)] = binding; injectionBinder.Bind<IList<T>>().To<List<T>>(); } return binding; } } }
572a5c28ba0126d3f16966a910160f11eb4e8678
[ "C#" ]
3
C#
mr-robert/strange-core
d82af015aeabbfa54acb265052901dd96fa2520a
20e83863e5d3d6b4c47e5a7b6ee89316cb334064
refs/heads/master
<file_sep>import React from 'react'; const CreatePost = ({ title, body, onSubmit, onChange }) => ( <form onSubmit={onSubmit}> <input name="title" onChange={onChange} value={title} type="text" placeholder="added title..." /> <input name="body" onChange={onChange} value={body} type="text" placeholder="added text..." /> <button type="submit">SUBMIT</button> </form> ); export default CreatePost; <file_sep>import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; import Post from './pages/PagePost'; import Posts from './pages/PagePosts'; import Create from './pages/PageCreate'; import PageNotFound from './pages/PageNotFound'; import Update from './pages/UpdatePage'; import Modal from './components/Modal/ModalContainer'; function App() { return ( <div> <Modal /> <Switch> <Route path="/posts/:id" component={Post} /> <Route path="/posts" exact component={Posts} /> <Route path="/update" exact component={Update} /> <Route path="/create" component={Create} /> {/* <Redirect to="/posts" /> */} <Route component={PageNotFound} /> </Switch> </div> ); } export default App; <file_sep>export const getOnePost = state => state.blog.post; export const getAllPosts = state => state.blog.posts; export const getActiveModal = state => state.blog.isActiveModal; export const getPostsComments = state => state.blog.comments; <file_sep>import React from 'react'; const UpdatePage = () => <p>UPDATE</p>; export default UpdatePage; <file_sep>import React from 'react'; import Create from '../components/CreatePost/CreatePostContainer'; const PageCreate = () => <Create />; export default PageCreate; <file_sep>import React from 'react'; // import { withRouter } from 'react-router-dom'; const Post = ({ post, onReturn, onDelete, onOpen }) => ( <div> <button onClick={onReturn} type="button"> return </button> <p>{post.title}</p> <p>{post.body}</p> <button onClick={onOpen} type="button"> Put </button> <button onClick={() => onDelete(post.id)} type="button"> Delete </button> </div> ); export default Post; <file_sep>import React from 'react'; import Posts from '../components/Posts/PostsContainer'; import Modal from '../components/Modal/ModalContainer'; const PagePosts = () => ( <div> <Modal /> <Posts /> </div> ); export default PagePosts; <file_sep>/* eslint-disable */ import { connect } from 'react-redux'; import React, { Component, createRef } from 'react'; import Modal from './Modal'; import CreatePost from '../CreatePost/CreatePostContainer'; import { getActiveModal } from '../../redux/postsSelectors'; import { openModal, closeModal } from '../../redux/postsAction'; class ModalContainer extends Component { // state = { // isOpen: false, // }; // createClose = createRef(); componentDidMount(e) { window.addEventListener('keydown', this.handleEsc); console.log('componentDidMount'); console.log('this.props', this.props); } componentWillUnmount() { window.removeEventListener('keydown', this.handleEsc); console.log('componentWillUnmount'); } handleEsc = e => { const { close } = this.props; if (e.code !== 'Escape') return; // this.handleClose(); close(); }; closeWindow = e => { const { close } = this.props; const { current } = this.createClose; if (current !== e.target) return; // this.handleClose(); close(); }; // // handleOpen = () => { // this.setState({ isOpen: true }); // }; handleClose = e => { const { close } = this.props; close(); // this.setState({ isOpen: false }); }; render() { // const { isOpen } = this.state; const { open, isActiveModal } = this.props; return ( <div> <button onClick={() => open()}>Open</button> {isActiveModal && ( <Modal referanse={this.createClose} onClose={this.closeWindow}> <CreatePost onClose={this.handleClose} /> </Modal> )} </div> ); } } const mapStateToProps = state => ({ isActiveModal: getActiveModal(state), }); const mapDispatchToProps = dispatch => ({ open: () => dispatch(openModal()), close: () => dispatch(closeModal()), }); export default connect( mapStateToProps, mapDispatchToProps, )(ModalContainer); <file_sep>import { createStore, applyMiddleware, combineReducers } from 'redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import reduxThunk from 'redux-thunk'; import postsReducer from './postsReducer'; const rootReducer = combineReducers({ blog: postsReducer, }); const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(reduxThunk)), ); export default store; <file_sep>const types = { GET_POSTS_START: 'GET_POSTS_START', GET_POSTS_SUCCESS: 'GET_POSTS_SUCCESS', GET_POSTS_ERROR: 'GET_POSTS_ERROR', ADD_COMMENT_START: 'ADD_COMMENT_START', ADD_COMMENT_SUCCESS: 'ADD_COMMENT_SUCCESS', ADD_COMMENT_ERROR: 'ADD_COMMENT_ERROR', GET_COMMENT_START: 'GET_COMMENT_START', GET_COMMENT_SUCCESS: 'GET_COMMENT_SUCCESS', GET_COMMENT_ERROR: 'GET_COMMENT_ERROR', GET_POST_FROM_ID_START: 'GET_POST_FROM_ID_START', GET_POST_FROM_ID_SUCCESS: 'GET_POST_FROM_ID_SUCCESS', GET_POST_FROM_ID_ERROR: 'GET_POST_FROM_ID_ERROR', PUT_POST_START: 'PUT_POST_START', PUT_POST_SUCCESS: 'PUT_POST_SUCCESS', PUT_POST_ERROR: 'PUT_POST_ERROR', ADD_POST_START: 'ADD_POST_START', ADD_POST_SUCCESS: 'ADD_POST_SUCCESS', ADD_POST_ERROR: 'ADD_POST_ERROR', DELETE_POST_START: 'DELETE_POST_START', DELETE_POST_SUCCESS: 'DELETE_POST_SUCCESS', DELETE_POST_ERROR: 'DELETE_POST_ERROR', EDIT_POST_START: 'EDIT_POST_START', EDIT_POST_SUCCESS: 'EDIT_POST_SUCCESS', EDIT_POST_ERROR: 'EDIT_POST_ERROR', OPEN_MODAL: 'OPEN_MODAL', CLOSE_MODAL: 'CLOSE_MODAL', }; export default types; <file_sep>import axios from 'axios'; import { getPostsStart, getPostsSuccess, getPostsError, deletePostStart, deletePostSuccess, deletePostError, addPostStart, addPostError, getPostFromIdStart, getPostFromIdSuccess, getPostFromIdError, putPostStart, putPostError, addCommentStart, addCommentError, getCommentStart, getCommentSuccess, getCommentError, } from './postsAction'; // export const addComment = (comment, id) => dispatch => { dispatch(addCommentStart()); axios .post('https://bloggy-api.herokuapp.com/comments', comment) .then(() => dispatch(getComment(id))) .catch(error => dispatch(addCommentError(error))); }; export const getComment = id => dispatch => { dispatch(getCommentStart()); axios .get(`https://bloggy-api.herokuapp.com/posts/${id}/comments`) .then(comments => dispatch(getCommentSuccess(comments))) .catch(error => dispatch(getCommentError(error))); }; export const getPosts = () => dispatch => { dispatch(getPostsStart()); axios .get('https://bloggy-api.herokuapp.com/posts') .then(posts => dispatch(getPostsSuccess(posts))) .catch(error => dispatch(getPostsError(error))); }; export const getPost = id => dispatch => { dispatch(getPostFromIdStart()); return axios .get(`https://bloggy-api.herokuapp.com/posts/${id}`) .then(post => dispatch(getPostFromIdSuccess(post))) .catch(error => dispatch(getPostFromIdError(error))); }; // ////////////////////////////////////////////////////////////////////////// export const putPost = (id, post) => dispatch => { dispatch(putPostStart()); axios .delete(`https://bloggy-api.herokuapp.com/posts/${id}`, post) .then(() => console.log('WORKS')) .catch(error => dispatch(putPostError(error))); }; // ///////////////////////////////////////////////////////////////////////////// export const deletePost = id => dispatch => { dispatch(deletePostStart()); axios .delete(`https://bloggy-api.herokuapp.com/posts/${id}`) .then(() => dispatch(deletePostSuccess(id))) .catch(error => dispatch(deletePostError(error))); }; export const addPost = post => dispatch => { dispatch(addPostStart()); axios .post('https://bloggy-api.herokuapp.com/posts', post) .then(() => dispatch(getPosts())) .catch(error => dispatch(addPostError(error))); }; <file_sep>import { connect } from 'react-redux'; import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import CreatePost from './CreatePost'; import * as postsOperation from '../../redux/postsOperations'; class CreatePostContainer extends Component { state = { title: '', body: '', }; handleChange = ({ target }) => { // const { AddPost, onClose, match } = this.props; const { name, value } = target; this.setState({ [name]: value }); // console.log(match); }; handleSubmit = e => { const { AddPost, onClose, match } = this.props; const operation = match.path.length; // operation >= 5 ? AddPost(this.state) : console.log('m'); e.preventDefault(); AddPost(this.state); onClose(); this.reset(); }; reset = () => { this.setState({ title: '', body: '', }); }; render() { const { title, body } = this.state; return ( <CreatePost title={title} body={body} onSubmit={this.handleSubmit} onChange={this.handleChange} /> ); } } const mapDispatchToProps = { AddPost: postsOperation.addPost, PutPost: postsOperation.putPost, }; export default connect( null, mapDispatchToProps, )(withRouter(CreatePostContainer)); <file_sep>// import React, { Component } from 'react'; // class Comments extends Component { // // state = { } // render() { // const { items } = this.props; // return ( // <div> // <ul> // {items.map(comment => ( // <li key={comment.id}> // {/* <p>{comment.}</p> */} // <p>comment</p> // </li> // ))} // </ul> // </div> // ); // } // } // export default Comments; import React from 'react'; const Comments = ({ comments }) => ( <div> <ul> {comments.map(comment => ( <li key={comment.id}> <p>{comment.body}</p> <p>12/02/12</p> </li> ))} </ul> </div> ); export default Comments; <file_sep>import React from 'react'; import Post from '../components/Post/PostContainer'; import Comments from '../components/Comments/CommentsContainer'; import CreateComment from '../components/CreateComment/CreateCommentContainer'; const PagePost = () => ( <div> <Post /> <Comments /> <CreateComment /> </div> ); export default PagePost; <file_sep>// import { getPosts } from './notesOperations'; import types from './postsTypes'; const initialState = { posts: [], post: {}, isActiveModal: false, comments: [], }; const postsReducer = (state = initialState, { type, payload }) => { switch (type) { case types.GET_POSTS_SUCCESS: return { ...state, posts: payload }; case types.GET_POST_FROM_ID_SUCCESS: return { ...state, post: payload }; case types.DELETE_POST_SUCCESS: return { ...state, posts: state.posts.filter(post => post.id !== payload), }; case types.ADD_POST_SUCCESS: return [payload, ...state]; case types.OPEN_MODAL: return { ...state, isActiveModal: payload }; case types.CLOSE_MODAL: return { ...state, isActiveModal: payload }; case types.ADD_COMMENT_SUCCESS: return { ...state, comments: payload }; case types.GET_COMMENT_SUCCESS: return { ...state, comments: payload }; // case types.PUT_POST_SUCCESS: // return default: return state; } }; export default postsReducer; <file_sep>/*eslint-disable */ import { connect } from 'react-redux'; import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import Post from './Post'; import * as postsOperation from '../../redux/postsOperations'; import { openModal } from '../../redux/postsAction'; import { getOnePost, getPostsComments } from '../../redux/postsSelectors'; class PostContainer extends Component { componentDidMount() { const { fetchPost, match, getComments } = this.props; const postId = match.params.id; fetchPost(postId); } handleReturnButton = () => { const { history } = this.props; history.push('/posts'); }; handleDeletePost = id => { const { history, removePost } = this.props; removePost(id); history.replace('/posts'); }; render() { const { post, open } = this.props; // console.log(open); return ( <div> <Post post={post} onDelete={this.handleDeletePost} onReturn={this.handleReturnButton} onOpen={open} /> </div> ); } } const mapStateToProps = state => ({ post: getOnePost(state), }); const mapDispatchToProps = { fetchPost: postsOperation.getPost, removePost: postsOperation.deletePost, open: openModal, }; export default connect( mapStateToProps, mapDispatchToProps, )(withRouter(PostContainer)); <file_sep>/*eslint-disable */ import React from 'react'; import css from '../Modal/Modal.module.css'; const Modal = ({ onClose, children, referanse }) => ( <div onClick={onClose} className={css.drop} ref={referanse}> <div className={css.innerMenu}>{children}</div> </div> ); export default Modal; <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; const Posts = ({ posts, onDelete }) => ( <ul> {posts.map(post => ( <li key={post.id}> <p>{post.title}</p> <p>{post.body}</p> <Link to={`posts/${post.id}`}> <button type="button">open</button> </Link> <button onClick={() => onDelete(post.id)} type="button"> delete </button> </li> ))} </ul> ); export default Posts;
5cadce2255bee66c2b2253367ec46ff4c46165db
[ "JavaScript" ]
18
JavaScript
AntonAzhhirevych/postList_redux
6e4360292e332ea4ff0e6cc301d898ae77a7dc45
78a7d606e8fff014023a475d2eb253a3dc8160ea
refs/heads/main
<repo_name>MichaelAds/gren-ddt<file_sep>/src/services/mirage/index.ts import { createServer, Model, ActiveModelSerializer } from 'miragejs'; type User = { name: string; } // Partial = parcial, talvez não use tudo do tipo export function makeServer() { const server = createServer({ serializers: { application: ActiveModelSerializer, }, models: { user: Model.extend<Partial<User>>({}) }, routes() { this.namespace = 'api'; // delay para chamadas; this.timing = 750; this.get('/users'); this.post('/users'); this.namespace = ''; // passa a chamada para a original, caso não seja do mirage this.passthrough(); } }) return server; }
21716cbd7e1f6cddafd35dc2c22b4bef84b037b0
[ "TypeScript" ]
1
TypeScript
MichaelAds/gren-ddt
afdf19d5bd07ae611096aa7ddc7b9aa44bab0e7b
9bc5105b3864fdc28a95e65801884a7a7b78af20
refs/heads/master
<repo_name>iandurbach/non-euclidean-scr<file_sep>/tost_simulation/tost-sim-chonly.R library(tidyverse) #library(devtools) #install_github("rachelphillip/SCR-Book/scrmlebook") library(scrmlebook) library(secrdesign) library(pals) library(furrr) # mean function for non-euc distance calcs mymean = function(x) exp(mean(log(x))) # general LCdist function that allows you to call your own "mymean" fn (this is the only diff # between the arithLCdist and geomLCdist in noneuc-utils.R) myLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = mymean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } # load Tost data dat = readRDS("data/TNN.Rds") Tost = dat$Tost # load model to be used to estimate lambda0 needed to give desired n recaps load("output/Tost_Enrm_calcs.RData") # reduce by some factor for faster processing (leave at 1 for as is) aoiR <- secr::raster(Tost$mask, "stdGC") aoiR <- raster::aggregate(aoiR, fact = 3, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(stdGC = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) %>% filter(!is.nan(stdGC),!is.na(stdGC)) aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) aoi_mesh <- read.mask(data = aoi_df) # turn the matrix of trap co-ordinates into a trap object detectors_df <- as.data.frame(traps(Tost$capthist)) colnames(detectors_df) <- c("x", "y") rownames(detectors_df) <- rownames(traps(Tost$capthist)) detectors <- read.traps(data = detectors_df, detector = "count", binary.usage = FALSE) #detectors <- read.traps(data = traps(Tost$capthist), detector = "count", binary.usage = FALSE) ## simulate a capture history with desired properties sim_noneuc_ch_only <- function(n_pts, b_ac, b_con, mean_r, sigma, n_occasions, mesh, detectors, mod0){ # get value of lambda0 that produces r recaps in expectation # comes from a previous model, see Enrm_for_noneuc_Tost.R lambda0 <- predict(mod0, newdata = data.frame(b_ac = b_ac, b_con = b_con, mean_r = mean_r)) # desired number of points to generate n_pts <- n_pts ## generate non-uniform AC density # ac density ~ ruggedness, so add this as a mesh covariate. # introduce an b_ac parameter controlling strength of relationship b_ac <- b_ac covariates(mesh)$Dac <- exp(b_ac * covariates(mesh)$stdGC) Dcov_for_sim = n_pts / attr(mesh, "area") * (covariates(mesh)$Dac / sum(covariates(mesh)$Dac)) simulated_points_Dcov <- sim.popn(D = Dcov_for_sim, core = mesh, model2D = "IHP", Ndist = "fixed") ## generate non-Euclidean conductance # conductance ~ ruggedness, so add this as a mesh covariate. # create pixel-specific cost/friction and assign to the simulated popn objects # introduce an b_con parameter controlling strength of relationship lambda0 <- lambda0 sigma <- sigma b_con <- b_con covariates(mesh)$noneuc <- exp(b_con * covariates(mesh)$stdGC) attr(simulated_points_Dcov, "mask") <- mesh ## simulate a capture history ch <- sim.capthist(traps = detectors, pop = simulated_points_Dcov, userdist = myLCdist, noccasions = n_occasions, detectpar = list(lambda0 = lambda0, sigma = sigma), detectfn = "HHN") return(ch) } chh <- sim_noneuc_ch_only(n_pts = 20, b_ac = 0.5, b_con = 2, mean_r = 1000, sigma = 4000, n_occasions = 1, mesh = aoi_mesh, detectors = detectors, mod0 = mod0c) <file_sep>/tost_simulation/tost_sign_flipping.R library(tidyverse) #library(devtools) #install_github("rachelphillip/SCR-Book/scrmlebook") library(scrmlebook) library(pals) ### CHECK MYMEAN FUNCTIONS!! # general LCdist function that allows you to call your own "mymean" fn (this is the only diff # between the arithLCdist and geomLCdist in noneuc-utils.R) myLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = mymean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } dat = readRDS("tost_simulation/data/TNN.Rds") Tost = dat$Tost # reduce by some factor for faster processing (leave at 1 for as is) aoiR <- secr::raster(Tost$mask, "stdGC") aoiR <- raster::aggregate(aoiR, fact = 3, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(stdGC = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) %>% filter(!is.nan(stdGC),!is.na(stdGC)) aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) aoi_mesh <- read.mask(data = aoi_df) # turn the matrix of trap co-ordinates into a trap object detectors_df <- as.data.frame(traps(Tost$capthist)) colnames(detectors_df) <- c("x", "y") rownames(detectors_df) <- rownames(traps(Tost$capthist)) detectors <- read.traps(data = detectors_df, detector = "count", binary.usage = FALSE) #detectors <- read.traps(data = traps(Tost$capthist), detector = "count", binary.usage = FALSE) # recreate the flipping problem ch_actual <- Tost$capthist mymean = function(x){mean(exp(x))} startvals = list(D = exp(-9.6371), lambda0 = exp(-4.3387), sigma = exp(8.8508), noneuc = 1) mod_5_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) plotcovariate(predictDsurface(mod_5_actual),"D.0",col=parula(40)) # but CIs include zero coefficients(mod_5_actual) # rather use a log link and don't exponentiate inside LCdist mymean = function(x){mean(x)} mod_4_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) plotcovariate(predictDsurface(mod_4_actual),"D.0",col=parula(40)) coefficients(mod_4_actual) # still includes zero # above is for arithmetic means, same for geometric means ########################### # check if can reproduce for a simulated dataset with similar properties ########################### # desired number of points to generate n_pts <- 15 # non-uniform AC density # ac density is potentially a function of distance to stream, so add this as a mesh covariate. # introduce an alpha3 parameter controlling strength of relationship alpha3 <- 1.5 covariates(aoi_mesh)$Dac <- exp(alpha3 * covariates(aoi_mesh)$stdGC) Dcov_for_sim = n_pts / attr(aoi_mesh, "area") * (covariates(aoi_mesh)$Dac / sum(covariates(aoi_mesh)$Dac)) simulated_points_Dcov <- sim.popn(D = Dcov_for_sim, core = aoi_mesh, model2D = "IHP", Ndist = "fixed", seed = 123) # plot the ACs generated from non-uniform D aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) + geom_point(data = simulated_points_Dcov, color = "red") + geom_point(data = detectors_df, color = "green", size = 2, shape = 3) + ggtitle("ACs with non-uniform density") # some parameter values alpha0 <- -1 # implies lambda0 = invlogit(-1) = 0.2689414 sigma <- 4000 alpha1 <- 1 / (2 * sigma^2) alpha2 <- 0.3 K <- 10 # sampling over 10 occasion, with 1 occasion variability is HIGH # create pixel-specific cost/friction and assign to the simulated popn objects covariates(aoi_mesh)$noneuc <- exp(alpha2 * covariates(aoi_mesh)$stdGC) attr(simulated_points_Dcov, "mask") <- aoi_mesh # choose the function used to compute non-Euc distance (transitionFunction) mymean <- function(x){mean(x)} #mymean <- function(x){(prod(x)^(1/length(x)))} # simulate capture history for non-uniform AC density, non-Euclidean distance ch_Dcov_noneuc <- sim.capthist(detectors, pop = simulated_points_Dcov, userdist = myLCdist, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") # fit a constant density Euc model to get starting values mod_0 <-secr.fit(ch_Dcov_noneuc, detectfn = "HHN", mask = aoi_mesh, model = D ~ 1) # set starting values startvals = list(D = exp(-9.536054), lambda0 = exp(-1.339195), sigma = exp(8.704232), noneuc = 1) # model 4: non-uniform AC density, non-Euclidean distance mod_4 <-secr.fit(ch_Dcov_noneuc, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_4) # model 5: as for model 4 but exponentiate inside LCdist and use identity link mymean = function(x) mean(exp(x)) mod_5 <-secr.fit(ch_Dcov_noneuc, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) # reset to what it was mymean <- function(x){mean(x)} #mymean <- function(x){(prod(x)^(1/length(x)))} # seems like things are consistent and correct simulated values are returned plotcovariate(predictDsurface(mod_4),"D.0",col=parula(40)) plotcovariate(predictDsurface(mod_5),"D.0",col=parula(40)) coefficients(mod_4) coefficients(mod_5) <file_sep>/explore/where_you_exp_doesnt_affect_costDist.R library(secr) library(pals) library(raster) library(spatstat) library(maptools) library(gdistance) library(dplyr) load("data/mee312316-sup-0002-appendix_s2.rdata") # from supplement zip file!! aoiR <- raster::aggregate(aoiR, fact = 8, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(dist_stream = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) aoi_mesh <- read.mask(data = aoi_df) covariates(aoi_mesh)$exp_dist_stream <- exp(covariates(aoi_mesh)$dist_stream) # simulate # desired number of points to generate n_pts <- 200 # simulate some activity centers D0_for_sim = n_pts / attr(aoi_mesh, "area") * (1 / nrow(aoi_df)) acs <- sim.popn(D = D0_for_sim, core = aoi_mesh, model2D = "IHP", Ndist = "fixed", seed = 123) Sraster1 <- raster(aoi_mesh, "dist_stream") trans1 <- transition(Sraster1, transitionFunction = function(x) exp(mean(x)), directions = 16) trans1 <- geoCorrection(trans1) cd1 <- costDistance(trans1, as.matrix(gridTrapsXY), as.matrix(acs)) Sraster2 <- raster(aoi_mesh, "exp_dist_stream") trans2 <- transition(Sraster2, transitionFunction = function(x) prod(x)^(1/length(x)), directions = 16) trans2 <- geoCorrection(trans2) cd2 <- costDistance(trans2, as.matrix(gridTrapsXY), as.matrix(acs)) trans3 <- transition(Sraster1, transitionFunction = function(x) prod(exp(x))^(1/length(x)), directions = 16) trans3 <- geoCorrection(trans3) cd3 <- costDistance(trans3, as.matrix(gridTrapsXY), as.matrix(acs)) cd_all <- data.frame(cd1 = as.vector(cd1), cd2 = as.vector(cd2), cd3 = as.vector(cd3)) cd_all <- cd_all %>% mutate(diff_cd12 = abs(cd1 - cd2), diff_cd13 = abs(cd1 - cd3), diff_cd23 = abs(cd2 - cd3)) apply(cd_all, 2, max) <file_sep>/README.md # non-euclidean-scr Some simulation experiments investigating the behaviour of non-Euclidean distance in SCR models. One set of simulations is for the paper in prep "Understanding snow leopard populations and their spatial ecology through Spatial Capture Recapture Analysis across three sites in South Gobi, Mongolia". To rerun these run *tost_simulation.R* and *tost_sim_analysis.R*. These simulations simulate capture histories assuming the same covariate affects both activity centre density and conductance/movement, and see whether the true parameter estimates can be reliably recovered. A second simulation in *does_getting_D_and_euc_right_matter.R* tests the effect of model misspecification. It is less complete * Line 10 loads the Tost data- Up to line 64 generates the ACs, either uniformly or as a function of ruggedness (true parameter = 1.5, line 45). * Up to line 115 generates capture histories again either uniform or ~ ruggedness (true parameter = 0.3, line 76). * On line 125 you specify which simulated history you want (currently set so both density and distance are function of ruggedness) * Up to line 167 fits 4 different models, corresponding to getting the D part right/wrong, and the distance part right/wrong. For this capture history model 4 is the correct one, and it recovers the true parameter values well. <file_sep>/explore/mee312316-sup-0003-appendix_s3.r ################################################################################ # load the R workspace and libraries: wd <- getwd() load("connectivitySpace.Rdata") # from supplement zip file!! library("gdistance") library("raster") greyRamp <- colorRampPalette(c("gray50", "white"))( 100 ) # Which contains: ls() # aoiR: A raster with 'distance to stream' values in kms # e2dist: A function to calculate Euclidean diastance between 2 sets of points # gridTrapsXY: Trap locations # intlik4: Function to fit SCR model using Euclidean distance # intlik4ed: Function to fit SCR model estimating ecological distance ################################################################################ # function to simulate a single data set simCH.fn <- function(x){ out <- NULL N <- 200 a0 <- -1 sigma <- 1.4 a1 <- 1/(2*sigma^2) K <- 10 a2vec <- seq(0,10,1) scen <- length(a2vec) r <- aoiR aoiXY <- as.matrix(coordinates(r)) for(s in 1:scen){ # generate individuals acXY <- as.matrix(aoiXY[sample(1:nrow(aoiXY),N,replace=T),c("x","y")]) # generate cost surface a2 <- a2vec[s] trLayer <- NULL cost <- exp(a2 * r) trFn <- function(x)(1/(mean(x))) tr <- transition(cost,transitionFunction=trFn, direction = 8) trLayer <- geoCorrection(tr, scl = F) # generate capture histories -- GRID nt <- nrow(gridTrapsXY) d <- costDistance(trLayer,acXY,gridTrapsXY) probcap <- plogis(a0) * exp(-a1 * d^2) Y <- matrix(NA,nrow=N,ncol=nt) for(i in 1:nrow(Y)){ Y[i,] <- rbinom(nt, K, probcap[i,]) } Y <- Y[apply(Y,1,sum)>0,] # fit the models mink1 <- nlm(intlik4,p=c(a0,log(a1),log(N-nrow(Y))), hessian=F, y=Y, K=K,X=gridTrapsXY,G=aoiXY) mink2 <- nlm(intlik4ed,p=c(a0,log(a1),log(N-nrow(Y)),log(2)), hessian=F, y=Y, K=K,X=gridTrapsXY,G=aoiXY,cov=r,directions=8) out <- rbind(out, c(mink1$estimate[1], mink1$estimate[2], mink1$estimate[3], NA, nrow(Y), exp(mink1$estimate[3])+nrow(Y),x,s,1), c(mink2$estimate[1], mink2$estimate[2], mink2$estimate[3], mink2$estimate[4], nrow(Y), exp(mink2$estimate[3])+nrow(Y),x,s,2)) } return(out) } plot(aoiR,col=greyRamp) points(gridTrapsXY,pch=16,col=2) # we used snowfall to parellize our processing so this looping version will: # a) take ages # b) differ very slightly due to different random numbers (monte carlo error) sim.out <- list() nsim <- 1 set.seed(04091984) for(i in 1:nsim){ sim.out[[i]] <- simCH.fn() } <file_sep>/explore/where_you_exp_doesnt_matter.R library(tidyverse) #library(devtools) #install_github("rachelphillip/SCR-Book/scrmlebook") library(scrmlebook) # be sure to check you're using the right kind of LC distance calculations!! source("noneuc-utils.R") load("data/mee312316-sup-0002-appendix_s2.rdata") # from supplement zip file!! aoiR <- raster::aggregate(aoiR, fact = 5, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(dist_stream = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = dist_stream)) aoi_mesh <- read.mask(data = aoi_df) # turn the matrix of trap co-ordinates into a trap object detectors_df <- as.data.frame(gridTrapsXY) colnames(detectors_df) <- c("x", "y") rownames(detectors_df) <- 1:nrow(detectors_df) detectors <- read.traps(data = detectors_df, detector = "count", binary.usage = FALSE) #### Simulate activity centers # these can be from a flat density or D ~ dist_to_stream # desired number of points to generate n_pts <- 200 # using secr, flat density D0_for_sim = n_pts / attr(aoi_mesh, "area") * (1 / nrow(aoi_df)) simulated_points_D0 <- sim.popn(D = D0_for_sim, core = aoi_mesh, model2D = "IHP", Ndist = "fixed", seed = 123) # plot the ACs generated from D ~ dist_to_stream aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = dist_stream)) + geom_point(data = simulated_points_D0, color = "red") + geom_point(data = detectors_df, color = "green", size = 2, shape = 3) + ggtitle("ACs closer to streams") #### Generate capture histories # parameter values from Sutherland (2014) alpha0 <- -1 # implies lambda0 = invlogit(-1) = 0.2689414 sigma <- 1.4 alpha1 <- 1 / (2 * sigma^2) alpha2 <- 5 # just one scenario from the range 0..10 K <- 2 # sampling over 10 occasions, collapsed to 1 occasion # create pixel-specific cost/friction ~ distance to stream, and assign to the simulated popn objects covariates(aoi_mesh)$noneuc <- exp(alpha2 * covariates(aoi_mesh)$dist_stream) attr(simulated_points_D0, "mask") <- aoi_mesh ## simulate capture histories from flat AC density with non-Euclidean distance function ch_flatD_noneuc <- sim.capthist(detectors, pop = simulated_points_D0, userdist = arithLCdist, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") # fit model (arithmetic mean, not exponentiating in LCdist, log link) mymean = function(x){1/mean(x)} startvals = list(D = exp(8.0156), lambda0 = exp(-1.6518), sigma = exp(-0.2381), noneuc = 1) mod_1 <-secr.fit(ch_flatD_noneuc, detectfn = "HHN", mask = aoi_mesh, model= noneuc ~ dist_stream -1, details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_1) # fit model (arithmetic mean, exponentiating in myLCdist, identity link) mymean = function(x){1/mean(exp(x))} startvals = list(D = exp(8.0156), lambda0 = exp(-1.6518), sigma = exp(-0.2381), noneuc = exp(1)) mod_2 <-secr.fit(ch_flatD_noneuc, detectfn = "HHN", mask = aoi_mesh, model= noneuc ~ dist_stream -1, details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) coefficients(mod_2) # fit model (geometric mean, not exponentiating in LCdist, log link) mymean = function(x){1 / (prod(x)^(1/length(x)))} startvals = list(D = exp(8.0156), lambda0 = exp(-1.6518), sigma = exp(-0.2381), noneuc = 1) mod_3 <-secr.fit(ch_flatD_noneuc, detectfn = "HHN", mask = aoi_mesh, model= noneuc ~ dist_stream -1, details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_3) # fit model (geometric mean, exponentiating in myLCdist, identity link) mymean = function(x){exp(-mean(x))} startvals = list(D = exp(8.0156), lambda0 = exp(-1.6518), sigma = exp(-0.2381), noneuc = exp(1)) mod_4 <-secr.fit(ch_flatD_noneuc, detectfn = "HHN", mask = aoi_mesh, model= noneuc ~ dist_stream -1, details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) coefficients(mod_4) <file_sep>/tost_simulation/tost_sim_analysis.R library(dplyr) library(ggplot2) allfiles <- list.files(path = "tost_simulation/output/", pattern = ".(?i)rds") y <- readRDS(paste0("tost_simulation/output/", allfiles[1])) for(i in allfiles[-1]){ yt <- readRDS(paste0("tost_simulation/output/",i)) y <- rbind(y, yt) } y <- y %>% filter(n_pts == 20) y <- y %>% filter(!(b_ac == 0.1 & b_con == 0.1), !(b_ac == 0.5 & b_con == 0.5), !(b_ac == 0.5 & b_con == 2), !(b_ac == 1.5 & b_con == 1.5), !(b_ac == 1 & b_con == 1), !(b_ac == 2 & b_con == 2)) y <- y %>% mutate(id = row_number(), mod_id = rep(1:(nrow(y)/5), each = 5)) # remove where estimation errors, careful here but based on bad D estimates y_keep_D <- y %>% filter(parm == "D") %>% mutate(drop_sim_D = (is.na(SE.beta) | (beta < -14) | (beta > -8)) | (abs(SE.beta / beta) > 0.5)) y_keep_ac <- y %>% filter(parm == "D.stdGC") %>% mutate(drop_sim_ac = (is.na(SE.beta) | (SE.beta > 4) | (abs(SE.beta / beta) > 4))) y_keep_con <- y %>% filter(parm == "noneuc.stdGC") %>% mutate(drop_sim_con = (is.na(SE.beta) | (SE.beta > 4) | (abs(SE.beta / beta) > 4))) y <- y %>% left_join(y_keep_D %>% dplyr::select(id, drop_sim_D), by = "id") %>% left_join(y_keep_ac %>% dplyr::select(id, drop_sim_ac), by = "id") %>% left_join(y_keep_con %>% dplyr::select(id, drop_sim_con), by = "id") y <- y %>% group_by(mod_id) %>% mutate(drop_sim = (any(drop_sim_D == TRUE, na.rm = TRUE) | any(drop_sim_ac == TRUE, na.rm = TRUE) | any(drop_sim_con == TRUE, na.rm = TRUE))) %>% ungroup() yf <- y %>% filter(drop_sim == 0) y_sum <- yf %>% filter(parm %in% c("D.stdGC", "noneuc.stdGC")) %>% droplevels() %>% group_by(mean_r, b_ac, b_con, parm) %>% summarize(mean_beta = median(beta, na.rm = TRUE), lcl1 = stats::quantile(beta, probs = 0.025, na.rm = TRUE), ucl1 = stats::quantile(beta, probs = 0.975, na.rm = TRUE), lcl2 = mean_beta - 2 * median(SE.beta, na.rm = TRUE), ucl2 = mean_beta + 2 * median(SE.beta, na.rm = TRUE), in_cl = mean(((mean_beta > lcl) & (mean_beta < ucl)), na.rm = TRUE), cl_cont_zero = mean(((lcl < 0) & (ucl > 0)), na.rm = TRUE), n_valid = sum(!(is.na(beta)|is.nan(beta))), mean_nuniq = mean(n), mean_recap = mean(r)) %>% mutate(true_beta = ifelse(parm == "D.stdGC", b_ac, b_con), bias = mean_beta - true_beta) #y_sum$b_ac <- factor(y_sum$b_ac, c(0.3,0.5,1), c("b[D]==0.3","b[D]==0.5", "b[D]==1", "b[D]==2")) #y_sum$b_con <- factor(y_sum$b_con, c(0.3,0.5), c("b[H]==0.3","b[H]==0.5", "b[H]==2")) y_sum$b_ac <- factor(y_sum$b_ac, c(0.3,0.5,1,2), c("b[D]==0.3","b[D]==0.5", "b[D]==1", "b[D]==2")) y_sum$b_con <- factor(y_sum$b_con, c(0.3,0.5), c("b[H]==0.3","b[H]==0.5")) p1 <- y_sum %>% ggplot(aes(x = mean_r, y = cl_cont_zero, colour = parm)) + geom_point() + geom_line() + facet_grid(. ~ b_ac + b_con, scales = "fixed", labeller = label_parsed) + xlab("Number of recaptures") + ylab("Proportion of CIs containing zero") + scale_colour_discrete(breaks = c("D.stdGC", "noneuc.stdGC"), labels = c(bquote(hat(b)[D] ~ "(Density coefficient)"), bquote(hat(b)[H] ~ "(Habitat use coefficient)"))) + theme(legend.title = element_blank(), legend.position = "bottom") p1 # save ggsave("tost_simulation/output/tost-sim-cis.png", p1, width = 9, height = 3.5, dpi = 300) y_sum <- yf %>% filter(parm %in% c("D.stdGC", "noneuc.stdGC")) %>% droplevels() %>% mutate(true_beta = ifelse(parm == "D.stdGC", b_ac, b_con), bias = beta - true_beta) %>% group_by(mean_r, b_ac, b_con, parm) %>% summarize(mean_bias = median(bias, na.rm = TRUE), lcl1 = stats::quantile(bias, probs = 0.025, na.rm = TRUE), ucl1 = stats::quantile(bias, probs = 0.975, na.rm = TRUE), cl_cont_zero = mean(((lcl < 0) & (ucl > 0)), na.rm = TRUE), n_valid = sum(!(is.na(beta)|is.nan(beta))), mean_nuniq = mean(n), mean_recap = mean(r), true_beta = first(true_beta), perc_bias = mean_bias / true_beta) #y_sum$b_ac <- factor(y_sum$b_ac, c(0.3,0.5,1,2), c("b[D]==0.3","b[D]==0.5", "b[D]==1", "b[D]==2")) #y_sum$b_con <- factor(y_sum$b_con, c(0.3,0.5,2), c("b[H]==0.3","b[H]==0.5", "b[H]==2")) y_sum$b_ac <- factor(y_sum$b_ac, c(0.3,0.5,1,2), c("b[D]==0.3","b[D]==0.5", "b[D]==1", "b[D]==2")) y_sum$b_con <- factor(y_sum$b_con, c(0.3,0.5), c("b[H]==0.3","b[H]==0.5")) p2 <- y_sum %>% ggplot(aes(x = mean_r, y = 100 * mean_bias / true_beta, colour = parm)) + geom_point() + geom_line() + # geom_pointrange(aes(ymin = lcl1 / true_beta, ymax = ucl1 / true_beta)) + facet_grid(. ~ b_ac + b_con, scales = "fixed", labeller = label_parsed) + xlab("Number of recaptures") + ylab("% Bias") + coord_cartesian(ylim = c(-100,100)) + scale_colour_discrete(breaks = c("D.stdGC", "noneuc.stdGC"), labels = c(bquote(hat(b)[D] ~ "(Density coefficient)"), bquote(hat(b)[H] ~ "(Habitat use coefficient)"))) + theme(legend.title = element_blank(), legend.position = "bottom") p2 # save ggsave("tost_simulation/output/tost-sim-bias.png", p2, width = 9, height = 3.5, dpi = 300) y_sum2 <- yf %>% filter(parm %in% c("D.stdGC", "noneuc.stdGC")) %>% droplevels() %>% mutate(true_beta = ifelse(parm == "D.stdGC", b_ac, b_con), bias = beta - true_beta, perc_bias = 100 * bias / true_beta) y_sum2$b_ac <- factor(y_sum2$b_ac, c(0.3,0.5,1,2), c("b[D]==0.3","b[D]==0.5", "b[D]==1", "b[D]==2")) y_sum2$b_con <- factor(y_sum2$b_con, c(0.3,0.5,2), c("b[H]==0.3","b[H]==0.5", "b[H]==2")) y_sum2$parm <- factor(y_sum2$parm, c("D.stdGC", "noneuc.stdGC"), c("hat(b)[D] ~ '(Density coefficient)'", "hat(b)[H] ~ '(Habitat use coefficient)'")) p3 <- y_sum2 %>% filter(!is.na(SE.beta)) %>% ggplot(aes(x = factor(mean_r), y = perc_bias)) + geom_boxplot(aes(group = factor(mean_r)), na.rm = TRUE, outlier.shape = NA) + facet_grid(parm ~ b_ac + b_con, scales = "fixed", labeller = label_parsed) + xlab("Number of recaptures") + ylab("% Error") + coord_cartesian(ylim = c(-200,200)) + theme(legend.title = element_blank(), legend.position = "bottom") p3 # save ggsave("tost_simulation/output/tost-sim-bias-box.png", p3, width = 9, height = 6, dpi = 300) x3 <- y_sum2 %>% filter(!is.na(SE.beta), b_con == "b[H]==0.5", b_ac == "b[D]==2", mean_r <= 100) %>% select(bias, perc_bias, everything()) y_sum %>% filter(parm == "noneuc.stdGC") %>% ggplot(aes(x = mean_r, y = mean_beta)) + geom_point() + geom_pointrange(aes(ymin = lcl2, ymax = ucl2)) + facet_grid(b_ac ~ b_con, scales = "free") <file_sep>/tost_simulation/does_getting_D_and_noneuc_right_matter.R library(tidyverse) #library(devtools) #install_github("rachelphillip/SCR-Book/scrmlebook") library(scrmlebook) library(pals) # be sure to check you're using the right kind of LC distance calculations!! source("noneuc-utils.R") dat = readRDS("data/TNN.Rds") Tost = dat$Tost aoiR <- secr::raster(Tost$mask, "stdGC") aoiR <- raster::aggregate(aoiR, fact = 3, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(stdGC = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) %>% filter(!is.nan(stdGC),!is.na(stdGC)) aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) aoi_mesh <- read.mask(data = aoi_df) # turn the matrix of trap co-ordinates into a trap object detectors_df <- as.data.frame(traps(Tost$capthist)) colnames(detectors_df) <- c("x", "y") rownames(detectors_df) <- rownames(traps(Tost$capthist)) detectors <- read.traps(data = detectors_df, detector = "count", binary.usage = FALSE) #detectors <- read.traps(data = traps(Tost$capthist), detector = "count", binary.usage = FALSE) ####################################### #### Simulate activity centres ####################################### # desired number of points to generate n_pts <- 500 # uniform AC density D0_for_sim = n_pts / attr(aoi_mesh, "area") * (1 / nrow(aoi_df)) simulated_points_D0 <- sim.popn(D = D0_for_sim, core = aoi_mesh, model2D = "IHP", Ndist = "fixed", seed = 123) # non-uniform AC density (fiddle n_pts a bit to get exactly 200, not sure why) # ac density is potentially a function of distance to stream, so add this as a mesh covariate. # introduce an alpha3 parameter controlling strength of relationship alpha3 <- 1.5 covariates(aoi_mesh)$Dac <- exp(alpha3 * covariates(aoi_mesh)$stdGC) Dcov_for_sim = n_pts / attr(aoi_mesh, "area") * (covariates(aoi_mesh)$Dac / sum(covariates(aoi_mesh)$Dac)) simulated_points_Dcov <- sim.popn(D = Dcov_for_sim, core = aoi_mesh, model2D = "IHP", Ndist = "fixed", seed = 123) # plot the ACs generated from uniform density aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) + geom_point(data = simulated_points_D0, color = "red") + geom_point(data = detectors_df, color = "green", size = 2, shape = 3) + ggtitle("Flat density") # plot the ACs generated from D ~ dist_to_stream aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) + geom_point(data = simulated_points_Dcov, color = "red") + geom_point(data = detectors_df, color = "green", size = 2, shape = 3) + ggtitle("ACs closer to streams") ####################################### #### Generate capture histories ####################################### # there are 4 kinds of simulated capture histories: D~0 / D~cov x euclidean / noneuclidean # parameter values from Sutherland (2014) alpha0 <- -1 # implies lambda0 = invlogit(-1) = 0.2689414 sigma <- 1700 alpha1 <- 1 / (2 * sigma^2) alpha2 <- 0.3 # true non-euc parameter -- cost/friction ~ exp(alpha2 * cov) (see below) K <- 10 # sampling over 10 occasions, collapsed to 1 occasion # create pixel-specific cost/friction ~ distance to stream, and assign to the simulated popn objects covariates(aoi_mesh)$noneuc <- exp(alpha2 * covariates(aoi_mesh)$stdGC) attr(simulated_points_D0, "mask") <- aoi_mesh attr(simulated_points_Dcov, "mask") <- aoi_mesh # choose the function used to compute the path weight (non-Euc distance) between two points from # the covariate values i.e. path_weight([x1,y1],[x2,y2]) = mymean(cov([x1,y1]), cov[x2,y2]) # this is where you specify arithmetic or geometric mean, and 1-upon if inverse reln between covariate # and conductance (higher distance from river = LESS conductance / MORE resistance) mymean <- function(x){mean(x)} #mymean <- function(x){(prod(x)^(1/length(x)))} # uniform AC density, Euclidean distance ch_flatD_euc <- sim.capthist(detectors, pop = simulated_points_D0, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") # non-uniform AC density, Euclidean distance ch_Dcov_euc <- sim.capthist(detectors, pop = simulated_points_Dcov, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") # uniform AC density, non-Euclidean distance ch_flatD_noneuc <- sim.capthist(detectors, pop = simulated_points_D0, userdist = myLCdist, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") # non-uniform AC density, non-Euclidean distance ch_Dcov_noneuc <- sim.capthist(detectors, pop = simulated_points_Dcov, userdist = myLCdist, noccasions = K, detectpar = list(lambda0 = invlogit(alpha0), sigma = sigma), detectfn = "HHN") ####################################### #### Fit models ####################################### # there are four kinds of models: D~0 / D~cov x euclidean / noneuclidean # each of these models can be fitted to any of the four kinds of capture histories # Sutherland et al. (2014) simulated one kind of CH (D~0, non-euc) and two kinds of # model (D~0, euc & D~0, non-euc). # set the capture history you want to use here ch <- ch_Dcov_noneuc # set starting values startvals = list(D = exp(-5.8952), lambda0 = exp(-1.3335), sigma = exp(7.9654), noneuc = 1) # model 1: uniform AC density, Euclidean distance, use to get startvals mod_1 <-secr.fit(ch, detectfn = "HHN", mask = aoi_mesh, model = list(D ~ 1)) coefficients(mod_1) # model 2: non-uniform AC density, Euclidean distance mod_2 <-secr.fit(ch, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC), start = startvals) coefficients(mod_2) # model 3: uniform AC density, non-Euclidean distance mod_3 <-secr.fit(ch, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ 1, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_3) # model 4: non-uniform AC density, non-Euclidean distance mod_4 <-secr.fit(ch, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_4) # model 5: as for model 4 but exponentiate inside LCdist and use identity link mymean = function(x) mean(exp(x)) mod_5l <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) # reset to what it was mymean <- function(x){mean(x)} #mymean <- function(x){(prod(x)^(1/length(x)))} ####################################### #### With actual capture history ####################################### ch_actual <- Tost$capthist # model 1: uniform AC density, Euclidean distance, use to get startvals mod_1_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model = list(D ~ 1)) startvals = list(D = exp(-9.6371), lambda0 = exp(-4.3387), sigma = exp(8.8508), noneuc = 1) # model 2: non-uniform AC density, Euclidean distance mod_2_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC), start = startvals) coefficients(mod_2) # model 3: uniform AC density, non-Euclidean distance mod_3_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ 1, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) coefficients(mod_3) # model 4: non-uniform AC density, non-Euclidean distance mod_4_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "log")) # model 5: as for model 4 but exponentiate inside LCdist and use identity link mymean = function(x) mean(exp(x)) mod_5_actual <-secr.fit(ch_actual, detectfn = "HHN", mask = aoi_mesh, model= list(D ~ stdGC, noneuc ~ stdGC -1), details = list(userdist = myLCdist), start = startvals, link = list(noneuc = "identity")) # review results coefficients(mod_1_actual) coefficients(mod_2_actual) coefficients(mod_3_actual) coefficients(mod_4_actual) coefficients(mod_5_actual) region.N(mod_1_actual) region.N(mod_2_actual) region.N(mod_3_actual) region.N(mod_4_actual) region.N(mod_5_actual) plotcovariate(predictDsurface(mod_2_actual),"D.0",col=parula(40)) plotcovariate(predictDsurface(mod_4_actual),"D.0",col=parula(40)) plotcovariate(predictDsurface(mod_5_actual),"D.0",col=parula(40)) <file_sep>/noneuc-utils.R # general LCdist function that allows you to call your own "mymean" fn (this is the only diff # between the arithLCdist and geomLCdist below) myLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = mymean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } # geommean = function(x){exp(mean(x))} ## if conductance increases with covariate geommean = function(x){exp(-mean(x))} ## if conductance decreases with covariate #geommean = function(x){mean(x)} ## if you already exponentiate outside the fn and con PT cov geomLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = geommean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } #arithmean = function(x){mean(exp(x))} ## if conductance increases with covariate #arithmean = function(x){1/mean(exp(x))} ## if conductance decreases with covariate arithmean = function(x){1/mean(x)} ## if you already exponentiate outside the fn and con PT cov arithLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = arithmean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } expmax = function(x) exp(max(x)) expmaxLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = expmax, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } lcusageplot = function(fit,n=512,mask=NULL,base="noneuc.0",lcdfun="geomLCdist",maskcol=parula(40),...) { require(pals) if(is.null(mask)) mask = fit$mask lcd.fun = match.fun(lcdfun) if(!is.element("noneuc.0",names(covariates(mask)))) stop("Must have 'noneuc.0' as one of the mask covariates. It is not there.") if(!is.element(base,names(covariates(mask)))) { warning(paste("mask does not have a covariate called ",base,"; noneuc.0 being used instead.")) } covariates(mask)$base = covariates(mask)$noneuc.0 for(i in 1:n){ plotcovariate(mask,"base",col=maskcol,what="image") fromind = nearesttrap(unlist(locator(1)), mask) from = c(x=mask$x[fromind],y=mask$y[fromind]) from=matrix(from,ncol=2) dists = lcd.fun(from,mask,mask) dfn <- secr:::getdfn(fit$detectfn) p = dfn(dists[1,],unlist(detectpar(fit))) covariates(mask)$p = p/sum(p) plotcovariate(mask,"p",what="image",...) points(from,col="white",pch=19) points(from,cex=0.8,pch=19) waitclick = unlist(locator(1)) } invisible(mask) } lcpathplot = function(mask,transitionFunction,type="noneuc",n=512,background="d2.river",linecol="white", directions=16, symm=TRUE,directed=FALSE,lwd=1,...) { if(!is.element("noneuc.0",names(covariates(mask)))) stop("Must have 'noneuc.0' as one of the mask covariates. It is not there.") if(!is.element(type,c("noneuc","sigma"))) stop(paste("Invalid type: '",type,"'"," It must be `noneuc` or `sigma`.",sep="")) rastermask = raster(mask,"noneuc.0") # make raster with covariates(mask)$noneuc.0 as values of pixels transfun=match.fun(transitionFunction) coords = coordinates(rastermask) # lookup table for vertex coordinates # secr models conductance (sigma) with a log link. Line below assumes that $noneuc.0 is on linear predictor scale # tr1<-transition(rastermask,transitionFunction=function(x) exp(lp(x)),directions=directions,symm=symm) tr1<-transition(rastermask,transitionFunction=transfun,directions=directions,symm=symm) tr1CorrC<-geoCorrection(tr1,type="c",multpl=FALSE,scl=FALSE) if(type=="noneuc") plotcovariate(mask,"noneuc.0",...) else { covariates(mask)$sigma = exp(covariates(mask)$noneuc.0) plotcovariate(mask,"sigma",...) } dists = rep(NA,n) # to keep least-cost path distances in for(i in 1:n) { fromind = nearesttrap(unlist(locator(1)), mask) toind = nearesttrap(unlist(locator(1)), mask) from = c(x=mask$x[fromind],y=mask$y[fromind]) to = c(x=mask$x[toind],y=mask$y[toind]) from=matrix(from,ncol=2) to=matrix(to,ncol=2) # npts=dim(from)[1] # nptsto=dim(to)[1] # if(nptsto != npts) stop("Must have same number of points in 'from' as in 'to'.") # if(npts>1) pts = closest_coords(from[i,],to[i,],rastermask) # else pts = closest_coords(from,to,rastermask) pts = closest_coords(from,to,rastermask) vpts = get_vertices(pts,rastermask) trmat=summary(transitionMatrix(tr1CorrC)) #cbind(trmat,1/trmat$x) # rel=data.frame(from=trmat$i,to=trmat$j,weight=1/trmat$x) rel=data.frame(from=trmat$i,to=trmat$j,weight=trmat$x) #rel g = graph_from_data_frame(rel,directed=directed,vertices=NULL) # attributes(g)$noneuc.0=1/trmat$x # E(g)$weight=1/trmat$x attributes(g)$noneuc.0=trmat$x E(g)$weight=trmat$x #vertices = as_data_frame(g, what="vertices") #edges = as_data_frame(g, what="edges") svert=which(names(V(g))==vpts[1]) evert=which(names(V(g))==vpts[2]) # NB: Need to invert E(g) so that higher values lead to shorter distances: spath=as.numeric(names(shortest_paths(g,from=svert,to=evert,weights=1/E(g)$weight)$vpath[[1]])) dists[i]=igraph:::distances(g,v=svert,to=evert,weights=attributes(g)$noneuc.0) nppts=length(spath) segments(coords[spath[-nppts],1],coords[spath[-nppts],2],coords[spath[-1],1],coords[spath[-1],2],col=linecol,lwd=lwd) points(coords[spath[c(1,nppts)],],pch=19,col="white",cex=1.5) points(coords[spath[c(1,nppts)],],pch=19,col=c("green","red"),cex=0.75) } invisible(dists) } closest_coords=function(from,to,rastermask){ ends=SpatialPoints(rbind(from,to)) grid=as(rastermask, 'SpatialGrid') xy=over(ends,grid) return(coordinates(grid)[xy,]) } plotcovariate = function(mask,covariate, ...) { require(sp) cnum=which(names(covariates(mask))==covariate) if(is.null(cnum)) stop(paste("No covariate(s) called",covariate)) if(length(cnum)>1) warning("Can only plot one covariate at a time. First covariate being plotted.") pts = cbind(mask$x,mask$y) spdfdat = data.frame(covariate=covariates(mask)[[cnum]]) spdf = SpatialPixelsDataFrame(pts, spdfdat) plot(spdf, ...) invisible(spdf) } #' @title Finds closest coordinates on raster to two points #' #' @description #' Uses function over() from package sp to overlay points on raster and return closest raster coordinates #' #' @param from pair of coordinates (x,y) from which to start #' @param to pair of coordinates (x,y) to get to #' @param rastermask Raster object (typically created from mask by something like #' rastermask = raster(mask,"noneuc")) #' #' @return Returns the coordinates of the closest point on the raster, as a matrix with two columns (x,y), #' named s1 and s2, with first row corresponding to 'from' coordinates, and second row corresponding to 'to' #' coordinates. #' @export closest_coords #' closest_coords=function(from,to,rastermask){ ends=SpatialPoints(rbind(from,to)) grid=as(rastermask, 'SpatialGrid') xy=over(ends,grid) return(coordinates(grid)[xy,]) } #' @title Finds vertex index on graph made from raster #' #' @description #' Finds vertex index on graph made from raster, of points at coordinates pts. Vertex index is just the row of #' the point in the raster object. #' #' @param pts Matrix whose rows are (x,y) coordinates of points on raster #' @param raster Raster object. #' #' @return Returns the row numbers of raster that correpond to pts. Note that pts must match exactly some #' coordinates of raster (use \code{closest_coords} to find closest coordinates if necessary). #' #' @export get_vertices #' get_vertices = function(pts,rastermask){ target = nearest.raster.point(pts[,1],pts[,2],as.im(rastermask),indices=FALSE) coords = coordinates(rastermask) # lookup table from index produced by transition() to coordinates npts = dim(pts)[1] vert = rep(NA,npts) for(i in 1:npts){ # vert[i] = which(coords[,1]==target$x[i] & coords[,2]==target$y[i]) dst = sqrt((coords[,1]-target$x[i])^2 + (coords[,2]-target$y[i])^2) vert[i] = which(dst == min(dst))[1] } return(vert) } #' @title Creates the igraph of a mask object #' #' @description #' Creates an igraph object with a vertex for each mask point and edges to neighbours, weighted according #' to the cost function \code{costfun}, using the mask covariate \code{costname}. #' #' Requires packages raster, gdistance, igraph #' #' @param mask \code{secr} mask object. Must have covariate called 'noneuc' containing cost #' @param costname Name of variable to use in cost calculation #' @param costfun Cost function name #' @param directed If TRUE, use directed graph for transition between cells, else undirected #' @param symm If TRUE, cost is same in both directions #' #' @examples #' ny=4; nx=4 # dimensions of mask #' # set costs (NA is "hole" - nothing there & can't go there): #' costs=c(100,100,100,100,NA,100,100,NA,1,NA,100,1,1,1,1,1) #' rmesh=data.frame(x=rep(1:nx,ny),y=rep(1:ny,rep(nx,ny)),noneuc=costs) # make data frame with coords and costs #' #' rmask=read.mask(data=rmesh,columns="noneuc") # make mask with covariate 'noneuc' containing cost #' ig=make_igraph(rmask,"noneuc") #' plot(ig, edge.label=round(E(g)$weight, 3)) #' #' cfun=function(x) exp(diff(x)) # asymmetric cost function #' #' ig=make_igraph(rmask,"noneuc",costfun=cfun) #' plot(ig, edge.label=round(E(g)$weight, 3)) #' #' ig=make_igraph(rmask,"noneuc",costfun=cfun,directed=TRUE) #' plot(ig, edge.label=round(E(g)$weight, 3)) #' #' ig=make_igraph(rmask,"noneuc",costfun=cfun,directed=TRUE) #' plot(ig, edge.label=round(E(g)$weight, 3)) #' #' ig=make_igraph(rmask,"noneuc",costfun=cfun,directed=TRUE,symm=FALSE) #' plot(ig, edge.label=round(E(g)$weight, 3)) #' #' @export make_igraph #' make_igraph = function(mask,costname,costfun="mean",directed=FALSE,symm=TRUE) { if(!is.element(costname,names(covariates(mask)))) stop(paste("'",costname,"'"," is not the name of one of the mask covariates.",sep="")) rastermask = raster(mask,costname) # make raster with covariates(mask)$costname as values of pixels f=match.fun(costfun) #tr1<-transition(rastermask,transitionFunction=function(x) 1/mean(x),directions=8) #tr1<-transition(rastermask,transitionFunction=function(x) 1/exp(diff(x)),directions=8,symm=FALSE) tr1<-transition(rastermask,transitionFunction=function(x) 1/f(x),directions=8,symm=symm) tr1CorrC<-geoCorrection(tr1,type="c",multpl=FALSE,scl=FALSE) #costs1<-costDistance(tr1CorrC,pts) pts = closest_coords(from,to,rastermask) vpts = get_vertices(pts,rastermask) trmat=summary(tr1CorrC) rel=data.frame(from=trmat$i,to=trmat$j,weight=1/trmat$x) if(directed) g = graph_from_data_frame(rel,directed=TRUE,vertices=NULL) else g = graph_from_data_frame(rel,directed=FALSE,vertices=NULL) attributes(g)$noneuc=1/trmat$x E(g)$weight=1/trmat$x return(g) } plot.eland.detprob = function(fit,mask=NULL,occ="all",...) { cams = traps(fit$capthist) ch = fit$capthist if(is.null(mask)) mask = fit$mask betas = coefficients(fit) # beta paameters # Make linear predictor and calculate g0 g0s = which(substr(row.names(betas),1,2)=="g0") beta.g0 = betas$beta[g0s] X.g0 = model.matrix(fit$model$g0,data=elandmask) masklp.g0 = X.g0%*%beta.g0 maskg0.hat=invlogit(masklp.g0)[,1] # Make linear predictor and calculate sigma sigmas = which(substr(row.names(betas),1,5)=="sigma") beta.sigma = betas$beta[sigmas] X.sigma = model.matrix(fit$model$sigma,data=elandmask) masklp.sigma = X.sigma%*%beta.sigma masksigma.hat=exp(masklp.sigma)[,1] #function to calculate Halfnormal dectection function: pdet = function(d,g0,sigma,nocc) { npar = length(g0) ncam = dim(d)[1] p = matrix(rep(NA,npar*ncam),nrow=ncam) for(i in 1:ncam) p[i,] = 1 - (1-g0*exp(-d[i,]^2/(2*sigma^2)))^nocc return(p) } # Function to combine across independen detect probs combdet = function(ps) 1 - prod(1-ps) ncam = dim(cams)[1] nmask = dim(elandmask)[1] dists = matrix(rep(NA,nmask*ncam),nrow=ncam) for(i in 1:ncam) { dists[i,] = distancetotrap(mask,cams[i,]) } nocc = dim(ch)[2] # pest = rbind(pest,pestot) if(occ=="all") { pest = pdet(dists,maskg0.hat,masksigma.hat,nocc=nocc) pestot = apply(pest,2,combdet) } else if(occ=="single") { pest = pdet(dists,maskg0.hat,masksigma.hat,nocc=1) pestot = apply(pest,2,combdet) } else stop("Invalid occ passed") covariates(mask)$p = pestot plotcovariate(mask,"p",...) } plotcovariate = function(mask,covariate, ...) { require(sp) cnum=which(names(covariates(mask))==covariate) if(is.null(cnum)) stop(paste("No covariate(s) called",covariate)) if(length(cnum)>1) warning("Can only plot one covariate at a time. First covariate being plotted.") pts = cbind(mask$x,mask$y) spdfdat = data.frame(covariate=covariates(mask)[[cnum]]) spdf = SpatialPixelsDataFrame(pts, spdfdat) plot(spdf, ...) invisible(spdf) } # Plot encounter rate in 3D plotER3d = function(capthist, mask=NULL, occasions=1, add.points=TRUE,add.text=FALSE, add.maskedge=FALSE,add.mask=TRUE, add.traps=TRUE) { require(rgl) require(pals) if(length(session)>1) stop("Only one session at a time: capthist must be a matrix, not a list.") if(max(occasions)>dim(capthist)[2]) stop("occasion bigger than number of occasions in cpature history.") if(min(occasions)<1) stop("occasion must be greater than zero.") occasions = as.integer(occasions) dets = traps(capthist) asp= c(1,diff(range(dets$y))/diff(range(dets$x)),1) effort = usage(dets)[,occasions] ndets = apply(capthist[,occasions,],2,"sum") er = ndets/effort zlim=range(0,er) if(!is.null(mask)){ xlim = range(mask$x) ylim = range(mask$y) plot3d(dets$x,dets$y,er, size=10,type="h",lwd=1,xlim=xlim,ylim=ylim,zlim=zlim, xlab="Easting",ylab="Northing",zlab="Encounter Rate",aspect=asp) } else { plot3d(dets$x,dets$y,er, size=10,type="h",lwd=1,zlim=zlim, xlab="Easting",ylab="Northing",zlab="Encounter Rate",aspect=asp) } rgl.bbox(xlen = 0, ylen = 0, zlen = 0, color = 'white') if(add.points) { pointcolr = parula(max(ndets[er>0])+1)[ndets[er>0]+1] points3d(dets$x[er>0],dets$y[er>0],er[er>0],col=pointcolr,size=10,add=TRUE) } if(add.text) { textcolr = parula(max(ndets)+1)[ndets+1] text3d(dets$x,dets$y,1.05*er, texts=signif(er,2),col=textcolr,add=TRUE, cex=0.75) } if(!is.null(mask)){ if(!add.maskedge & !add.mask) add.mask=TRUE # if pass mask, plot it! # add mask edge if asked to if(add.maskedge) { edge = plotMaskEdge(mask,plt=FALSE,add=TRUE) xedge = edge[c(1,3),] yedge = edge[c(2,4),] segments3d(xedge,yedge,z=-0.01*diff(zlim)) } # add mask if asked to if(add.mask) { points3d(mask$x,mask$y,z=-0.01*diff(zlim),col="gray") } } # add traps if(add.traps) points3d(dets$x,dets$y,z=0,pch=1,col="red") } <file_sep>/explore/mee312316-sup-0001-appendix_s1.r ################################################################################ ## Integrated likelihood function (intlik4 above) to calculate cost distance ## Required objects for running the model: # # 'start': starting parameter values # 'y': individual x trap (row x col) counts of detections across K occasions # 'K': number of sampling occassions # 'delta': SCRed <- function(start = NULL, y = y, K = NULL, delta = 0.3, X = traplocs, cov=cov,G = NULL, ssbuffer = 2,directions=16, dist="ecol"){ if (is.null(G)) { Xl <- min(X[, 1]) - ssbuffer Xu <- max(X[, 1]) + ssbuffer Yu <- max(X[, 2]) + ssbuffer Yl <- min(X[, 2]) - ssbuffer SSarea <- (Xu - Xl) * (Yu - Yl) if (is.null(K)) return("need sample size") xg <- seq(Xl + delta/2, Xu - delta/2, delta) yg <- seq(Yl + delta/2, Yu - delta/2, delta) npix.x <- length(xg) npix.y <- length(yg) area <- (Xu - Xl) * (Yu - Yl)/((npix.x) * (npix.y)) G <- cbind(rep(xg, npix.y), sort(rep(yg, npix.x))) } else { G <- G SSarea <- nrow(G) } nG <- nrow(G) ## cost distance -- This (#~#) differs from Euclidean distance model #~# alpha2 <- exp(start[4]) #~# cost <- exp(alpha2 * cov) #~# tr <- transition(cost, transitionFunction=function(x) (1/(mean(x))), #~# direction = directions) #~# trLayer <- geoCorrection(tr, scl = F) #~# D <- costDistance(trLayer,as.matrix(X),as.matrix(G)) #~# alpha0 <- start[1] alpha1 <- exp(start[2]) n0 <- exp(start[3]) probcap <- plogis(alpha0) * exp(-alpha1 * D * D) Pm <- matrix(NA, nrow = nrow(probcap), ncol = ncol(probcap)) ymat <- y ymat <- rbind(y, rep(0, ncol(y))) lik.marg <- rep(NA, nrow(ymat)) for (i in 1:nrow(ymat)) { Pm[1:length(Pm)] <- (dbinom(rep(ymat[i, ], nG), rep(K, nG), probcap[1:length(Pm)], log = TRUE)) lik.cond <- exp(colSums(Pm)) lik.marg[i] <- sum(lik.cond * (1/nG)) } nv <- c(rep(1, length(lik.marg) - 1), n0) part1 <- lgamma(nrow(y) + n0 + 1) - lgamma(n0 + 1) part2 <- sum(nv * log(lik.marg)) out <- -1 * (part1 + part2) attr(out, "SSarea") <- SSarea out } <file_sep>/tost_simulation/Ernm_for_noneuc_Tost.R library(tidyverse) #library(devtools) #install_github("rachelphillip/SCR-Book/scrmlebook") library(scrmlebook) library(secrdesign) library(pals) library(furrr) # mean function for non-euc distance calcs mymean = function(x) exp(mean(log(x))) # general LCdist function that allows you to call your own "mymean" fn (this is the only diff # between the arithLCdist and geomLCdist in noneuc-utils.R) myLCdist <- function (xy1, xy2, mask) { if (missing(xy1)) return('noneuc') # required by secr require(gdistance) # to load transition and geoCorrection functions if(is.element("noneuc",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc') # Make raster from mesh with covariate 'noneuc' } else if(is.element("noneuc.0",names(covariates(mask)))) { Sraster <- raster(mask, 'noneuc.0') # Make raster from mesh with covariate 'noneuc' } else stop("Got to have covariate named `noneuc` or `noneuc.0` on mask.") # Calculate all the conductances, using mytransfun trans <- transition(Sraster, transitionFunction = mymean, directions = 16) # Adjust for distance difference between square and diagonal neighbours trans <- geoCorrection(trans) # calculate the least-cost distance (trans must be conductances) costDistance(trans, as.matrix(xy1), as.matrix(xy2)) } dat = readRDS("tost_simulation/data/TNN.Rds") Tost = dat$Tost # reduce by some factor for faster processing (leave at 1 for as is) aoiR <- secr::raster(Tost$mask, "stdGC") aoiR <- raster::aggregate(aoiR, fact = 3, fun = mean) aoi <- as.data.frame(aoiR) %>% rename(stdGC = layer) aoi_df <- cbind(as.data.frame(coordinates(aoiR)), aoi, D = 1) %>% filter(!is.nan(stdGC),!is.na(stdGC)) aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) aoi_mesh <- read.mask(data = aoi_df) # turn the matrix of trap co-ordinates into a trap object detectors_df <- as.data.frame(traps(Tost$capthist)) colnames(detectors_df) <- c("x", "y") rownames(detectors_df) <- rownames(traps(Tost$capthist)) detectors <- read.traps(data = detectors_df, detector = "count", binary.usage = FALSE) #detectors <- read.traps(data = traps(Tost$capthist), detector = "count", binary.usage = FALSE) # # plot the ACs generated from non-uniform D # aoi_df %>% ggplot(aes(x, y)) + geom_raster(aes(fill = stdGC)) + # geom_point(data = simulated_points_Dcov, color = "red") + # geom_point(data = detectors_df, color = "green", size = 2, shape = 3) + # ggtitle("ACs with non-uniform density") ### find N recaps as function of lambda # function that simulates many capture histories and takes calc_recaps <- function(n_pts, b_ac, b_con, lambda0, sigma, n_occasions, mesh, detectors){ # desired number of points to generate n_pts <- n_pts ## generate non-uniform AC density # ac density ~ ruggedness, so add this as a mesh covariate. # introduce an b_ac parameter controlling strength of relationship b_ac <- b_ac covariates(mesh)$Dac <- exp(b_ac * covariates(mesh)$stdGC) Dcov_for_sim = n_pts / attr(mesh, "area") * (covariates(mesh)$Dac / sum(covariates(mesh)$Dac)) simulated_points_Dcov <- sim.popn(D = Dcov_for_sim, core = mesh, model2D = "IHP", Ndist = "fixed") ## generate non-Euclidean conductance # conductance ~ ruggedness, so add this as a mesh covariate. # create pixel-specific cost/friction and assign to the simulated popn objects # introduce an b_con parameter controlling strength of relationship lambda0 <- lambda0 sigma <- sigma b_con <- b_con covariates(mesh)$noneuc <- exp(b_con * covariates(mesh)$stdGC) attr(simulated_points_Dcov, "mask") <- mesh ## simulate a capture history ch <- sim.capthist(traps = detectors, pop = simulated_points_Dcov, userdist = myLCdist, noccasions = n_occasions, detectpar = list(lambda0 = lambda0, sigma = sigma), detectfn = "HHN") ## number of unique animals detected n <- summary(ch)$counts$Total[4] ## number of recaptures r <- summary(ch)$counts$Total[6] res <- data.frame(n_pts, b_ac, b_con, lambda0, sigma, n_occasions, n, r) return(res) } # calc_recaps(n_pts = 15, b_ac = 1.5, b_con = 0.3, lambda0 = .26, sigma = 4000, # n_occasions = 1, mesh = aoi_mesh, detectors = detectors) pars <- expand.grid(b_ac = c(0.3,0.5,1,2), b_con = c(0.3,0.5), lambda0 = seq(0.5, 2, by = 0.5)) future::plan(multiprocess) f_allres <- future_map_dfr(1:50, ~ future_pmap_dfr(pars, calc_recaps, n_pts = 20, sigma = 4000, n_occasions = 1, mesh = aoi_mesh, detectors = detectors), .progress = TRUE) f_allres %>% ggplot(aes(x = lambda0, y = r)) + facet_grid(b_ac ~ b_con) + stat_summary(fun.y = "mean", geom = "point") + stat_summary(fun.data = mean_cl_normal, geom = "pointrange") + ylab("Number of recaps") + xlab("lambda0") newdata <- f_allres %>% group_by(b_ac, b_con, lambda0) %>% summarize(mean_r = mean(r), mean_n = mean(n)) %>% ungroup() %>% data.frame() mod0 <- lm(lambda0 ~ -1 + factor(b_ac)*factor(b_con)*mean_r, data = newdata) # best model uses b_ac and b_con as factor variables (fits line to each combo) but # this means you can only predict with same values of b_ac and b_con (only mean_r changes) summary(mod0) plot(newdata$lambda0,predict(mod0)) predict(mod0, newdata = data.frame(b_ac = 0.5, b_con = 2, mean_r = 100)) # model with continuous b_ac and b_con, useful if want to predict with different values # of these mod0c <- lm(lambda0 ~ -1 + b_ac*b_con*mean_r, data = newdata) plot(newdata$lambda0,predict(mod0c)) predict(mod0c, newdata = data.frame(b_ac = 0.3, b_con = 1, mean_r = 100)) save(mod0, mod0c, f_allres, file = "tost_simulation/output/Tost_Enrm_calcs.RData")
f3c96968d56c51e5069dcb1d037d3afd578bd85d
[ "Markdown", "R" ]
11
R
iandurbach/non-euclidean-scr
4e81e82c76e890ed61164b88035b033675ca77e2
5138dc359eb4e6f657ffb3825b18c6fe9cd6aca1
refs/heads/main
<file_sep>**NOTE: This frontend is discontinued, and is no longer being updated.** # Sluggo-Slack [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) A slack application that will communicate with Sluggo's REST api. ## Installation Currently, installation steps are focused on development. This process will hopefully be simplified once more complete versions of the tracker are available. To install Sluggo on development machines, perform the following: 1. Create the virtual environment for Sluggo using the command `python3 -m venv env` 2. Activate the Sluggo virtual environment. a. For POSIX platforms (macOS and Linux) run: `source ./env/bin/activate` b. For Windows: `.\env\Scripts\activate.bat` 3. Install the dependencies for Sluggo to run using the command `pip install -r ./requirements.txt` 4. Set the environment variable `SLACK_DJANGO_KEY` to some random, unique value (only important for production): `export SLACK_DJANGO_KEY="not important for non producton"` 5. Obtain the Slack Bot's _Bot User OAuth Access Token_ from [here](https://api.slack.com/apps/A01K80T5XCP/oauth?), and set the environment variable `SLACK_BOT_TOKEN` to it in your work environment. 6. To obtain a request url for Slack to communicate with, install [Ngrok](https://ngrok.com/) and make an account. ## Running 1. Activate the virtual environment shown in the Installation steps. a. For POSIX platforms (macOS and Linux): `source ./env/bin/activate` b. For Windows: `.\env\Scripts\activate.bat` 2. Run the following command whenever changes to the database models are made. This is likely necessary whenever new versions of the repository are pulled, or your version of SluggoAPI is otherwise upgraded: `python manage.py makemigrations; python manage.py migrate` 3. Run with: `python manage.py runserver` 4. In a seperate terminal run: `ngrok http <YOUR DJANGO PORT>` which will give you a url to use for all requests. 5. Replace the URLs within the command you are working on in the api's website. a. For the slash commands you're currently working on, navigate to the slash commands subsection on the Slack API site and replace the hostnames where necessary b. To get authentication working, navigate to the oauth & permissions subsection on the Slack API site and replace the hostname of the single redirect url. ## License This project is licensed under the Apache 2.0 License. See LICENSE for more details. <file_sep>from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from slack_sdk import WebClient import os, requests, json from .helper import ArgumentParser, translateError from .request_wrappers import AuthorizedRequest from . import config client = WebClient(token=config.SLACK_BOT_TOKEN) @csrf_exempt def create_ticket(request): required_fields = ["title"] ticket_url = f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/" members_url = f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/members/" slack_data = request.POST channel_id = slack_data.get("channel_id") args = ArgumentParser.parse_args(slack_data.get("text")) user_id = slack_data.get("user_id") api_request = AuthorizedRequest(user_id=user_id) if not all(field in args for field in required_fields): client.chat_postEphemeral( channel=channel_id, text=f'/ticket syntax error:\n\t/ticket --title "Title" [--asgn @username --desc "Description"]', user=user_id, ) return HttpResponse(status=200) ticket = { "team_id": config.TEAM_ID, "title": args.get("title", ""), } if "asgn" in args: pk = -1 try: response = api_request.get(url=members_url) users_json = response.json().get("results") for i in users_json: if i["owner"]["username"] == args["asgn"]: pk = i["owner"]["id"] break if pk != -1: ticket["assigned_user"] = pk except Exception as e: message = e.__str__() if "desc" in args: ticket["description"] = args["desc"] try: response = api_request.post(url=ticket_url, data=ticket) except Exception as e: message = e.__str__() if response.status_code != 201: client.chat_postEphemeral( channel=channel_id, text=f"/ticket: Internal Error: {translateError(response.json())}", user=user_id, ) return HttpResponse(status=200) ticket_res = response.json() message = "Ticket Created:\n" message += f"Ticket {ticket_res['ticket_number']}: {ticket_res['title']}\n" message += f"Description: {ticket_res['description']}\n" message += f"Owner: {ticket_res['owner']['username']}\n" if ("asgn" in args) and (pk != -1): message += f"Assigned User: {ticket_res['assigned_user']['username']}" client.chat_postMessage( channel=channel_id, text=message, ) return HttpResponse(status=200) @csrf_exempt def dhelp(request): data = request.POST channel_id = data.get("channel_id") text = data.get("text") multi_help = """ _*# Welcome to Sluggo!*_ Our commands are as follows: • /dhelp: _display this message_ • /ticket-create --title "My title" --desc "My Description" --asgn @username • /my-tickets _shows current tickets_ """ client.chat_postMessage( channel=channel_id, blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": multi_help, }, } ], text="Welcome to Sluggo!", ) return HttpResponse(status=200) @csrf_exempt def auth(request): data = request.POST channel_id = data.get("channel_id") user_id = data.get("user_id") url = f"https://slack.com/oauth/v2/authorize?user_scope=identity.basic&client_id={config.CLIENT_ID}" client.chat_postEphemeral( channel=channel_id, blocks=[ { "type": "section", "text": {"type": "mrkdwn", "text": "Connect slack to sluggo"}, }, { "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "Connect account", }, "url": url, } ], }, ], text="Connect Slack to Sluggo", user=user_id, ) return HttpResponse(status=200) @csrf_exempt def my_tickets(request): data = request.POST channel_id = data.get("channel_id") username = data.get("user_name") my_tickets_data = {"owner__username": username, "team_pk": config.TEAM_ID} user_id = data.get("user_id") api_request = AuthorizedRequest(user_id=user_id) message = f"{username}'s current tickets:\n" try: response = api_request.get( url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/", data=my_tickets_data ) except Exception as e: message = e.__str__() if response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text="Error, try again", user=data.get("user_id") ) return HttpResponse(status=404) json_response = response.json() results = json_response.get("results") ticket_num = 1 if len(results) == 0: client.chat_postMessage( channel=channel_id, text=f"{username} currently has no tickets", ) return HttpResponse(status=200) for result in results: title = result.get("title") message += f"Ticket {ticket_num}: {title}\n" ticket_num += 1 client.chat_postMessage( channel=channel_id, text=message, ) return HttpResponse(status=200) @csrf_exempt def set_description(request): required_fields = ["desc", "id"] data = request.POST channel_id = data.get("channel_id") text = data.get("text") args = ArgumentParser.parse_args(text) user_id = data.get("user_id") api_request = AuthorizedRequest(user_id=user_id) ticket_desc = args.get("desc") ticket_id = args.get("id") message = f"Description for ticket {ticket_id} updated" if not all(field in args for field in required_fields): client.chat_postEphemeral( channel=channel_id, text=f'/syntax error:\n\t/set-description --desc "Description" --id "Ticket ID', user=user_id, ) return HttpResponse(status=200) try: response = api_request.patch( url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/{ticket_id}/", data={"description": ticket_desc} ) except Exception as e: message = e.__str__() if response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text=f"/set-description: Internal Error: {translateError(response.json())}", user=user_id, ) return HttpResponse(status=200) client.chat_postMessage(channel=channel_id, text=message) return HttpResponse(status=200) @csrf_exempt def check_status(request): data = request.POST channel_id = data.get("channel_id") text = data.get("text") args = ArgumentParser.parse_args(text) ticket_id = args.get("id") user_id = data.get("user_id") api_req = AuthorizedRequest(user_id=user_id) required_params = ["id"] if not all(field in args for field in required_params): client.chat_postEphemeral( channel=channel_id, text=f'/syntax error:\n\t/check-status --id <ticket id>', user=user_id, ) return HttpResponse(status=200) try: response = api_req.get(url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/{ticket_id}/") message = json.dumps(response.json(), indent=4) except Exception as e: message = e.__str__() if response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text="Error, try again", user=data.get("user_id") ) return HttpResponse(status=404) status = response.json().get("status").get("title") client.chat_postMessage( channel = channel_id, text = f"Ticket status: {status}", ) return HttpResponse(status=200) @csrf_exempt def change_status(request): data = request.POST channel_id = data.get("channel_id") text = data.get("text") args = ArgumentParser.parse_args(text) ticket_id = args.get("id") new_status = args.get("new_status") new_status_id = 0 # get auth token user_id = data.get("user_id") auth_req = AuthorizedRequest(user_id=user_id) # check for correct parameters required_params = ["id", "new_status"] if not all(field in args for field in required_params): client.chat_postEphemeral( channel=channel_id, text=f'/syntax error:\n\t/change-status --id <ticket id> --new_status <status>', user=user_id, ) return HttpResponse(status=200) # get available statuses try: statuses_response = auth_req.get(url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/statuses/") statuses_message = json.dumps(statuses_response.json(), indent=4) except Exception as e: statuses_message = e.__str__() # print(statuses_response.status_code) if statuses_response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text="Error, try again", user=data.get("user_id") ) return HttpResponse(status=404) # make a list of statuses and check if new status is valid status_results = statuses_response.json().get("results") statuses_list = [] for status in status_results: title = status.get("title") statuses_list.append(title) if new_status not in statuses_list: client.chat_postEphemeral( channel=channel_id, text=f"Invalid status, choose from: {statuses_list}", user=data.get("user_id") ) return HttpResponse(status=404) # if status valid get the id for status in status_results: if status.get("title") == new_status: new_status_id = status.get("id") # update the status id try: response = auth_req.patch( url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/{ticket_id}/", data={"status": int(new_status_id)} ) message = json.dumps(response.json(), indent=4) except Exception as e: message = e.__str__() # print(response.status_code) if response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text="Error, try again", user=data.get("user_id") ) return HttpResponse(status=404) client.chat_postMessage( channel = channel_id, text = "Ticket status updated!" ) return HttpResponse(status=200) # debug for simple checking if the status changed # response = auth_req.get(url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/tickets/{ticket_id}/").json().get("status") # print(response) @csrf_exempt def print_statuses(request): data = request.POST channel_id = data.get("channel_id") text = data.get("text") args = ArgumentParser.parse_args(text) user_id = data.get("user_id") auth_req = AuthorizedRequest(user_id=user_id) try: response = auth_req.get(url=f"{config.API_ROOT}/api/teams/{config.TEAM_ID}/statuses/") message = json.dumps(response.json(), indent=4) except Exception as e: message = e.__str__() if response.status_code != 200: client.chat_postEphemeral( channel=channel_id, text="Error, try again", user=data.get("user_id") ) return HttpResponse(status=404) status_results = response.json().get("results") status_message = f"Team {config.TEAM_ID} statuses: " if len(status_results) > 0: statuses_list = [] for status in status_results: title = status.get("title") statuses_list.append(title) s = ','.join(statuses_list) status_message += s client.chat_postMessage( channel = channel_id, text = status_message) else: client.chat_postMessage( channel = channel_id, text = "There are no statuses for this team." ) return HttpResponse(status=200)<file_sep>slack-sdk aiohttp django requests pipenv <file_sep>""" Views that are not part of the slash commands. These are used in the oauth flow """ from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import authed_user as User from . import config import requests as req import json, os @csrf_exempt def slack_callback(request): if hasattr(request, "GET") and (code := request.GET["code"]): url = f"https://slack.com/api/oauth.v2.access" response = req.get(url, params={ "client_id": config.CLIENT_ID, "client_secret": config.CLIENT_SECRET, "code": code }) authed_user = response.json().get("authed_user", None) msg = "success!" if authed_user: print(json.dumps(authed_user, indent=4)) instance, _ = User.objects.update_or_create( **authed_user ) instance.save() else: msg = json.dumps(response.json(), indent=4) return HttpResponse(status=200, content=msg) return HttpResponse(status=400) <file_sep>from django.db import models # Create your models here. class authed_user(models.Model): id = models.CharField(max_length=20, unique=True, primary_key=True) scope = models.TextField(null=True) access_token = models.CharField(max_length=80, unique=True) token_type = models.TextField(null=True) <file_sep>import re import requests from requests.structures import CaseInsensitiveDict class ArgumentParser: @classmethod def parse_args(cls, text: str) -> dict: """ takes the text from a slack command and parses the arguments """ arg_pattern = re.compile(r'--(\w+) *["@]?([^-"]*)\"?') return dict(arg_pattern.findall(text)) def translateError(error_dict): error_string = """""" for key, value in error_dict.items(): if isinstance(value, dict): error_string += f"\t{key}: {translateError(value)}\n" elif isinstance(value, list): error_string += f"\t{key}: {' '.join(value)}\n" else: error_string += f"\t{key}: {error_dict[key]}\n" return error_string<file_sep>import requests, json from . import models, exceptions, config class AuthRequests: auth_root = "/auth" oauth = "/slack/" # keys kACCESS_TOKEN = "access_token" kKEY = "key" @classmethod def authenticate_oauth(cls, oauth_token: str) -> str: url = config.API_ROOT + cls.auth_root + cls.oauth response = requests.post(url, data={cls.kACCESS_TOKEN: oauth_token}) if not (key := response.json().get(cls.kKEY)): raise exceptions.InvalidOAuthToken( f"Invalid response {json.dumps(response.json(), indent=4)}" ) return key class AuthorizedRequest: cache = {} kACCEPT = "accept" kAUTHORIZATION = "authorization" def _fetch_user_key_(self, user_id: str) -> str: if (token := self.cache.get(user_id)) is None: try: oauth_token = models.authed_user.objects.get(pk=user_id).access_token token = AuthRequests.authenticate_oauth(oauth_token) self.cache[user_id] = token except models.authed_user.DoesNotExist: raise exceptions.MissingOAuthToken( "User needs to authenticate through Slack using /authenticate" ) return token def __init__(self, user_id: str): self.key = self._fetch_user_key_(user_id) def __getattr__(self, attr): if not hasattr(requests, attr): raise AttributeError("requests has no such method") def wrapper(*args, **kwargs): headers = requests.models.CaseInsensitiveDict() headers[self.kACCEPT] = "application/json" headers[self.kAUTHORIZATION] = f"Bearer {self.key}" kwargs.update(headers=headers) return getattr(requests, attr)(*args, **kwargs) return wrapper <file_sep>from django.urls import include, path from . import commands, views urlpatterns = [ path("commands/dhelp", commands.dhelp), path("commands/ticket", commands.create_ticket), path("commands/auth", commands.auth), path("callback", views.slack_callback), path("commands/status-check", commands.check_status), path("commands/status-change", commands.change_status), path("commands/print_statuses", commands.print_statuses), path("commands/my_tickets", commands.my_tickets), path("commands/set-description", commands.set_description), ] <file_sep>error_messages = dict() error_messages["auth_error"] = "{} Error: Unable to authenticate" error_messages["ticket_create"] = "{} Internal Error:\n{}" error_messages["required_field"] = "{} Error: missing required fields:\n{}" error_messages["my_tickets"] = "{} Internal Error:\n{}" <file_sep>""" Various exceptions """ class InvalidOAuthToken(Exception): pass class MissingOAuthToken(Exception): pass class InvalidHandshake(Exception): pass <file_sep>""" configuration settings """ import os CLIENT_ID = os.getenv("CLIENT_ID") SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN") CLIENT_SECRET = os.getenv("CLIENT_SECRET") API_ROOT = "http://localhost:8000" TEAM_ID = 1
61df9453ad23a8d1c5352815eb387e60f1fc46b9
[ "Markdown", "Python", "Text" ]
11
Markdown
Slugbotics/Sluggo-Slack
670bf5d749b467c40f0ec9aae5adeaaba61174e9
b717cb4ab071f139ea9ab6010e6576b65bc83adb
refs/heads/master
<repo_name>harounhajem/HealthDesk<file_sep>/Communication.cpp // // // #include "Communication.h" String CommunicationClass::ReadBytesUntil() { String recivedMessage = ""; if (Serial.available() > 0) { Serial.print("RCV: "); const int MAX_MESSAGE_LENGTH = 35; char buffer[MAX_MESSAGE_LENGTH]; size_t num_read = Serial.readBytesUntil('#', buffer, sizeof(buffer) - 1); buffer[num_read] = '\0'; // Set null at the end since String is NULL-terminated Serial.println(buffer); recivedMessage = buffer; } return recivedMessage; } String CommunicationClass::Read() { String recivedMessage = ""; if (Serial.available() > 0) { Serial.print("RCV: "); delay(15); // Read byte by byte while (Serial.available() > 0) { char msg = Serial.read(); // Convert byte to Char recivedMessage += msg; } Serial.println(recivedMessage); } return recivedMessage; } void CommunicationClass::init() { Serial.println("Init CommunicationClass"); } CommunicationClass Communication; <file_sep>/README.md # HealthDesk Here is the code, on the Arduino side, for adjusting the height of your motorized desk through Bluetooth. You will need my app for sending the commands to the Arduino slave. ![Image of WorkBench](http://store.featherlitefurniture.com/media/product/4fd/height-adjustable-table-automatic-854.jpg) <file_sep>/BT_TableControl.ino #include "Communication.h" #define BUTTON_UP 6 #define BUTTON_DOWN 5 CommunicationClass communication; String recivedMessage; String COMMAND_UP = "UP"; String COMMAND_DOWN = "DN"; unsigned long timer_ResetComndDelay = 0; void setup() { Serial.begin(9600); pinMode(BUTTON_UP, OUTPUT); pinMode(BUTTON_DOWN, OUTPUT); } void loop() { // Recive message recivedMessage = communication.ReadBytesUntil(); // Execute Command if (recivedMessage == COMMAND_UP) { Serial.println("EXEC: UP"); MoveUp(); timer_ResetComndDelay = millis(); } else if (recivedMessage == COMMAND_DOWN) { Serial.println("EXEC: DOWN"); MoveDown(); timer_ResetComndDelay = millis(); } else if (recivedMessage == "") { Reset(); } // Execute Timer // - blink and play sound // - cancel timer if user pushes buttons breaks } void Reset() { if (millis() - timer_ResetComndDelay > 12UL) { digitalWrite(BUTTON_UP, HIGH); digitalWrite(BUTTON_DOWN, HIGH); } } void MoveUp() { digitalWrite(BUTTON_UP, LOW); } void MoveDown() { digitalWrite(BUTTON_DOWN, LOW); }
f6bedcbfc2327ca2a9c279b07255b73336525160
[ "Markdown", "C++" ]
3
C++
harounhajem/HealthDesk
37cd930a99da03c518d34a15473149a439a05416
423faaf1051431742858d3427d88fa6e4214134d
refs/heads/master
<repo_name>MazeDev7/Jumping-Frogs-Puzzle-Solver<file_sep>/A-star/Frogs.cpp // // CIS479 // // Created by <NAME> on 5/25/17. // Copyright © 2017 <NAME>. All rights reserved. // #include <iostream> #include <vector> #include <queue> #include <set> #include <chrono> //https://stackoverflow.com/questions/22387586/measuring-execution-time-of-a-function-in-c #include "State.h" using namespace std; using namespace std::chrono; #define PRINT_STEPS 0 // show every step of the search? Reasonable for size 1 #define PRINT_SOLUTION 1 // show the optimal solution #define STEP_LIMIT 2000000 // limit the iterations /* Condenses the state into an int. Low 32 bits encode the state, high 32 bits contain the gap Pre: &state must be a valid address of a State object Post: returns a hash for the current state in the form of a 64-bit unsigned int */ uint64_t stateToHash(const State& state) { uint64_t hash = 0; for (int i = 0; i < state.length; ++i) { if (i == state.gap) { continue; // a 0 goes to gap } hash |= state.state[i] << i; } hash |= (uint64_t)(state.gap) << 32; return hash; } /* Runs the algorithm. Pre: size number of T or F. The whole puzzle size is then 2* size + 1. Size must be >0 useUnderestimate must be true A* , useGuess must be false B&B uniqueState must be true for A*, uniqueState must be false for B&B */ void runAlg(int size, bool useUnderestimate, bool uniqueState = true) { bool done; int searchSteps; State start(size, useUnderestimate); cout << "Doing " << (useUnderestimate ? "A*" : "B&B") << " with size " << size << ", Starting state: " << endl; start.print(); priority_queue<State, vector<State>> queue; queue.push(start); set<uint64_t> bannedStates; // alternative structure for fast exclusion of states already visited or in the queue if (uniqueState) { bannedStates.insert(stateToHash(start)); } done = false; searchSteps = 0; // safety limit for the while while (!done && searchSteps < STEP_LIMIT) { searchSteps++; State state = queue.top(); // pull state from the queue queue.pop(); // remove the taken element #if PRINT_STEPS cout << endl << "-------- step: " << searchSteps << ", distance: " << state.steps << endl; state.print(); #endif // expand the state for (Move move : {Move::left, Move::right, Move::jumpLeft, Move::jumpRight}) { if (state.moveLegal(move)) { #if PRINT_STEPS cout << "Move: "; switch (move) { case Move::left: cout << "move left"; break; case Move::right: cout << "move right"; break; case Move::jumpLeft: cout << "jump left"; break; case Move::jumpRight: cout << "jump right"; break; } cout << endl; #endif State newState(state, move); // create new state by applying the move #if PRINT_STEPS newState.print(); #endif if (newState.isFinal()) { cout << "The shortest solution has been found. It took " << searchSteps << " iterations! Solution is " << newState.steps << " steps long." << endl; #if PRINT_SOLUTION cout << "\nSolution:" << endl; newState.printPath(); #endif cout << endl; done = true; break; } // check if the state was visited / is in queue if (uniqueState) { if (bannedStates.find(stateToHash(newState)) != bannedStates.end()) { continue; // the new state is banned, so we skip it. } bannedStates.insert(stateToHash(newState)); } queue.push(newState); } } } if (searchSteps == STEP_LIMIT) { cout << "Reached limit of " << STEP_LIMIT << " iterations before reaching the solution." << endl; } } int main(void) { high_resolution_clock::time_point t1 , t2; int size = 1; cout << "Enter problem size (max 15): "; cin >> size; if (size > 15) { cout << "Game size is too large!" << endl; return 0; } cout << endl; // initialize time before calling method // t1 = high_resolution_clock::now(); // runAlg(size, false, false); // Branch and Bound // // initialize time after method ends // t2 = high_resolution_clock::now(); // figure out time passed before and after method call auto duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << "Branch and Bound took " << duration << " microseconds to execute.\n\n" << endl; t1 = high_resolution_clock::now(); runAlg(size, true, true); // A* t2 = high_resolution_clock::now(); duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << "A* algorithm took " << duration << " microseconds to execute." << endl; cin >> size; return 0; } <file_sep>/A-star/State.h // // State.h // // Created by <NAME> on 5/25/17. // Copyright © 2017 <NAME>. All rights reserved. // #pragma once using namespace std; // possible moves in the game enum class Move { left, // move thing right of the gap (higher index) to the left right, // move thing left of the gap (higher index) to the right jumpLeft, // etc.. jumpRight, none }; // parent class containing all stuff common to a game state in both algorithms. class State { public: bool* state; // 0 for F, 1 for T int length; // total size, not the toad/frog number int gap; // position of the gap int steps; // steps done so far bool useUnderestimate; int underestimate; vector<Move> path; State() : length(0), state(nullptr), gap(0), steps(0), useUnderestimate(false), underestimate(0) {}; // default constructor, not used // copy constructor, used when pulling from the queue (= queue.top()) State(const State& other) : length(other.length), steps(other.steps), gap(other.gap), useUnderestimate(other.useUnderestimate), underestimate(other.underestimate), path(other.path) { // first copy the state this->state = new bool[length]; for (int i = 0; i < this->length; ++i) { this->state[i] = other.state[i]; } } // constructor of a starting state State(int size, bool useGuess) : length(size * 2 + 1), gap(size), steps(0), useUnderestimate(useGuess), underestimate(0) { // init the starting position this->state = new bool[length]; // size F and T and the gap for (int i = 0; i < size; ++i) { this->state[i] = 0; } for (int i = size + 1; i < 2 * size + 1; ++i) { this->state[i] = 1; } } /* constructor of a state evolved from another state by making the given move. If the move is not possible, creates an inconsistent state and reports an error to cout. */ State(const State& other, Move move) : length(other.length), steps(other.steps + 1), gap(other.gap), useUnderestimate(other.useUnderestimate), underestimate(other.underestimate), path(other.path) { if (!other.moveLegal(move)) { cout << "Error - illegal move" << endl; return; } // copy the state this->state = new bool[length]; for (int i = 0; i < this->length; ++i) { this->state[i] = other.state[i]; } // perform the move switch (move) { case Move::left: // move item right of this->gap to the this->gap position and move the this->gap right this->state[this->gap] = this->state[this->gap + 1]; ++this->gap; break; case Move::right: this->state[this->gap] = this->state[this->gap - 1]; --this->gap; break; case Move::jumpLeft: this->state[this->gap] = this->state[this->gap + 2]; this->gap += 2; break; case Move::jumpRight: this->state[this->gap] = this->state[this->gap - 2]; this->gap -= 2; break; } path.push_back(move); if (useUnderestimate) { // For A*, otherwise guess stays at 0 updateUnderestimate(); } } /* Checks if the current move is possible Pre: move must be a valid "move" Post: returns false if move is not possible. returns true otherwise */ bool moveLegal(Move move) const { switch (move) { case Move::left: if (this->gap == this->length - 1) // gap is last, can't move from the right { return false; } break; case Move::right: if (this->gap == 0) // this->gap is first { return false; } break; case Move::jumpLeft: // must have two items right of the this->gap and different thing between if (this->gap >= this->length - 2 || this->state[this->gap + 1] == this->state[this->gap + 2]) { return false; } break; case Move::jumpRight: // must have two items left of the this->gap and different thing between if (this->gap <= 1 || this->state[this->gap - 1] == this->state[this->gap - 2]) { return false; } break; default: return false; } return true; } /* Checks if the game is finished in the current state Pre: No input parameter Post: returns true if the final solution is found. returns false otherwise */ bool isFinal(void) { bool finished = true; int size = this->length / 2; // loop to check if left side still contains frogs for (int i = 0; i < size; ++i) { if (this->state[i] == 0 || this->gap == i) { finished = false; } } // loop to check if left side still contains frogs for (int i = size + 1; i < this->length; ++i) { if (this->state[i] == 1 || this->gap == i) { finished = false; } } return finished; } /* recalculate guess of distance to the end Pre: No input parameter Post: modifies the current underestimate */ void updateUnderestimate(void) { this->underestimate = 0; int size = this->length / 2; // count number of frogs out of position for (int i = 0; i < size; ++i) { if (this->state[i] == 0 || gap == i) { this->underestimate++; } } // count number of toads out of position for (int i = size + 1; i < this->length; ++i) { if (this->state[i] == 1 || gap == i) { this->underestimate++; } } } /* This method returns the score of the state Pre: No input parameter Post: returns the current steps + underestimate */ int score(void) const { return steps + underestimate; } // score of the state. Different implementation by used algorithm. /* Operator overloading > symbol to allow comparison of objects for priority queue sorting Pre: other must contain a valid address of a State object Post: returns true if left objects score is less then right objects score */ bool operator<(const State& other) const { // lower score is better -> higher in order. return this->score() > other.score(); } /* operator overloading = to allow deep copy of object Pre: other must contain a valid address of a State object Post: returns the the "left object" which contains data of the "right object" */ State& operator=(const State& rhs) // for the = when pulled out of queue, must be implemented explicitely { if (this != &rhs) { this->steps = rhs.steps; this->length = rhs.length; this->gap = rhs.gap; this->useUnderestimate = rhs.useUnderestimate; this->underestimate = rhs.underestimate; delete[] this->state; this->state = new bool[length]; for (int i = 0; i < this->length; ++i) { this->state[i] = rhs.state[i]; } this->path = rhs.path; } return *this; } /* Prints out the current state Pre: No input, but must have an active State object Post: Prints out the state as e.g. 0 _ 1 0 1 */ void print(void) const { for (int i = 0; i < this->length; ++i) { if (this->gap == i) { cout << "_ "; } else { cout << this->state[i] << " "; } } cout << endl; } /* prints the move set leading to this state Pre: No input, but must have an active State object Post: prints the move set leading to this state */ void printPath() { for (Move move : path) { switch (move) { case Move::left: cout << "move left" << endl; break; case Move::right: cout << "move right" << endl; break; case Move::jumpLeft: cout << "jump left" << endl; break; case Move::jumpRight: cout << "jump right" << endl; break; } } } // Destructor ~State() { delete[] state; }; }; <file_sep>/README.md # Jumping-Frogs-Puzzle-Solver This is a program written in C++ that will run two different algorithms of solving the puzzle.
f19627b2241849425c5fc42116ccb33162142a7e
[ "Markdown", "C++" ]
3
C++
MazeDev7/Jumping-Frogs-Puzzle-Solver
fccab8888bde8b11959bce36451a0300671d3d4d
3daf031a83373143369bab0860f004f6fa4ce96e
refs/heads/master
<repo_name>Heroi211/Exercicios-resolvidos-<file_sep>/exerc1/telas.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc1 { class telas { public static computadores TelaComp() { Console.WriteLine("Digite o Id do computador: "); int Id = int.Parse(Console.ReadLine()); Console.WriteLine("Digite o nome do computador: "); string nome = Console.ReadLine(); Console.WriteLine("Digite o preço do computador : "); double preco = double.Parse(Console.ReadLine()); Console.WriteLine("Digite a quantidade em estoque: "); int quantidade = int.Parse(Console.ReadLine()); return new computadores(Id, nome, preco, quantidade); } public static televisoes TelaTele() { Console.WriteLine("Digite o Id da televisão: "); int Id = int.Parse(Console.ReadLine()); Console.WriteLine("Digite o nome da televisão: "); string nome = Console.ReadLine(); Console.WriteLine("Digite o preço da televisão : "); double preco = double.Parse(Console.ReadLine()); Console.WriteLine("Digite a quantidade em estoque: "); int quantidade = int.Parse(Console.ReadLine()); return new televisoes(Id, nome, preco, quantidade); } } } <file_sep>/exerc1/televisoes.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc1 { class televisoes : Equipamento { public int Id { get; set; } public string Nome { get; set; } public double Preco { get; set; } public int Quantidade { get; set; } public televisoes(int Id, string Nome, double Preco, int Quantidade) { this.Id = Id; this.Nome = Nome; this.Preco = Preco; this.Quantidade = Quantidade; } public override double CalculaValor() { double valortotal; return valortotal = Quantidade * Preco; } public override string ToString() { return "A televisão de Id: " + Id + "/ nome: " + Nome + "/ R$" + Preco.ToString("F2"); } } } <file_sep>/exerc1/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc1 { class Program { public static List<Equipamento> equip = new List<Equipamento>(); public static int n; static void Main(string[] args) { try { Console.WriteLine("Quantos equipamentos pretende cadastrar?"); n = int.Parse(Console.ReadLine()); } catch (Exception e) { Console.WriteLine("Erro inesperado"); Console.WriteLine(e.Message); } try { for (int i = 0; i < n; i++) { Console.WriteLine("Vai cadastrar computadores ou televisoes? C ou T"); char resposta = char.Parse(Console.ReadLine()); if (resposta == 'C' || resposta == 'c') { Equipamento X = telas.TelaComp(); double valorComp = X.CalculaValor(); Console.WriteLine(X); Console.WriteLine("O valor total dos computadores é " + valorComp.ToString("F2")); } else if (resposta == 't' || resposta == 'T') { Equipamento Y = telas.TelaTele(); double valorComp = Y.CalculaValor(); Console.WriteLine(Y); Console.WriteLine("O valor total dos computadores é " + valorComp.ToString("F2")); } } } catch(Exception e) { Console.WriteLine("Caracter inválido: "); Console.WriteLine(e.Message); } for (int i = 0;i< equip.Count;i++) { Console.WriteLine("Os equipamentos cadastrados são: " + equip[i]); } Console.ReadLine(); } } } <file_sep>/exerc1/Equipamento.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc1 { abstract class Equipamento { public abstract double CalculaValor(); } } <file_sep>/README.md # Exercicios-resolvidos- <file_sep>/exerc1/computadores.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc1 { class computadores : Equipamento { public int Id { get; set; } public string Nome { get; set; } public double Preco { get; set; } public int Quantidade { get; set; } public computadores (int Id,string Nome,double Preco, int Quantidade) { this.Id = Id; this.Nome = Nome; this.Preco = Preco; this.Quantidade = Quantidade; } public override double CalculaValor() { double valortotal; return valortotal = Quantidade * Preco; } public override string ToString() { return "O computador de Id: " + Id + "/ nome:" + Nome + "/ R$" + Preco.ToString("F2"); } } }
931186e69b43a0f8756b6de5d5404561b0133074
[ "Markdown", "C#" ]
6
C#
Heroi211/Exercicios-resolvidos-
6a087214d789348d20f0d8a22ad6fd0989b634ac
f5712f46aed00b976bab273c7116192241d5a641
refs/heads/master
<file_sep>enum messageSet { MSG_SDEFAULT = 0, MSG_SDEFAULT2, MSG_PRIORITY, //MSG_PRIORITY2 MSG_LOG2PRINTER = 4, MSG_LOCALDIVERTER, MSG_ENTERPW, // no 7 MSG_SET_TIMEOUT = 8, // no 9 MSG_ALARM = 10, // no 11 MSG_SETTING = 12, MSG_DROPEN, MSG_CIC, MSG_ARVALRT, MSG_ODUE, MSG_RTRN, MSG_PURGE, // no 19 MSG_NOCOMM = 20, // no 21,22,23 MSG_SET_CLOCK = 24, MSG_PENDING, MSG_SEND, MSG_RETURN, MSG_TIMEOUT, MSG_ERROR, MSG_REMOTESTA, MSG_FUNCTION, MSG_SET_HOURS, // no 33-37 MSG_INC_DEC = 38, MSG_ON_OFF, MSG_SND_RTN, MSG_ARRIVE_SND, MSG_ALARM_SND, MSG_ALARM_RESET, MSG_RESET, MSG_SYSBUSY, // no 46,47 MSG_SHOW_COMM = 48, MSG_YES_NO, MSG_SET_STANAMES, MSG_OPTIC_BLOCKED, MSG_AT, // points to message before station 1 // no 53-60 MSG_FROM = 61, // .. // no 62-69 MSG_TO = 70, // .. // no 71-78 MSG_F1_PRESSURE = 79, MSG_F2_VACUUM, MSG_AUTO_PURGE, MSG_DEF_STATIONS, MSG_SEL_STATION, MSG_END_OF_MENU, MSG_NOT_READY, MSG_SAVE_ERROR, MSG_MSTACKING, MSG_RSTACKING, MSG_RESET_COUNT, MSG_TIME, MSG_DATE, MSG_TRANS_COUNT, MSG_FLAG_SET, // on/off flag setting MSG_DATE_TIME, MSG_DONTUSE, MSG_SETPASSWORD, MSG_SETCLEAR, MSG_TURNAROUND, MSG_MAINREMOTE, MSG_PAR_VALUE, MSG_ADV_SETUP, MSG_RMTALRTSTAT, }; #define MSG_SDEFAULT 0 #define MSG_SDEFAULT2 1 #define MSG_PRIORITY 2 #define MSG_LOG2PRINTER 4 #define MSG_LOCALDIVERTER 5 #define MSG_ENTERPW 6 //#define MSG_TESTING 8 #define MSG_SET_TIMEOUT 8 #define MSG_ALARM 10 #define MSG_SETTING 12 #define MSG_DROPEN 13 #define MSG_CIC 14 #define MSG_ARVALRT 15 #define MSG_ODUE 16 #define MSG_RTRN 17 #define MSG_PURGE 18 #define MSG_NOCOMM 20 #define MSG_SET_CLOCK 24 #define MSG_PENDING 25 #define MSG_SEND 26 #define MSG_RETURN 27 #define MSG_TIMEOUT 28 #define MSG_ERROR 29 #define MSG_REMOTESTA 30 #define MSG_FUNCTION 31 #define MSG_SET_HOURS 32 #define MSG_INC_DEC 38 #define MSG_ON_OFF 39 #define MSG_SND_RTN 40 #define MSG_ARRIVE_SND 41 #define MSG_ALARM_SND 42 #define MSG_ALARM_RESET 43 #define MSG_RESET 44 #define MSG_SYSBUSY 45 #define MSG_SHOW_COMM 48 #define MSG_YES_NO 49 #define MSG_SET_STANAMES 50 #define MSG_OPTIC_BLOCKED 51 #define MSG_AT 52 // points to message before station 1 #define MSG_FROM 60 // .. #define MSG_TO 68 // .. #define MSG_F1_PRESSURE 76 #define MSG_F2_VACUUM 77 #define MSG_AUTO_PURGE 78 #define MSG_DEF_STATIONS 79 #define MSG_SEL_STATION 80 #define MSG_END_OF_MENU 81 #define MSG_NOT_READY 82 #define MSG_SAVE_ERROR 83 #define MSG_MSTACKING 84 #define MSG_RSTACKING 85 #define MSG_RESET_COUNT 86 #define MSG_TIME 87 #define MSG_DATE 88 #define MSG_TRANS_COUNT 89 #define MSG_FLAG_SET 90 // on/off flag setting #define MSG_DATE_TIME 91 #define MSG_DONTUSE 92 #define MSG_SETPASSWORD 93 #define MSG_SETCLEAR 94 #define MSG_TURNAROUND 95 #define MSG_MAINREMOTE 96 #define MSG_PAR_VALUE 97 #define MSG_ADV_SETUP 98 #define MSG_RMTALRTSTAT 99 <file_sep>/*************************************************************************** Samples\Random.c Z-World, Inc, 2000 This program generates pseudo-random integers between 2000 and 2999 The library rand() function returns a floating-point value (not POSIX). ***************************************************************************/ #class auto #define STDIO_ENABLE_LONG_STRINGS int UID_Encode(char *UID, char *Result); int UID_Decode(char *UID, char *Result); void show_me(char *UID); void main () { int i; char id[14]; char Res[16]; // demo some numbers show_me("154224091045"); show_me("123456789012"); show_me("12345678901"); show_me("1234567890"); show_me("123456789"); show_me("12345678"); show_me("1234567"); show_me("123456"); show_me("12345"); show_me("1234"); show_me("123"); show_me("12"); show_me("1"); } void show_me(char *id) { int i; char Res[14]; char Reid[14]; i = UID_Encode(id, Res); printf("%d %s -> %02X%02X%02X%02X%02X\n", i, id, Res[0], Res[1], Res[2], Res[3], Res[4]); i = UID_Decode(Res, Reid); printf("%d %s <- %02X%02X%02X%02X%02X\n\n", i, Reid, Res[0], Res[1], Res[2], Res[3], Res[4]); //printf("%d %02X%02X%02X%02X%02X = %s\n\n", i, Res[0], Res[1], Res[2], Res[3], Res[4], Reid); return; } int UID_Encode(char *UID, char *Result) { // convert 12 byte string into 5 byte UID // Result must be sized to handle 5 bytes // Return -1 if invalid UID or 0 if success // char Buf[3]; // int i; // int res; // for (i=0; i<6; i++) // { // strncpy(Buf, &UID[i*2], 2); // res = atoi(Buf); // if (res <= 99 && res >= 0) Result[i] = res; // else return -1; // } // return 0; int i; int hval; int carry; int uidlen; unsigned long lval; unsigned long llast; unsigned long incr; char hdig[4]; // high 3 digits char ldig[10]; // low 9 digits // deal with length of number up to 12 digits uidlen = strlen(UID); if (uidlen < 10) { // simple math on 4 byte numbers hval = 0; lval = atol(UID); } else { // split after 9th digit and get decimal equivalents strncpy(hdig, UID, uidlen-9); hdig[3]=0; strcpy(ldig, &UID[uidlen-9]); hval = atoi(hdig); lval = atol(ldig); } // do the math incr = 1000000000; llast = lval; carry=0; for (i=0; i<hval; i++) { // long math loop lval = lval + incr; if (lval<llast) carry++; llast = lval; } // transfer back into Result Result[0] = (char)carry; Result[1] = (char)((lval >> 24) & 0xFF) ; Result[2] = (char)((lval >> 16) & 0xFF) ; Result[3] = (char)((lval >> 8) & 0XFF); Result[4] = (char)((lval & 0XFF)); return 0; } int UID_Decode(char *UID, char *Result) { // convert 5 byte UID into 12 byte string // Result must be sized to handle 12+1 bytes // Return -1 if invalid UID or 0 if success // int i; // int res; // for (i=0; i<6; i++) // { // if (UID[i] >=0 && UID[i] <=99) sprintf(&Result[i*2], "%02d", UID[i]); // else return -1; // } // return 0; int i; unsigned long lval; unsigned long ba; unsigned long bm; unsigned long lo; int hi; int hval; // setup the math lval = (unsigned long)UID[1] << 24; lval = lval | (unsigned long)UID[2] << 16; lval = lval | (unsigned long)UID[3] << 8; lval = lval | (unsigned long)UID[4]; hval = (int)(UID[0]<<4) + (int)((lval & 0xF0000000)>>28); // how many times to loop lo = lval & 0x0FFFFFFF; // highest byte in hi hi=0; ba = 0x10000000; // add this bm = 1000000000; // mod this for (i=0; i<hval; i++) { // do the long math lo = lo + ba; // add hi += (int)(lo / bm); // mod lo = lo % bm; // div } // now put into string if (hi>0) { // longer than 9 digits snprintf(Result, 13, "%d%09lu", hi, lo); Result[12]=0; // null term } else { // less or equal to 9 digits sprintf(Result,"%lu", lo); } return 0; } <file_sep>/******************************************************************* MAINSTREAM_REMOTE_V4xx.C Colombo Semi-Automatic Pneumatic Tube Transfer System Purpose: Remote station control program. Processes local i/o and main_station control commands. Target: Z-World BL2500 Rabbit Language: Dynamic C v9.x Created: Aug 16, 2008 by <NAME> (C) MS Technology Solutions History: 12-Jun-06 v301 Original version created from RMOT235.c 21-Sep-06 v302 skipped version to sync with main 21-Sep-06 v303 Invert logic state of read-bank inputs 24-Sep-06 v304 Further refinement of I/O, add InUse/CIC/Flashing 22-Oct-06 v307 Sync version with Main. Integrate 4 open-door alerts. 04-Jan-07 v311 Sync version with Main. Extend command to 5 data bytes. 08-Jan-07 v312 Do not invert requestToSend inputs 10-Jan-07 v313 Setup for using ALL_DEVICES = 0xFF in .devAddr 14-Jan-07 v314 Integrate turnaround head diverter 19-Jan-07 v316 Diverter map missing [8] and causing out-of-bounds crash 24-Jan-07 v318 Continued improvements 25-Jan-07 v319 Enable TX control a bit sooner to improve communications HD & slave both known at station 8, so ready/not-ready commands now return devAddr 27-Jan-07 v320 fix bug returning response with device address (THIS_LPLC) -> (THIS_LPLC-1) Clean up implentation & reporting of latched arrival interrupt 28-Jan-07 v321 Delay response commands to give main time to be ready 01-Feb-07 v322 Switch from standard blower to heavy duty APU 03-Feb-07 v323 Initialize blower when starting up head diverter 11-Feb-07 v326 Handle failure of readDigBank when rn1100 is failed/missing Fix bug in sending arrival status to main 27-Mar-07 v342 Invert logic state of carrier in chamber and arrival optics 31-Mar-07 v343 Revert to original logic of CIC and arrival optics Set digital inputs low upon loss of connection to RN1100 10-Apr-07 v346 Set diverter addr-2 passthrough to port 4 instead of 1 03-May-07 v347 Delay clearing of arrival latch for 1 second 04-May-07 v348 Fix handling of latched arrival 24-May-07 v349 Fix bug in CIC lights not working, no IO Shift 05-Jun-07 v350 Don't clear latchedCarrierArrival until transaction is complete (remove 1 second clear) 15-Jul-07 v351 Improve exercise_io so that arrival alert and inuse light up Report latched arrival only when state is wait_for_remote_arrive Implement feature for remote alternate address request-to-send, to send to master or slave 23-Jul-07 v352 Implement compile-time selectable blower interface 25-Jul-07 v353 Bug fix for standard blower in head diverter setup (blwrConfig must equal 1) 27-Jul-07 v354 Shore up possible weakness in head diverter optic detection Head diverter arrival optic is on input 0 31-Jul-07 v355 Don't use interrupt for head diverter, raw arrival input only 29-Aug-07 v356 DEVELOPMENT VERSION 29-Dec-07 v365 Released Version - sync w/ main Get blower selection by main menu setting Get diverter port mapping configuration by main menu setting Support for point to point configuration, remote with one station, no diverter, re-mapped I/O 13-Apr-08 v366 Support for reporting blower errors Reduce blower timeout to 12 seconds so it happens before carrier lift timeout 16-Apr-08 v367 Fix mistake in initBlower: blowerPosition==0 --> blowerPosition()==0 Return blowerPosition to the main station for head diverters with APU 16-Aug-08 v400 Created from MAINSTREAM_REMOTE_V367.C Now handles only one dedicated station 19-Oct-08 v402 Clear request-to-send latch on setting diverter 16-Nov-08 v403 Fix up to operate point to point over RS485 06-Dec-08 v404 Added handling of secure transaction 24-Dec-08 v405 Improve handling of secure transaction 30-Dec-08 v406 Improve robustness of secure transaction 05-Jan-09 v407 Fix handling of alert for door open during transaction 03-Mar-09 v408 Bump version to 409 Implement card parameters 19-Apr-11 v410 When notified of purge mode, flash in-use and cic alternating 07-Sep-13 v411 Additional card range block and parameters 31-Dec-13 v412 Add individual user identification 06-Jun-14 v413 Send every card scan 15-Aug-14 v414 Improve com when sending UID's; Set limit to 1100 users 15-Dec-14 v415 24-Oct-15 v416 Include Point-to-Point support (card data over RS485) 02-Jan-16 v417 Support for blower controlled by remote (vacuum pull) 22-May-16 v418 Setup for card format parameter 26 or 40 bits cardNumbits = = param.cardFormat Changed lib\wiegand_v2.lib to accept 4-bit pin input 26-Jan-17 v419 Update mapping of 26 bit to right justify site code w/ card # (one big number) 05-Nov-17 v420 Mainstream_Touch_Remote first version to support Reach color touchscreen Including local logging and station selection by touch-screen v421 Support for landscape. Was developed only for portrait. ***************************************************************/ #memmap xmem // Required to reduce root memory usage #class auto #define FIRMWARE_VERSION "TOUCH REMOTE V4.21" #define VERSION 4 #define SUBVERSION 21 // compile as "STANDARD" or "POINT2POINT" remote #define RT_STANDARD 1 #define REMOTE_TYPE RT_STANDARD //#define REMOTE_TYPE RT_POINT2POINT // For Point2Point do not use TCPIP. Could fix this though (activeStations) //int lastcommand; // for debug #define USE_TCPIP 1 // define PRINT_ON for additional debug printing via printf // #define PRINT_ON 1 #use "bl25xx.lib" Controller library #use "rn_cfg_bl25.lib" Configuration library #use "rnet.lib" RabbitNet library #use "rnet_driver.lib" RabbitNet library #use "rnet_keyif.lib" RN1600 keypad library #use "rnet_lcdif.lib" RN1600 LCD library #define USE_BLOWER #use "MAINSTREAM.lib" Mainstream v4xx function library //#define WIEGAND_DEBUG //#define WIEGAND_VERBOSE #use "wiegand_v2.lib" RFID card reader interface // RabbitNet RN1600 Setup //int DevRN1600; // Rabbit Net Device Number Keypad/LCD int DevRN1100; // Rabbit Net Device Number Digital I/O //configure to sinking safe state #define OUTCONFIG 0xFFFF // setup for Reach color LCD #define LCD_USE_PORTE // tell Reach library which serial port to use //#define REACH_LIB_DEBUG debug #use Reach101.lib // Setup interrupt handling for carrier arrival input // Set equal to 1 to use fast interrupt in I&D space #define FAST_INTERRUPT 0 int latchCarrierArrival; void my_isr1(); void arrivalEnable(char how); // Communications data structures #define NUMDATA 6 struct iomessage /* Communications command structure */ { char device; char command; char station; char data[NUMDATA]; }; struct stats_type // transaction summary statistics { long trans_in; // incoming transactions long trans_out; // outgoing transactions int deliv_alarm; // incomplete delivery timeout alarm int divert_alarm; // diverter timeout alarm int cic_lift_alarm; // carrier lift timeout alarm int door_alarm; // door open during transaction }; struct trans_log_type // transaction logging info { unsigned long trans_num; // transaction number unsigned long start_tm; // time of departure unsigned int duration; // duration of event in seconds // time of arrival (or alarm) char source_sta; // where it came from char dest_sta; // where it went to char status; // transaction status (0-63) or other event (64-255) // 0 = no malfunction or other transaction status // 1 = diverter timeout // 2 = carrier exit (lift) timeout // 3 = delivery overdue timeout // 4 = blower timeout // 5 = station not ready after setting diverter or cancel dispatch // 6 = transaction cancelled/aborted (future) // 64 = Door opened event char flags; // transaction flags // xxxx xxx1 = Stat Transaction // xxxx xx1x = Carrier return function // xxxx x1xx = Auto return function // xxxx 1xxx = Door opened in transaction // other event flags defined elsewhere // IF TRANSLOG GROWS MAKE SURE UDP COMMAND CAN HOLD IT ALL (NUMUDPDATA) }; // define transaction and event logging status and flags #define STS_DIVERTER_TOUT 1 #define STS_DEPART_TOUT 2 #define STS_ARRIVE_TOUT 3 #define STS_BLOWER_TOUT 4 #define STS_TRANS_CANCEL 5 #define STS_CANCEL_BY_SEND 6 #define STS_CANCEL_BY_CIC 7 #define STS_CANCEL_BY_REMOTE 8 #define STS_CANCEL_BY_STACK 9 #define LAST_TRANS_EVENT 31 #define FLAG_STAT 0x01 #define FLAG_CRETURN 0x02 #define FLAG_ARETURN 0x04 #define FLAG_DOOROPEN 0x08 #define FLAG_ARETURNING 0x10 #define FLAG_SECURE 0x20 // define event logging status and flags #define ESTS_DOOROPEN 64 #define EFLAG_MAINDOOR 0x01 #define EFLAG_SUBSDOOR 0x02 #define EFLAG_EXTRA_CIC 0x04 #define ESTS_MANPURGE 65 #define ESTS_AUTOPURGE 66 #define ESTS_SECURE_REMOVAL 32 #define ESTS_CARD_SCAN 33 #define ESTS_UNAUTH_CARD 34 #define ESTS_BLANK 255 #define NUMUDPDATA 18 struct UDPmessageType // UDP based messages { char device; char devType; // M for main station char command; // can be heartbeat, event, transaction char station; unsigned long timestamp; char data[NUMUDPDATA]; }; // Define communications using TCP/IP (UDP) #ifdef USE_TCPIP #define TCPCONFIG 106 // 106 is an empty config for run-time setup //#define USE_DHCP //#define USE_ETHERNET 1 #define MAX_UDP_SOCKET_BUFFERS 1 #define DISABLE_TCP // Not using TCP #define MY_STATIC_IP "192.168.0.11" #define MY_BASE_IP "192.168.0.3%d" char myIPaddress[18]; // string to hold runtime IP address #define MY_IP_NETMASK "255.255.255.0" #define LOCAL_PORT 1235 // for inbound messages // #define REMOTE_IP "255.255.255.255" //255.255.255.255" /*broadcast*/ #define REMOTE_PORT 1234 // for outbound messages #use "dcrtcp.lib" udp_Socket sock; int sendUDPHeartbeat(char sample); int sendUDPcommand(struct UDPmessageType message); int getUDPcommand(struct UDPmessageType *message); void processUDPcommand(struct UDPmessageType message); #endif // Including parameter block structure // Parameters are NOT read to / written from FLASH #define UIDSize 1000 // UIDLen more than 5 is not supported by UID_Send due to command length limit #define UIDLen 5 struct par_block_type { // These parameters are defined on the fly at run-time char opMode; // STD_REMOTE or HEAD_DIVERTER char subStaAddressing; // to indicate if substation can select slave for destination char blowerType; char portMapping; //char cardL3Digits; // Constant left 3 digits of valid secure cards //unsigned long cardR9Min; // Secure card ID minimum value for the right 9 digits //unsigned long cardR9Max; // Secure card ID maximum value for the right 9 digits //char card2L3Digits; // Constant left 3 digits of valid secure cards //unsigned long card2R9Min; // Secure card ID minimum value for the right 9 digits //unsigned long card2R9Max; // Secure card ID maximum value for the right 9 digits char cardCheckEnabled; // enable individual card id checking char cardFormat; // defines type of card (26 or 40 bits) char stationNum; char stationName[12]; char mainName[12]; char remoteAudibleAlert; char orientLandscape; // which screen orientation char reserved[71]; unsigned long UIDSync; // timestamp (seconds) since last good block char UID[UIDSize][UIDLen]; } param; #define STD_REMOTE 0 #define HEAD_DIVERTER 1 #define SLAVE 0x08 // Station number of the slave #define SLAVE_b 0x80 // Bit representation char THIS_DEVICE; // board address for communications and setup char THIS_DEVICE_b; char MY_STATIONS; // to mask supported stations char IO_SHIFT; // to map expansion board i/o char diverter_map[9]; // to assign diverter positions to stations // Global variables unsigned long thistime, lasttime, lost; /* Declare general function prototypes */ void msDelay(unsigned int msec); //char bit2station(char station_b);// station_b refers to bit equivalent: 0100 //char station2bit(char station); // station refers to decimal value: 3 --^ void init_counter(void); void process_local_io(void); void set_remote_io(char *remotedata); void init_io(void); void exercise_io(void); void send_response(struct iomessage message); char get_command(struct iomessage *message); void process_command(struct iomessage message); void processCardReads(void); void enable_commands(void); void arrival_alert(char code, char station); char isMyStation(char station); void toggleLED(char LEDDev); void maintenance(void); char Timeout(unsigned long start_time, unsigned long duration); int readParameterSettings(void); int writeParameterSettings(void); /* Declare local and expansion bus input prototypes */ char carrierInChamber(char station_mask); char doorClosed(char station_mask); char carrierArrival(char station_mask); char requestToSend(char station_mask); char requestToSend2(char station_mask); //char diverter_pos(void); /* Declare local and expansion bus output prototypes */ char rts_latch; // Used for latching requestToSend char rts2_latch; // Used for latching 2nd requestToSend (to slave) void inUse(char how, char station_b); void alert(char how, char station_b); void alarm(char how); void doorAlert(char how); void unlockDoor(void); // void diverter(char how); //void setDiverter(char station); //void processDiverter(void); void setDiverterMap(char portMap); char secTimeout(unsigned long ttime); // TRANSACTION LOG DEFINITIONS void initTransLog(void); void addTransaction(struct trans_log_type trans, char xtra); //void addSecureTransaction(struct secure_log_type); int getTransaction(long entry, struct trans_log_type *trans); long findTransaction(unsigned long transNum); long sizeOfTransLog(void); void checkSerialFlash(void); void analyzeEventLog(void); struct trans_log_type translog; // can this be encapsulated? unsigned long transactionCount(void); void loadTransactionCount(void); void resetTransactionCount(unsigned long value); void resetStatistics(void); // TOUCHSCREEN DEFINITIONS void lcd_splashScreen(char view); void lcd_drawScreen(char whichScreen, char *title); char systemStateMsg; int lastBkColor; void lcd_resetMsgBackColor(void); int lcd_Center(char * string, char font); char lcd_ShowMenu(char menuLevel, char page); int lcd_RefreshScreen(char refresh); void lcd_ProcessButtons(void); char lcd_SendButton(void); int lcd_SelectChoice(char *choice, char *label, char *optZero, char *optOne); char lcd_GetNumberEntry(char *description, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units, char max_digits, char nc_as_ok); void lcd_ShowKeypad(char opts); void lcd_showPage(long thisPage, long lastPage); void lcd_showTransPage(long page, long lastPage, char format); void lcd_showTransactions(char format); void lcd_showTransSummary(void); char lcd_enableAdvancedFeatures(char menu_level, char * description); char lcd_getPin(char *PIN, char *description); void lcd_enterSetupMode(char operatorLevel); char lcd_ProcessMenuItem(char menu_idx, char *menu_level); void lcd_helpScreen(char view); void lcd_show_inputs(void); unsigned long menu_timeout; void set_lcd_limits(void); int lcd_max_x; // to manage orientation int lcd_max_y; char echoLcdToTouchscreen; // to control echo of lcd messages to the touch screen #define lcd_NO_BUTTONS "" #define lcd_WITH_BUTTONS " " #define LCD_DIM 0 #define LCD_BRIGHT 4 #define BMP_COLOMBO_LOGO 1 #define BMP_green_light 2 #define BMP_red_light 3 #define BMP_check_box 4 #define BMP_check_box_click 5 #define BMP_button_on 6 #define BMP_button_off 7 #define BMP_button_up 8 #define BMP_button_dn 9 #define BMP_input_box 10 #define BMP_med_button 11 #define BMP_med_button_dn 12 #define BMP_long_button 13 #define BMP_long_button_dn 14 #define BMP_92x32_button 15 #define BMP_92x32_button_dn 16 #define BMP_med_red_button 17 #define BMP_med_red_button_dn 18 #define BMP_med_grn_button 19 #define BMP_med_grn_button_dn 20 #define BMP_92x40_button 21 #define BMP_92x40_button_dn 22 #define BMP_med_yel_button 23 #define BMP_med_yel_button_dn 24 #define BMP_ltgrey_light 25 #define BTN_MENU 1 #define BTN_DIRECTORY 2 //#define BTN_HELP 3 #define BTN_STAT 4 #define BTN_CRETURN 5 #define BTN_ARETURN 6 #define BTN_SECURE 7 #define BTN_FUTURE 8 #define BTN_OK 10 #define BTN_CANCEL 11 #define BTN_SAVE 12 #define BTN_PREV 13 #define BTN_NEXT 14 #define BTN_HELP 15 #define BTN_YES_ON 16 #define BTN_NO_OFF 17 #define BTN_DEL 18 #define BTN_EXIT 19 #define BTN_MNU_FIRST 21 #define BTN_SEND 22 // USER ID MANAGEMENT DEFINITIONS int UID_Add(char *ID); int UID_Del(char *ID); int UID_Search(char *ID); int UID_Get(int UIndex); unsigned int UID_Cksum(); int UID_Decode(char *UID, char *Result); int UID_Encode(char *UID, char *Result); int UID_Not_Zero(char *UID); void UID_Clear(char *UID); // Declare watchdog and powerlow handlers char watchdogCount(void); char powerlowCount(void); void incrementWDCount(void); void incrementPLCount(void); void loadResetCounters(void); void checkMalfunction(void); // Digital I/O definitions char outputvalue [6]; // buffer for some outputs char remoteoutput [5]; // buffer for main commanded outputs // INPUTS int readDigInput(char channel); int readDigBank(char bank); // banks 0,1 on Coyote; banks 2,3 on RN1100 // dio_ON|OFF must be used ONLY in primatives readDigInput and setDigOutput // they reflect the real state of the logic inputs and outputs #define dio_ON 0 #define dio_OFF 1 #define di_HDArrival readDigInput(0) #define di_carrierArrival readDigInput(0) #define di_requestToSend readDigInput(1) #define di_requestToSend2 readDigInput(8) #define di_doorClosed readDigInput(2) #define di_carrierInChamber readDigInput(3) #define di_remoteAddress ((readDigBank(0) & 0xF0) >> 4) /* BLOWER BUT NO DIVERTER IN THIS VERSION #define USE_DIVERTER #define USE_BLOWER #define di_diverterPos (readDigBank(1) & 0x0F) */ #define di_shifterPosIdle 1 #define di_shifterPosPrs 0 #define di_shifterPosVac 0 // OUTPUTS void setDigOutput(int channel, int value); #define do_shift 0 #define do_doorAlert(which,value) setDigOutput(0,value) #define do_arrivalAlert(which,value) setDigOutput(1,value) #define do_CICLight(which,value) setDigOutput(2,value) #define do_inUseLight(which,value) setDigOutput(3,value) #define do_doorUnLock(value) setDigOutput(4,value) //#define do_inUseLight2(which,value) setDigOutput(5,value) // for remotes, vac and prs are reversed (prs=O5; vac=O6) #define do_blowerVac(value) setDigOutput(5,value) #define do_blowerPrs(value) setDigOutput(6,value) #define do_blower(value) #define do_secureTransLight(value) setDigOutput(7,value) // inUseLight on output 3,4,7 causes RS485 transmitter to enable (PA4) // Root cause was use of static CHAR elements in maintenance() instead of static INT //#define do_alarm(value) setDigOutput(xx+do_shift,value) /* BLOWER BUT NO DIVERTER IN THIS VERSION #define do_diverter(value) setDigOutput(4+do_shift,value) #define do_blower(value) setDigOutput(5+do_shift,value) #define do_blowerVac(value) setDigOutput(6+do_shift,value) #define do_blowerPrs(value) setDigOutput(7+do_shift,value) */ #define ALARM_MASK 0x20 // #define beep(value) rn_keyBuzzerAct(DevRN1600, value, 0) void inUse(char how, char station_b); void inUse2(char how, char station_b); void alarm(char how); /* "how" types & values and other constants */ #define ON 0xFF #define OFF 0x00 #define FLASH 0x01 #define READY 0x01 #define NOT_READY 0xFF //#define TRUE 0xFF //#define FALSE 0x00 #define aaRESET 0x00 #define aaSET 0x01 #define aaTEST 0x02 #define ToREMOTE 0x01 #define ToMAIN 0x02 #define ALL_DEVICES 0xFF /* Serial communications send and receive commands */ #define NAK 0x15 #define ACK 0x06 #define STX 0x02 #define ETX 0x03 #define DINBUFSIZE 63 #define DOUTBUFSIZE 63 #define SET_DIVERTER 'A' #define DIVERTER_STATUS 'B' #define REMOTE_PAYLOAD 'C' #define SECURE_REMOVAL 'C' #define ACK_SECURE_REMOVAL 'D' #define RETURN_INPUTS 'E' #define INPUTS_ARE 'E' #define SET_OUTPUTS 'G' #define CLEAR_OUTPUTS 'H' #define SET_OPMODE 'I' #define ARE_YOU_READY 'J' #define RETURN_EXTENDED 'K' #define SET_TRANS_COUNT 'L' #define SET_DATE_TIME 'M' #define SET_STATION_NAME 'N' #define CANCEL_PENDING 'O' #define TAKE_COMMAND 'P' #define DISPLAY_MESSAGE 'Q' #define SET_PHONE_NUMS 'R' #define SET_PARAMETERS 'S' #define SET_CARD_PARAMS 'T' #define UID_ADD 'U' #define UID_DEL 'u' #define TRANS_COMPLETE 'X' #define RESET 'Y' #define MALFUNCTION 'Z' // Define all system states - MUST BE IDENTICAL TO MAIN #define IDLE_STATE 0x01 #define PREPARE_SEND 0x02 #define WAIT_FOR_DIVERTERS 0x03 #define BEGIN_SEND 0x04 #define WAIT_FOR_MAIN_DEPART 0x05 #define WAIT_FOR_REM_ARRIVE 0x06 #define HOLD_TRANSACTION 0x07 #define WAIT_FOR_REM_DEPART 0x08 #define WAIT_FOR_MAIN_ARRIVE 0x09 #define WAIT_FOR_TURNAROUND 0x0A #define SHIFT_TURNAROUND 0x0B #define CANCEL_STATE 0x0C #define MALFUNCTION_STATE 0x0D #define FINAL_COMMAND 0x0E // Define transaction direction constants #define DIR_SEND 1 #define DIR_RETURN 2 /* Declare miscellaneous timeouts */ #define DIVERTER_TIMEOUT 30000 // How long to set diverter // May be longer than mainsta timeout /******************************************************************/ // Define various globals char mainStation; char arrival_from; // indicates if main is ready for receive or in arrival alert char transStation, diverterStation; char malfunctionActive; char carrier_attn, carrier_attn2; char system_state, transDirection; char doorWasOpen; #define FLAG_SECURE 0x20 char transFlags; char handleSecure; char gotCardRead; char gotPinRead; int securePIN; unsigned long cardID_hb, cardID_lb; int cardNumbits; void cardReaderInit(); //#define CARDHBOFFSET 119 //#define CARDLBOFFSET 3676144640 // offset to get printed card id number //#define CARDBASE 0xE8777C00 char purge_mode; // indicates if main is in purge mode (flash lights differently) //unsigned long secureCardID; //unsigned long secureCardTime; struct { //unsigned long id; char id[UIDLen]; // same as UIDLen unsigned long time; } secureCard, stdCard, unauthCard; unsigned long arrivalTime; static struct stats_type statistics; /* Array index values for remote data, returned by INPUTS_ARE command. */ #define REMOTE_CIC 0 #define REMOTE_DOOR 1 #define REMOTE_ARRIVE 2 #define REMOTE_RTS 3 #define REMOTE_RTS2 4 main() { int i; unsigned long timeout; unsigned long heartbeat_timer; unsigned long heartbeat_interval; struct iomessage message; struct UDPmessageType UDPmessage; char key, simonsays; auto rn_search newdev; int status; char UID[15]; char txt[6]; // unsigned long R[2]; // unsigned short fac, id; // int wr; /* Initialize i/o */ loadResetCounters(); // load counters for watchdog and powerlow resets // Initialize the controller brdInit(); // Initialize the controller rn_init(RN_PORTS, 1); // Initialize controller RN ports // Check if Rabbitnet boards are connected newdev.flags = RN_MATCH_PRDID; newdev.productid = RN1100; if ((DevRN1100 = rn_find(&newdev)) == -1) { printf("\n no RN1100 found\n"); } else status = rn_digOutConfig(DevRN1100, OUTCONFIG); //configure safe state // check if last reset was due to watchdog //if (wderror()) incrementWDCount(); // initialize display and show splash screen // back door way to toggle screen orientation if (di_requestToSend==1) param.orientLandscape = !param.orientLandscape; set_lcd_limits(); lcd_splashScreen(0); // allocate xmem for transaction log initTransLog(); loadTransactionCount(); // Read transaction counter from EEPROM hitwd(); init_io(); arrival_alert(aaRESET, 0); toggleLED(255); // initialize LED outputs readParameterSettings(); /* read board address and set configuration i/o mappings */ //THIS_DEVICE = (di_remoteAddress); THIS_DEVICE = param.stationNum; // get device/station from parameter instead of digital inputs if ((THIS_DEVICE < 1) || (THIS_DEVICE > 7)) THIS_DEVICE = 1; // default to 1 when out of range THIS_DEVICE_b = station2bit(THIS_DEVICE); lcd_DispText("Device/Station: ",0,0,MODE_NORMAL); sprintf(txt, "%d\n", THIS_DEVICE); lcd_DispText(txt,0,0,MODE_NORMAL); // flash the plc number //flasher(0); for (i=0; i<THIS_DEVICE; i++) { msDelay(200); ledOut(0,1); msDelay(150); ledOut(0,0); hitwd(); } // if (PRINT_ON) printf("\nWD and PL Reset Counters %d %d", watchdogCount(), powerlowCount()); // Set the diverter mapping based on the Remote ID# setDiverterMap(param.portMapping); // setup interrupt handler for arrival optics #if __SEPARATE_INST_DATA__ && FAST_INTERRUPT interrupt_vector ext1_intvec my_isr1; #else SetVectExtern3000(1, my_isr1); #endif arrivalEnable(FALSE); // Disable for now #ifdef USE_TCPIP // setup default static IP using THIS_DEVICE (myIPaddress = MY_BASE_IP + THIS_DEVICE) sprintf(myIPaddress, MY_BASE_IP, THIS_DEVICE); //printf("My IP address: %s\n", myIPaddress); lcd_DispText("IP address: ",0,0,MODE_NORMAL); lcd_DispText(myIPaddress,0,0,MODE_NORMAL); // configure the interface if(sock_init()) printf("IP sock_init() failed\n"); // Initialize UDP communications ifconfig(IF_ETH0, IFS_DHCP, 1, IFS_IPADDR,aton(myIPaddress), IFS_NETMASK,aton(MY_IP_NETMASK), IFS_DHCP_FALLBACK, 1, IFS_UP, IFS_END); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); //lcd_print(1, 0, "No IP Communications"); msDelay(1000); } #endif // flash output lamps exercise_io(); // Initialize serial port 1 enable_commands(); // Initialize card reader cardReaderInit(); // setup screen lcd_drawScreen(1, "TEST"); systemStateMsg=4; // INITIAL systemStateMsg PAUSED lcd_RefreshScreen(1); // force refresh of messages thistime=MS_TIMER; lost=0; heartbeat_interval=100; simonsays=TRUE; while(simonsays) { // loop forever maintenance(); // Hit WD, flash LEDs, write outputs, tcp tick lcd_RefreshScreen(0); lcd_ProcessButtons(); /* check for and process incoming commands */ if (get_command(&message)) process_command(message); if (getUDPcommand(&UDPmessage) > 0) processUDPcommand(UDPmessage); /* check for and process local inputs */ process_local_io(); arrival_alert(aaTEST, 0); if ((MS_TIMER - heartbeat_timer) > heartbeat_interval) { // Send a UDP heartbeat sendUDPHeartbeat(1); heartbeat_timer=MS_TIMER; } } /* end while */ } /********************************************************/ //unsigned long arrival_time; //char whichCA; unsigned long arrivalDuration; char arrivalISRstate; #define AISR_RISING 1 #define AISR_FALLING 2 nodebug root interrupt void my_isr1() { /* latchCarrierArrival=TRUE; //whichCA=di_carrierArrival; //carrierArrival(255); WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 */ // New concept ... // arrivalEnable sets up for falling edge interrupt // Detect that here and then reverse setup to detect rising edge // Once rising edge detected then validate duration // If duration is good (> x ms) then latch and disable interrupt // Otherwise reset interrupt for rising edge since it was previously active if (arrivalISRstate == AISR_FALLING) // Carrier has entered optic zone { // Setup to detect rising edge WrPortI(I1CR, &I1CRShadow, 0x0A); arrivalDuration = MS_TIMER; arrivalISRstate = AISR_RISING; } else if (arrivalISRstate == AISR_RISING) // Carrier has left optic zone { // WrPortI(I1CR, &I1CRShadow, 0x00); // disable interrupt arrivalDuration = MS_TIMER - arrivalDuration; arrivalISRstate = 0; // No more activity if (arrivalDuration > 10) latchCarrierArrival=TRUE; // Got a good arrival // note: 10 ms pulse for a 12 inch carrier is 100 FPS or 61.4 MPH else { WrPortI(I1CR, &I1CRShadow, 0x06); // Too short, reset for another try arrivalISRstate = AISR_FALLING; } } } void cardReaderInit() { // Initialize card reader // Input capture 0, zero bit on port F:3, one bit port F:5, 26 bits cardNumbits=param.cardFormat; if (wiegand_init(3, PFDR, 3, PFDR, 5, cardNumbits)) printf("Card reader init failed\n"); } void arrivalEnable(char how) { // should call this routine once to enable interrupt and once to disable #GLOBAL_INIT { latchCarrierArrival=FALSE; } latchCarrierArrival=FALSE; // clear existing latch if (how) { // enable INT1 WrPortI(I1CR, &I1CRShadow, 0x06); // enable external INT1 on PE1, falling edge, priority 2 arrivalISRstate = AISR_FALLING; } else { // disable INT1 WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 arrivalISRstate = 0; } } void setDiverterMap(char portMap) { // Sets up the diverter port mapping based on the supplied parameter // Also sets the parameter opMode to standard or head-diverter // Entry in diverter_map is the binary diverter port number (1,2,4,8) // At the moment, station number is tied to device number param.opMode = STD_REMOTE; MY_STATIONS = 1; //THIS_DEVICE; IO_SHIFT = 0; diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main initBlower(); // put this here to be similar to diverter software } void init_io() { char i; for (i=0; i<4; i++) // four or five output ports { outputvalue[i] = 0; remoteoutput[i] = 0; } #ifdef USE_BLOWER blower(blwrOFF); #endif alarm(OFF); do_doorUnLock(OFF); //secureCard.id=0; UID_Clear(secureCard.id); UID_Clear(stdCard.id); UID_Clear(unauthCard.id); secureCard.time=0; stdCard.time=0; unauthCard.time=0; handleSecure=FALSE; arrivalTime=0; purge_mode=0; } void exercise_io() { // if (!wderror()) // { alert(ON, MY_STATIONS); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); maintenance(); msDelay(1000); maintenance(); msDelay(1000); //inUse(ON, MY_STATIONS); maintenance(); msDelay(200); inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); msDelay(200); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); alert(ON, MY_STATIONS); maintenance(); msDelay(200); // } inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); hitwd(); // hit the watchdog } /********************************************************/ void process_local_io() { char rts_data, rts2_data, cic_data; /* bitwise station bytes */ char door_closed; char on_bits, flash_bits; /* which ones on and flash */ char on_bits2, flash_bits2; /* which ones on and flash for 2nd in-use light */ char s, sb; /* work vars for station & stationbit */ char i; //static unsigned long LA_Timer; // to latch the arrival signal #GLOBAL_INIT { rts_latch=0; rts2_latch=0; transStation=0; diverterStation=0; carrier_attn=0; carrier_attn2=0; //arrival_time=0; arrival_from=0; //LA_Timer=0; mainStation=0; param.subStaAddressing=FALSE; doorWasOpen=0; } /* Check for diverter and blower attention */ #ifdef USE_DIVERTER processDiverter(); #endif #ifdef USE_BLOWER processBlower(); #endif /* Use local buffers for some inputs */ if (param.opMode == STD_REMOTE) { // stuff for standard remote inputs rts_data=requestToSend(MY_STATIONS); // check for digital input send button //rts2_data=requestToSend2(MY_STATIONS); if (rts_data==0) rts_data=lcd_SendButton(); // if no digital button then try screen button rts2_data=0; //requestToSend2(MY_STATIONS); cic_data=carrierInChamber(MY_STATIONS); door_closed=doorClosed(MY_STATIONS); /* Latch request_to_send for new requests */ //rts_latch |= (rts_data & cic_data & door_closed) & ~carrier_attn & ~rts2_data; // de-latch when rts2 pressed //rts2_latch |= (rts2_data & cic_data & door_closed) & ~carrier_attn2 & ~rts_data; // de-latch when rts pressed // don't latch inputs if in purge mode if (purge_mode==0) { rts_latch |= (rts_data) & ~carrier_attn & ~rts2_data; // de-latch when rts2 pressed rts2_latch |= (rts2_data) & ~carrier_attn2 & ~rts_data; // de-latch when rts pressed } /* Clear latch requests from station in current transaction */ rts_latch &= (isMyStation(transStation) | isMyStation(diverterStation)) ? 0 : 1; rts2_latch &= (isMyStation(transStation) | isMyStation(diverterStation)) ? 0 : 1; /* Turn off those who have lost their carrier or opened door */ rts_latch &= cic_data; rts2_latch &= cic_data; rts_latch &= door_closed; rts2_latch &= door_closed; // Setup in-use lights for primary and optional secondary in-use lights on_bits = isMyStation(transStation) ? 1 : 0; flash_bits = rts_latch | rts_data; flash_bits |= ~door_closed; // flash open doors flash_bits |= carrier_attn; // flash stations needing attention (unremoved delivery) on_bits2 = isMyStation(transStation) ? 1 : 0; flash_bits2 = rts2_latch | rts2_data; flash_bits2 |= ~door_closed; // flash open doors flash_bits2 |= carrier_attn2; // flash stations needing attention (unremoved delivery) if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) flash_bits2 |= isMyStation(diverterStation) ? 1 : 0; else flash_bits |= isMyStation(diverterStation) ? 1 : 0; // if main arrival active, flash inuse at who sent to main if (arrival_from & THIS_DEVICE_b) { on_bits =0; //&= ~arrival_from; // Not on solid flash_bits =1; //|= arrival_from; // On flash instead } // Now ensure on bits overrides flash bits flash_bits &= ~on_bits; flash_bits2 &= ~on_bits2; // set the in use lights as necessary //inUse(OFF, ~on_bits & ~flash_bits & MY_STATIONS & ~station2bit(transStation)); //inUse(FLASH, flash_bits & ~station2bit(transStation)); inUse(OFF, ~on_bits & ~flash_bits); inUse(ON, on_bits); inUse(FLASH, flash_bits); //inUse2(OFF, ~on_bits2 & ~flash_bits2 & MY_STATIONS & ~station2bit(transStation)); //inUse2(FLASH, flash_bits2 & ~station2bit(transStation)); inUse2(OFF, ~on_bits2 & ~flash_bits2); inUse2(ON, on_bits2); inUse2(FLASH, flash_bits2); // latch the arrival signal //// if (carrierArrival(MY_STATIONS)) latchCarrierArrival=TRUE; // latch this value // locally handle the alert for door open during transaction if (door_closed) doorAlert(OFF); else { if (isMyStation(transStation)) { doorAlert(ON); doorWasOpen=TRUE; } } // Check for and process door unlock processCardReads(); } else { // stuff for head diverter //i = di_HDArrival; // && (system_state==WAIT_FOR_TURNAROUND) if (di_HDArrival && (system_state==WAIT_FOR_TURNAROUND)) latchCarrierArrival=TRUE; // latch this value rts_data=0; // No push to send buttons cic_data=0; // No carrier in chamber optics door_closed=0; // No door switches } } void processCardReads(void) { // check for card or pin read and latch in gotCardRead or gotPinRead unsigned long R[2]; int wr, PIN; unsigned long test; unsigned long test2; char Buf[14]; static char Uid[5]; // check for card read wr = wiegand_result(3, NULL, R); if (wr == WIEGAND_OK) { // got a card read if (cardNumbits == 40) { cardID_lb = R[0] | (R[1] << 19); // first 32 bits cardID_hb = R[1] >> 13; } else if (cardNumbits == 26) { cardID_lb = (R[0] | (R[1] << 12)) & 0xFFFFFF; // card number (16 bits) w/ site code cardID_hb = 0;//(R[1] >> 4); // site code (8 bits) } else // unknown format { cardID_lb = 0; cardID_hb = 0; } // stuff lb,hb into Uid Uid[0] = (char)cardID_hb; Uid[1] = (char)((cardID_lb >> 24) & 0xFF); Uid[2] = (char)((cardID_lb >> 16) & 0xFF); Uid[3] = (char)((cardID_lb >> 8) & 0xFF); Uid[4] = (char)((cardID_lb) & 0xFF); UID_Decode(Uid, Buf); printf(" Got Card %lX %lX -> %s\n", cardID_hb, cardID_lb, Buf); // check against card block 1 or 2 /// if ( (((cardID_hb+CARDHBOFFSET) == param.cardL3Digits) /// && ((cardID_lb-CARDLBOFFSET) >= param.cardR9Min) /// && ((cardID_lb-CARDLBOFFSET) <= param.cardR9Max)) /// || (((cardID_hb+CARDHBOFFSET) == param.card2L3Digits) /// && ((cardID_lb) >= param.card2R9Min) /// && ((cardID_lb) <= param.card2R9Max)) ) ///if ((param.cardCheckEnabled == FALSE) || (UID_Search(Uid) >= 0)) ///{ printf(" Card is valid\n"); /// gotCardRead = TRUE; ///} gotCardRead = TRUE; // Always accept a card read regardless of param and search } //else if (gotCardRead==FALSE) secureCardID = 0; // only clear if not pending xmit // check for PIN read if in a secure transaction if (handleSecure) { do_secureTransLight(ON); wr = wiegand_PIN_result(&PIN); if (wr == WIEGAND_OK) { if (PIN == securePIN) //{ if (PIN == 2321) { // PIN matches securePIN printf(" Got PIN %d\n", PIN); gotPinRead = TRUE; } } } else do_secureTransLight(OFF); // what to do if (gotCardRead) { if (isMyStation(transStation)) { // we're busy so ignore card read gotCardRead=FALSE; // if there is a returning transaction from me // then may be due to an auto or manual return // therefore clear the handling of secure transactions if (transDirection == DIR_RETURN) handleSecure=FALSE; } else { // no active transaction, so what next // 3 choices // Card check not enabled // Card check enabled and card found // Card check enabled and card not found // Choice 1 & 2 if ((param.cardCheckEnabled == FALSE) || (UID_Search(Uid) >= 0)) { // Either card check not enabled or is enabled and card found if (handleSecure) { // we need to deal with secure, did we get a pin also if (gotPinRead) { // Got a valid PIN number on a secure transaction unlockDoor(); // Unlatch door // Return card number to host (in return inputs x2) // Reset operations handleSecure=FALSE; gotPinRead=FALSE; gotCardRead=FALSE; //secureCard.id = cardID_lb; memcpy(secureCard.id, Uid, sizeof(Uid)); secureCard.time = SEC_TIMER - arrivalTime; } } else { // not doing anything else so just open door unlockDoor(); gotCardRead=FALSE; // need to send non-secure card reads as well memcpy(stdCard.id, Uid, sizeof(Uid)); stdCard.time = SEC_TIMER; } } else { // Choice 3 card check enabled and card not found // don't unlock door, but do send card data to host gotCardRead=FALSE; memcpy(unauthCard.id, Uid, sizeof(Uid)); unauthCard.time = SEC_TIMER; } } } } /********************************************************/ void process_command(struct iomessage message) { // from RS485 bus char wcmd, wdata; char ok; char i; char *sid; char scanType; //static char system_state, new_state; static char new_state; struct iomessage response; static unsigned long lastSecureRemoveMsg; char UID[15]; char bUID[7]; #GLOBAL_INIT { system_state=IDLE_STATE; new_state=system_state; lastSecureRemoveMsg=0; } response.command=0; response.station=message.station; // set initial default /* determine what type of command */ switch(message.command) { case UID_ADD: case UID_DEL: // works for both for (i=0; i<UIDLen; i++) bUID[i] = message.data[i]; UID_Decode(bUID, UID); if (message.command == UID_ADD) UID_Add(UID); else if (bUID[0]=='d') UID_Del("ALL"); // clear whole list else UID_Del(UID); // delete just this one UID[14]=0; // null term for printf printf("%s UID %s\n", (message.command == UID_ADD) ? "ADD" : "DEL", UID); break; case ARE_YOU_READY: // debug to see what may be causing loss of communication //lastcommand=message.command; // enable arrival interrupt / latch if (param.opMode == STD_REMOTE) arrivalEnable(TRUE); // don't enable interrupt for head diverter response.command=ARE_YOU_READY; // assume ready for now //#warnt "NEED TO FIX LOGIC OF HANDLING DEVICE > 7" response.data[0]=THIS_DEVICE_b; // CONSIDER TO SEND DECIMAL NUMBER AND LET HOST ASSEMBLE THE COLLECTIVE RESPONSE transStation=message.station; transDirection=message.data[0]; mainStation=message.data[1]; // get the main station to be used //transFlags=message.data[3]; // transaction flags such as STAT & Secure // Negate assumption if not ready if (isMyStation(message.station) && (param.opMode == STD_REMOTE)) { // stuff for standard remote rts_latch &= ~station2bit(message.station); // clear latch rts2_latch &= ~station2bit(message.station); // clear latch /* only if door closed, and (CIC or send-to-here) */ if ( doorClosed(station2bit(message.station)) && ( carrierInChamber(station2bit(message.station)) || message.data[0]==DIR_SEND) ) { // ready if (param.subStaAddressing && mainStation==SLAVE) { inUse2(ON, station2bit(message.station)); }else { inUse(ON, station2bit(message.station)); } } else { response.data[0]=0; // not ready if (param.subStaAddressing && mainStation==SLAVE) inUse2(OFF, station2bit(message.station)); else inUse(OFF, station2bit(message.station)); alert(ON, station2bit(message.station)); } } break; case SET_DIVERTER: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote if (param.subStaAddressing && message.data[1]==SLAVE) inUse2(FLASH, station2bit(message.station)); else inUse(FLASH, station2bit(message.station)); #ifdef USE_DIVERTER setDiverter(message.station); #endif } else { // stuff for head diverter #ifdef USE_DIVERTER setDiverter(message.data[0]); // head diverter comes in different byte #endif } mainStation=message.data[1]; // get the main station to be used param.subStaAddressing=message.data[2]; param.blowerType = message.data[3]; transFlags = message.data[4]; // transaction flags such as STAT & Secure if (transFlags & FLAG_SECURE) handleSecure = TRUE; break; case DIVERTER_STATUS: // return logic of correct position // debug to see what may be causing loss of communication //lastcommand=message.command; // capture the securePIN if (isMyStation(message.station)) securePIN = (message.data[2]<<8) + message.data[3]; // return response response.command=DIVERTER_STATUS; // which port dependent on opMode if (param.opMode == STD_REMOTE) i = message.station; else i = message.data[0]; // is that port aligned? or not used? response.data[0]=THIS_DEVICE_b; // DIVERTER_READY; /* if ( (di_diverterPos == diverter_map[i]) || (diverter_map[i] == 0) ) { response.data[0]=1<<(THIS_DEVICE-1); // DIVERTER_READY; } else { response.data[0]=0; // DIVERTER_NOT_READY; } */ break; case RETURN_INPUTS: /* return general status */ // debug to see what may be causing loss of communication //lastcommand=message.command; // main includes some status info here ... pull it out arrival_from=message.data[0]; new_state=message.data[1]; // NOT USING IT: system_direction=message.data[2]; // tell main how I am doing response.command=INPUTS_ARE; response.station=MY_STATIONS; // return this to enlighten main // fill in the rest of the response based on who I am if (param.opMode == STD_REMOTE) { // stuff for standard remote // is there a Secure Card or Std Card ID to pass along? // determine if there is a secure or standard card swipe sid = secureCard.id; // maybe nothing maybe something if (UID_Not_Zero(secureCard.id)) { //sid = secureCard.id; already set scanType = 1; // secure ID } else if (UID_Not_Zero(stdCard.id)) { sid = stdCard.id; scanType = 2; // standard ID } else if (UID_Not_Zero(unauthCard.id)) { sid = unauthCard.id; scanType = 3; // unauthorized ID } if (UID_Not_Zero(sid) && ((MS_TIMER - lastSecureRemoveMsg)>500)) { // instead of INPUTS_ARE need to send SECURE_REMOVAL lastSecureRemoveMsg = MS_TIMER; response.command=SECURE_REMOVAL; response.data[0] = *sid++; // secureCardID byte 3 response.data[1] = *sid++; // secureCardID byte 2 response.data[2] = *sid++; // secureCardID byte 1 response.data[3] = *sid++; // secureCardID byte 0 //response.data[4] = (char) (secureCard.time/6); // 6 second resolution response.data[4] = *sid++; // 5 bytes and time is calculated response.data[5] = scanType; // scan type Secure or Std } else { // Return latched carrier arrival if state is wait_for_remote_arrival if (latchCarrierArrival && system_state==WAIT_FOR_REM_ARRIVE) { ok=TRUE; gotPinRead=FALSE; // Reset any PIN and card reads gotCardRead=FALSE; } else ok=FALSE; // Return the arrival signal response.data[REMOTE_ARRIVE]=carrierArrival(MY_STATIONS); // but if it is none then send latched arrival under some conditions if ((response.data[REMOTE_ARRIVE]==0) && (latchCarrierArrival) && (system_state==WAIT_FOR_REM_ARRIVE)) response.data[REMOTE_ARRIVE]=latchCarrierArrival; response.data[REMOTE_CIC]=carrierInChamber(MY_STATIONS); response.data[REMOTE_DOOR]=doorClosed(MY_STATIONS); response.data[REMOTE_RTS]=rts_latch; response.data[REMOTE_RTS2]=rts2_latch; } } else { // stuff for head diverter // Return latched carrier arrival if state is wait_for_turnaround if ((latchCarrierArrival || di_HDArrival) && (system_state==WAIT_FOR_TURNAROUND)) ok=TRUE; else ok=FALSE; // Return the arrival signal if (ok) response.data[REMOTE_ARRIVE]=MY_STATIONS; else response.data[REMOTE_ARRIVE]=0; response.data[REMOTE_CIC]=0; response.data[REMOTE_DOOR]=0; // HD has no stations MY_STATIONS; response.data[REMOTE_RTS]=0; #ifdef USE_BLOWER if (blwrError==FALSE) response.data[REMOTE_RTS2]=blowerPosition(); else response.data[REMOTE_RTS2]=0xFF; // Blower has an error #else response.data[REMOTE_RTS2]=0; // No blower here #endif } break; case ACK_SECURE_REMOVAL: // Acknowledge of secure card id from station n //if (isMyStation(message.station)) // message.data[0] contains bit-wise stations to acknowledge if (message.data[0] & THIS_DEVICE_b) { UID_Clear(secureCard.id); UID_Clear(stdCard.id); UID_Clear(unauthCard.id); } break; case RETURN_EXTENDED: /* return extended data */ // debug to see what may be causing loss of communication //lastcommand=message.command; // return watchdog and powerlow counters response.command=RETURN_EXTENDED; response.data[0]=0;//watchdogCount(); response.data[1]=0;//powerlowCount(); response.data[2]=SUBVERSION; break; case SET_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote /* set outputs from mainsta */ set_remote_io(&message.data[0]); } break; case CLEAR_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_OPMODE: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_PARAMETERS: // get the blower type and other parameters // debug to see what may be causing loss of communication //lastcommand=message.command; param.portMapping = message.data[0]; param.blowerType = message.data[1]; writeParameterSettings(); setDiverterMap(param.portMapping); break; case SET_CARD_PARAMS: // Setup the secure card parameters switch (message.data[0]) { case 0: param.cardFormat = message.data[1]; cardReaderInit(); break; case 1: /// param.cardR9Min = *(unsigned long *)&message.data[1]; break; case 2: /// param.cardR9Max = *(unsigned long *)&message.data[1]; break; case 3: /// param.card2L3Digits = message.data[1]; break; case 4: /// param.card2R9Min = *(unsigned long *)&message.data[1]; break; case 5: /// param.card2R9Max = *(unsigned long *)&message.data[1]; break; // last one so save and send the data to remotes // writeParameterSettings(); SAVE WILL FOLLOW IMMEDIATELY FROM SET_PARAMETERS case 6: // others above probably not used except 0 param.cardCheckEnabled = message.data[1]; break; } break; case TRANS_COMPLETE: // debug to see what may be causing loss of communication //lastcommand=message.command; arrivalEnable(FALSE); // Disable arrival interrupt transStation=0; if (param.opMode == STD_REMOTE) { // stuff for standard remote alert(OFF, station2bit(message.station)); // set arrival alert if the transaction is to here if (message.data[0] == DIR_SEND && isMyStation(message.station)) { if (message.data[1]==1) // and Main says to set arrival alert { // OK to set alert // REDUNDANT inUse(FLASH, station2bit(message.station)); // until no cic if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) carrier_attn2 |= station2bit(message.station); // to flash inuse else carrier_attn |= station2bit(message.station); // to flash inuse arrival_alert(aaSET, message.station); } arrivalTime=SEC_TIMER; // used with secureRemovalTime } else if (message.data[0] == DIR_RETURN && isMyStation(message.station)) { // capture the main arrival flag } } // nothing else for head diverter break; case MALFUNCTION: // may be contributing to funky flashing // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // turn on alarm output only inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(ON); arrival_alert(aaRESET, 0); } arrivalEnable(FALSE); // Disable arrival interrupt rts_latch=0; rts2_latch=0; transStation=0; diverterStation=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; case RESET: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // Turn off all outputs inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(OFF); arrival_alert(aaRESET, 0); } #ifdef USE_BLOWER blwrError=FALSE; // reset blower error #endif arrivalEnable(FALSE); // Disable arrival interrupt /// rts_latch=0; Try to not clear latch on reset transStation=0; diverterStation=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; } /* send the response message if any AND the query was only to me */ if (response.command && (message.device==THIS_DEVICE)) { msDelay(2); // hold off response just a bit //response.device=THIS_DEVICE; send_response(response); } // process state change if (new_state != system_state) { // set blower for new state system_state=new_state; #ifdef USE_BLOWER blower(blowerStateTable[system_state][0]); // remote always uses blwrconfig 0 #endif } // state change to/from malfunction state malfunctionActive = (system_state == MALFUNCTION_STATE); // handle state change of malfunction checkMalfunction(); return; } void checkMalfunction() { // take care of business when malfunction changes state // uses malfunctionActive static char lastMalfunction; // to keep track of when malfunctionActive changes if (lastMalfunction != malfunctionActive) { // malf activated or reset? if (malfunctionActive) { // malfunction alarm(ON); arrival_alert(aaRESET, 0); } else { // reset alarm(OFF); #ifdef USE_BLOWER blwrError=FALSE; // reset blower error #endif arrivalEnable(FALSE); // Disable arrival interrupt // Resetting of handleSecure may be a problem because it could lead to // the ability to remove a secure substance when the main station resets // handleSecure = FALSE; } lastMalfunction = malfunctionActive; } } void processUDPcommand(struct UDPmessageType UDPmessage) { // Handles incoming requests from the diverter controller static char lastTransStation; // to keep track of when transStation changes char UID[15]; char bUID[7]; int i, j; struct tm time; static char new_state; #GLOBAL_INIT { new_state=0; } //printf("\n Got UDP message %c at %ld, %d, %d, %ld", UDPmessage.command, UDPmessage.timestamp, latchCarrierArrival, arrivalISRstate, arrivalDuration); /* determine what type of command */ switch(UDPmessage.command) { case UID_ADD: case UID_DEL: for (i=0; i<UIDLen; i++) bUID[i] = UDPmessage.data[i]; UID_Decode(bUID, UID); if (UDPmessage.command == UID_ADD) UID_Add(UID); else if (bUID[0]=='d') UID_Del("ALL"); // clear whole list else UID_Del(UID); // delete just this one UID[14]=0; // null term for printf printf("%s UID %s\n", (UDPmessage.command == UID_ADD) ? "ADD" : "DEL", UID); break; case TRANS_COMPLETE: // handle completed transaction arrivalEnable(FALSE); // Disable arrival interrupt - probably redundant transStation=0; alert(OFF, MY_STATIONS); // in case it was on?? doorAlert(OFF); // ditto // set arrival alert if the transaction is to here if (isMyStation(UDPmessage.station)) { if (UDPmessage.data[0] == DIR_SEND) { //if (UDPmessage.data[1]==1) // and Main says to set arrival alert if (param.remoteAudibleAlert) // and WE say to set arrival alert { // OK to set alert if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) carrier_attn2 = 1; //|= station2bit(UDPmessage.station); // to flash inuse else carrier_attn = 1; //|= station2bit(UDPmessage.station); // to flash inuse arrival_alert(aaSET, 1); //UDPmessage.station); } gotPinRead=FALSE; // Reset any PIN and card reads gotCardRead=FALSE; arrivalTime=SEC_TIMER; // used with secureRemovalTime statistics.trans_in++; } else { statistics.trans_out++; } // record in the log translog.source_sta=UDPmessage.station; translog.status |= UDPmessage.data[3]; // local or global status translog.flags = UDPmessage.data[4]; // local or global flags translog.duration=(int)(SEC_TIMER-translog.start_tm); addTransaction( translog, 0 ); // update alarm statistics if (translog.status==3) statistics.deliv_alarm++; // incomplete delivery timeout alarm else if (translog.status==2) statistics.cic_lift_alarm++; if (doorWasOpen) { statistics.door_alarm++; doorWasOpen=0; } } // refresh screen on trans complete lcd_RefreshScreen(1); // force refresh of messages break; case SET_DIVERTER: // debug to see what may be causing loss of communication //lastcommand=message.command; if (isMyStation(UDPmessage.station)) { if (param.opMode == STD_REMOTE) { // stuff for standard remote if (param.subStaAddressing && UDPmessage.data[1]==SLAVE) inUse2(FLASH, station2bit(UDPmessage.station)); else inUse(FLASH, station2bit(UDPmessage.station)); #ifdef USE_DIVERTER setDiverter(UDPmessage.station); #endif } else { // stuff for head diverter #ifdef USE_DIVERTER setDiverter(UDPmessage.data[0]); // head diverter comes in different byte #endif } mainStation=UDPmessage.data[1]; // get the main station to be used param.subStaAddressing=UDPmessage.data[2]; param.blowerType = UDPmessage.data[3]; transFlags = UDPmessage.data[4]; // transaction flags such as STAT & Secure if (transFlags & FLAG_SECURE) handleSecure = TRUE; // starting a transaction? let's assume translog.trans_num = transactionCount()+1; //eventlog.trans_num = translog.trans_num; translog.start_tm = SEC_TIMER; translog.duration = 0; translog.source_sta = 0; translog.dest_sta = 0; translog.status = 0; translog.flags=transFlags; } break; case REMOTE_PAYLOAD: // standard data distribution message arrival_from = UDPmessage.data[0]; new_state = UDPmessage.data[1]; transStation = UDPmessage.data[3]; mainStation = UDPmessage.data[4]; diverterStation = UDPmessage.data[5]; param.subStaAddressing = UDPmessage.data[6]; transFlags = UDPmessage.data[7]; // do we have a secure ack? if (isMyStation(UDPmessage.data[8])) { UID_Clear(secureCard.id); // clear secureCardID UID_Clear(stdCard.id); // and standard card UID_Clear(unauthCard.id); } malfunctionActive = (new_state == MALFUNCTION_STATE); transDirection = UDPmessage.data[11]; purge_mode = UDPmessage.data[12]; // handle capture of secure transaction if ((transFlags & FLAG_SECURE) && isMyStation(transStation)) { handleSecure = TRUE; securePIN = (UDPmessage.data[9]<<8) + UDPmessage.data[10]; UID_Clear(secureCard.id); } // handle reset of secure transaction if ((new_state == CANCEL_STATE) && isMyStation(transStation)) { handleSecure = FALSE; UID_Clear(secureCard.id); UID_Clear(stdCard.id); UID_Clear(unauthCard.id); } // handle some state changes if (transStation != lastTransStation) { // is transaction starting or stopping? if (isMyStation(transStation)) { arrivalEnable(TRUE); // ready latch } else arrivalEnable(FALSE); // clear the latched arrival // reset state change lastTransStation = transStation; } // handle state change of malfunction checkMalfunction(); break; case SET_STATION_NAME: if (UDPmessage.station==69) { // construct messages and save parameters to flash //buildStationNames(); writeParameterSettings(); printf("Set station name %s\n", param.stationName); printf("Set main name %s\n", param.mainName); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen lcd_RefreshScreen(1); } else { if (UDPmessage.station == param.stationNum) { // is my station // save chunk of name i=UDPmessage.data[0]; for (j=0; j<4; j++) param.stationName[i+j] = UDPmessage.data[j+1]; } else if (UDPmessage.station == 0) // 0 is main; 9 is system { // main station name // save chunk of name i=UDPmessage.data[0]; for (j=0; j<4; j++) param.mainName[i+j] = UDPmessage.data[j+1]; } // else not my station } break; case SET_DATE_TIME: tm_rd(&time); // read all time data time.tm_year=UDPmessage.data[0]; time.tm_mon=UDPmessage.data[1]; time.tm_mday=UDPmessage.data[2]; time.tm_hour=UDPmessage.data[3]; time.tm_min=UDPmessage.data[4]; time.tm_sec=UDPmessage.station; tm_wr(&time); // write new time data SEC_TIMER = mktime(&time); // resync SEC_TIMER break; case SET_CARD_PARAMS: /// param.cardL3Digits = UDPmessage.data[0]; /// param.cardR9Min = *(unsigned long *)&UDPmessage.data[1]; /// param.cardR9Max = *(unsigned long *)&UDPmessage.data[5]; /// param.card2L3Digits = UDPmessage.data[9]; /// param.card2R9Min = *(unsigned long *)&UDPmessage.data[10]; /// param.card2R9Max = *(unsigned long *)&UDPmessage.data[14]; param.cardCheckEnabled = UDPmessage.data[0]; param.cardFormat = UDPmessage.data[1]; writeParameterSettings(); cardReaderInit(); break; } // process state change if (new_state != system_state) { // set blower for new state system_state=new_state; #ifdef USE_BLOWER blower(blowerStateTable[system_state][0]); // always config 0 (standard blower) #endif } // update system state message EVERY TIME if (system_state==IDLE_STATE) systemStateMsg = 1; // READY else if (system_state==HOLD_TRANSACTION) systemStateMsg = 4; // PAUSED else if (system_state==MALFUNCTION_STATE) systemStateMsg = 6; // ALARM else if (transStation!=THIS_DEVICE) systemStateMsg = 5; // BUSY else if (transDirection==DIR_RETURN) systemStateMsg = 3; // SENDING else systemStateMsg = 2; // RECEIVING if (isMyStation(bit2station(arrival_from))) systemStateMsg = 8; // waiting for removal at main } unsigned long alert_timer[8]; // for stations 1..7 ... [0] is not used. void arrival_alert(char func, char station) { int i; switch (func) { case aaRESET: for (i=1; i<=7; i++) { alert_timer[i]=0; alert(OFF, station2bit(i)); } break; case aaSET: if (station>=1 && station<=7) // make sure s# is correct { alert_timer[ station ] = SEC_TIMER; } break; case aaTEST: for (i=1; i<=7; i++) // Check each station { if (alert_timer[i]) { if ( carrierInChamber( station2bit(i) )) // || (remote_stat_alert==i) ) { // Flash as necessary if ( (SEC_TIMER - alert_timer[i]) %20 >= 10 ) alert(ON, station2bit(i)); else alert(OFF, station2bit(i)); } //else if (clock() = alert_timer[i] > 1) //else if (!doorClosed( station2bit(i) ) || i==transStation) // will only use station 1 in the alert array but transStation is the real station number else if (!doorClosed( station2bit(i) ) || isMyStation(transStation)) { // no carrier, door open // or no carrier, in transit --> reset alert_timer[i]=0; alert(OFF, station2bit(i)); carrier_attn &= ~station2bit(i); // clear attn flag carrier_attn2 &= ~station2bit(i); // clear attn flag // This should only happen with this_station handleSecure = FALSE; } } else { carrier_attn &= ~station2bit(i); // no timer, so no flag carrier_attn2 &= ~station2bit(i); // no timer, so no flag } } break; } } /************************************************************/ /************** DIGITAL I/O *************************/ /************************************************************/ #define devIUS 0 #define devIUF 1 #define devAlert 2 #define devAlarm 3 #define dev2IUS 4 #define dev2IUF 5 // #define devDoorAlert 4 int readDigInput(char channel) { // returns the state of digital input 0-39 // function supports inverted logic by assigning dio_ON and dio_OFF char rtnval; if (channel < 16) { // on-board inputs rtnval = digIn(channel); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digIn(DevRN1100, channel-16, &rtnval, 0) == -1) rtnval=1; } // 1 is off else rtnval = 0; } // deal with logic inversion if (rtnval) rtnval = dio_ON; else rtnval = dio_OFF; return rtnval; } int readDigBank(char bank) { // returns the state of digital input banks 0-3 // banks 0-1 on Coyote; banks 2-3 on RN1100 // function supports inverted logic by assigning dio_ON and dio_OFF static char rtnval[4]; // to cache previous inputs char returnVal; char temp; #GLOBAL_INIT { rtnval[0]=0; rtnval[1]=0; rtnval[2]=0; rtnval[3]=0; } if (bank < 2) { // on-board inputs rtnval[bank] = digBankIn(bank); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digBankIn(DevRN1100, bank-1, &temp, 0) == -1) rtnval[bank]=0xFF; // 1 is off else rtnval[bank]=temp; } } returnVal = rtnval[bank]; // deal with logic inversion if (dio_OFF) returnVal ^= 0xFF; return returnVal; } void setDigOutput(int channel, int value) { // sets the state of digital output 0-23 // call with logic value (0=OFF, 1=ON) // function is adapted to support inverted logic by assigning dio_ON and dio_OFF int outval; // check for logic inversion if (value) outval = dio_ON; else outval = dio_OFF; if (channel < 8) { // on-board outputs digOut(channel, outval); } else { // rn1100 outputs if (DevRN1100 != -1) rn_digOut(DevRN1100, channel-8, outval, 0); } } /*************************************************************/ void set_remote_io(char *remotedata) { /* save state of remote output request */ remoteoutput[0]=remotedata[0]; remoteoutput[1]=remotedata[1]; // remoteoutput[2]=remotedata[2]; // THIS IS devAlert - DON'T TAKE FROM MAIN remoteoutput[2]=remotedata[2]; // Instead use remotedata[2] to drive the door alert remoteoutput[3]=remotedata[3]; /* write out all outputs .. some may need to be shifted */ // write4data(addrIUS, outputvalue[devIUS] | remoteoutput[devIUS]); // write4data(addrIUF, outputvalue[devIUF] | remoteoutput[devIUF]); // outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); // write4data(addrALT, outval); // write4data(addrALM, outputvalue[devAlarm] | remoteoutput[devAlarm]); // Write remotedata[devAlert] to output ports O5-O8 // hv_outval &= ~DOOR_ALERT_MASK; // turn off door alert bits // hv_outval = (remotedata[devAlert] & MY_STATIONS) >> IO_SHIFT; // hv_wr(hv_outval); } /******************************************************************/ char carrierInChamber(char stamask) { return (di_carrierInChamber << IO_SHIFT) & stamask; } /******************************************************************/ char doorClosed(char stamask) { // Note: input is normally high on closed. char indata; indata = di_doorClosed; return ((indata << IO_SHIFT) & stamask); } /******************************************************************/ char carrierArrival(char stamask) { return (di_carrierArrival << IO_SHIFT) & stamask; } /******************************************************************/ char requestToSend(char stamask) { char indata; indata = di_requestToSend; return ((indata << IO_SHIFT) & stamask); } char requestToSend2(char stamask) { char indata; indata = di_requestToSend2; return ((indata << IO_SHIFT) & stamask); } /******************************************************************/ void inUse(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[devIUS] |= station_b; outputvalue[devIUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] |= station_b; } return; } void inUse2(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[dev2IUS] |= station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] |= station_b; } return; } void doorAlert(char how) { // still using remoteoutput[devAlert] because thats how it was handled before remoteoutput[devAlert] = how; return; } unsigned long doorUnLockTimer; void unlockDoor(void) { // trigger door output timer #GLOBAL_INIT {doorUnLockTimer=0;} doorUnLockTimer = MS_TIMER; do_doorUnLock(ON); } /******************************************************************/ void alert(char how, char station_b) { if (how == ON) outputvalue[devAlert] |= station_b; if (how == OFF) outputvalue[devAlert] &= ~station_b; //outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); //write4data(addrALT, outval); //do_alert(outval, how); // OUTPUTS WRITTEN IN SYSTEM LOOP CALL TO updateOutputs(); return; } /******************************************************************/ void alarm(char how) { // outputvalue is checked in the maintenance function to turn alarm on/off outputvalue[devAlarm] = how; return; } /******************************************************************/ #ifdef USE_DIVERTER unsigned long diverter_start_time; // these used primarily by diverter functions char diverter_setting; char diverter_attention; void setDiverter(char station) { /* Controls the setting of diverter positions Return from this routine is immediate. If diverter is not in position, it is turned on and a timer started. You MUST repeatedly call processDiverter() to complete processing of the diverter control position */ /* use mapping from station to diverter position */ if ((station>0) && (station<9)) // Valid station # { diverter_setting = diverter_map[station]; // mapped setting // if position<>ANY (any=0) and not in position if ((diverter_setting>0) && (diverter_setting!=di_diverterPos)) { /* turn on diverter and start timer */ do_diverter(ON); diverter_start_time = MS_TIMER; diverter_attention = TRUE; diverterStation=station; } } return; } /******************************************************************/ void processDiverter() { /* Poll type processing of diverter control system */ /* Allows other processes to be acknowleged when setting diverter */ if (diverter_attention) { if ((diverter_setting == di_diverterPos) || Timeout(diverter_start_time, DIVERTER_TIMEOUT)) { // turn off diverter and clear status do_diverter(OFF); diverter_attention = FALSE; diverterStation=0; } } } #endif void showactivity() { // update active processor signal ledOut(0, (MS_TIMER %250) < 125); // on fixed frequency //ledOut(1, (MS_TIMER %500) > 250); // off fixed frequency toggleLED(2); // toggle each call } void toggleLED(char LEDDev) { static char LEDState[4]; // if LEDDev not 0..3 then initialize LED states off if (LEDDev > 3) { LEDState[0]=0; LEDState[1]=0; LEDState[2]=0; LEDState[3]=0; } else { LEDState[LEDDev] ^= 1; // toggle LED state on/off ledOut(LEDDev, LEDState[LEDDev]); // send LED state } } #ifdef USE_TCPIP int getUDPcommand(struct UDPmessageType *UDPmessage) { // be sure to allocate enough space in buffer to handle possible incoming messages (up to 128 bytes for now) auto char buf[128]; auto int length, retval; int idx; char * UDPbuffer; // to index into UDPmessage byte by byte length = sizeof(buf); retval = udp_recv(&sock, buf, length); if (retval < -1) { printf("Error %d receiving datagram! Closing and reopening socket...\n", retval); sock_close(&sock); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); } } else { // Is there any message if (retval >1) { // is the command for me? // map it into the UDPmessage structure UDPbuffer = (char *) UDPmessage; for (idx = 0; idx < sizeof(*UDPmessage); idx++) UDPbuffer[idx] = buf[idx]; // Return it } } return retval; } int sendUDPcommand(struct UDPmessageType UDPmessage) { // Send the supplied command over UDP // Appends some info to the standard message // .device // .timestamp auto int length, retval; char * UDPbuffer; // to index into UDPmessage byte by byte // fill the packet with additional data UDPmessage.device = THIS_DEVICE; // system id UDPmessage.devType = 3; // remote UDPmessage.timestamp = MS_TIMER; length = sizeof(UDPmessage); // how many bytes to send UDPbuffer = (char *) &UDPmessage; /* send the packet */ retval = udp_send(&sock, UDPbuffer, length); if (retval < 0) { printf("Error sending datagram! Closing and reopening socket...\n"); sock_close(&sock); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); } } } int sendUDPHeartbeat(char sample) { // Sends an INPUTS_ARE message to the host struct UDPmessageType HBmessage; char * sid; HBmessage.command = INPUTS_ARE; HBmessage.station = THIS_DEVICE; // provide the real station number HBmessage.data[0] = carrierInChamber(MY_STATIONS); // CIC HBmessage.data[1] = doorClosed(MY_STATIONS); // Door closed HBmessage.data[2] = carrierArrival(MY_STATIONS); // Arrival // but if Arrival is none then send latched arrival under some conditions if ((HBmessage.data[2]==0) && (latchCarrierArrival) && (system_state==WAIT_FOR_REM_ARRIVE)) HBmessage.data[2] = latchCarrierArrival; // Arrival HBmessage.data[3] = rts_latch; // RTS latch HBmessage.data[4] = rts2_latch; // RTS latch - 2nd destination HBmessage.data[5] = VERSION; // Version HBmessage.data[6] = SUBVERSION; // Sub-version HBmessage.data[7] = 0; // nothing HBmessage.data[8] = 0; // nothing initialize sid = secureCard.id; // maybe nothing maybe something if (UID_Not_Zero(secureCard.id)) { //sid = secureCard.id; already set HBmessage.data[8] = 1; // secure ID HBmessage.data[14] = (char) (secureCard.time/6); } else if (UID_Not_Zero(stdCard.id)) { sid = stdCard.id; HBmessage.data[8] = 2; // standard ID HBmessage.data[14] = 0; // no timing } else if (UID_Not_Zero(unauthCard.id)) { sid = unauthCard.id; HBmessage.data[8] = 3; // unauthorized ID HBmessage.data[14] = 0; // no timing } HBmessage.data[9] = *sid++; // secureCardID[0] HBmessage.data[10] = *sid++; // secureCardID[1] HBmessage.data[11] = *sid++; // secureCardID[2] HBmessage.data[12] = *sid++; // secureCardID[3] HBmessage.data[13] = *sid++; // secureCardID[4] sendUDPcommand(HBmessage); // ignore return value, will send again periodically } #endif void maintenance(void) { // handle all regularly scheduled calls // use of static CHAR was causing PA4 RS485 transmitter to enable without reason ... static INT works ok. static int out_alert, out_inuse, out_inuse2, out_doorAlert, out_cic; char i; hitwd(); // hit the watchdog timer showactivity(); //rn_keyProcess(DevRN1600, 0); // process keypad device // process command communications #ifdef USE_TCPIP tcp_tick(NULL); #endif //receive_command(); // process flashing inUse lights // out_alert = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); out_alert = ((outputvalue[devAlert]) >> IO_SHIFT); out_doorAlert = (remoteoutput[devAlert] >> IO_SHIFT); // flash on if ((MS_TIMER %500) < 300) { out_inuse = (outputvalue[devIUF] | outputvalue[devIUS]) >> IO_SHIFT; out_inuse2 = (outputvalue[dev2IUF] | outputvalue[dev2IUS]) >> IO_SHIFT; } // or flash off else { out_inuse = outputvalue[devIUS] >> IO_SHIFT; out_inuse2 = outputvalue[dev2IUS] >> IO_SHIFT; } // handle carrier in chamber light // Need to shift CIC input back to (1..4) range for correct output out_cic = carrierInChamber(MY_STATIONS)>>IO_SHIFT; // Process alarm output or purge mode flashing if (outputvalue[devAlarm] || purge_mode==1) { // override use of inuse and carrier-in-chamber if ((MS_TIMER %300) < 150) { out_inuse=MY_STATIONS; out_inuse2=MY_STATIONS; out_cic=0; } else { out_inuse=0; out_inuse2=0; out_cic=MY_STATIONS; } } // Write out alerts and inUse light do_arrivalAlert(0, out_alert & 1); do_inUseLight(0, out_inuse & 1); // do_inUseLight2(0, out_inuse2 & 1); output reassigned v417 and later do_doorAlert(0, out_doorAlert & 1); do_CICLight(0, out_cic & 1); // handle door lock reset if (doorUnLockTimer && ((MS_TIMER - doorUnLockTimer) > 2500)) { // Reset door lock doorUnLockTimer = 0; do_doorUnLock(OFF); } } /******************************************************** Communication I/O drivers *********************************************************/ /* Initialize buffers and counters */ #define BAUD_RATE 19200 #define CMD_LENGTH 12 #define RCV_TIMEOUT 2 #define rbuflen 30 #define sbuflen 5 char rbuf[rbuflen], sbuf[sbuflen]; char bufstart; //rcc void disable485whenDone(void) { while (serDwrUsed()); // wait for all bytes to be transmitted while (RdPortI(SDSR) & 0x0C); // wait for last byte to complete serDrdFlush(); // flush the read buffer ser485Rx(); // disable transmitter } /********************************************************/ void enable_commands() { // open serial port D serDopen(BAUD_RATE); ser485Rx(); // enable the receiver serDrdFlush(); // flush the read buffer } /********************************************************/ void send_response(struct iomessage message) { /* Transmits a message/command to the main system. Command string defined as: <STX> <device> <Command> <Station> <Data0..3> <ETX> <CHKSUM> */ char i; char cmdstr[CMD_LENGTH]; char cmdlen; char rcvbuf[CMD_LENGTH]; char rcvlen; unsigned long timeout, cmdsent; cmdlen=CMD_LENGTH; // enable transmitter and send ser485Tx(); /* formulate the full command string */ cmdstr[0] = STX; cmdstr[1] = THIS_DEVICE; cmdstr[2] = message.command; cmdstr[3] = message.station; for (i=0; i<NUMDATA; i++) cmdstr[i+4]=message.data[i]; cmdstr[CMD_LENGTH-2] = ETX; cmdstr[CMD_LENGTH-1] = 0; for (i=0; i<CMD_LENGTH-1; i++) cmdstr[CMD_LENGTH-1] += cmdstr[i]; /* calculate checksum */ // send it cmdlen = serDwrite(cmdstr, CMD_LENGTH); if (cmdlen != CMD_LENGTH) printf("Send command failed, only sent %d chars \n", cmdlen); disable485whenDone(); } /********************************************************/ char get_command(struct iomessage *message) { /* Repeatedly call this function to process incoming commands efficiently. */ int charsinbuf; char msg_address; //worklen, char rtnval, chksum, i; unsigned long t1, t2; char tossed[50]; // charsinbuf = rbuflen-rcc; // worklen = charsinbuf-bufstart; rtnval=FALSE; /* assume none for now */ // align frame to <STX> i=0; t1=MS_TIMER; while ((serDrdUsed() > 0) && (serDpeek() != STX)) { tossed[i]=serDgetc(); i++; } t2=MS_TIMER; if (i>0) { //printf("%ld %ld tossed %d: ",t1, t2, i); //while (i>0) { i--; printf(" %d", tossed[i]); } //printf("\n"); } // if at least 1 command in buffer then get them charsinbuf=0; if (serDrdUsed() >= CMD_LENGTH) charsinbuf = serDread(rbuf, CMD_LENGTH, RCV_TIMEOUT); bufstart = 0; if (charsinbuf==CMD_LENGTH) /* all characters received */ { /* verify STX, ETX, checksum then respond */ if ((rbuf[bufstart] == STX) && (rbuf[bufstart+CMD_LENGTH-2] == ETX)) { // enable transmitter if message is addressed to me only // set msg_address here since i'm using it next msg_address = rbuf[bufstart+1]; if (msg_address==THIS_DEVICE) ser485Tx(); /* check checksum */ chksum=0; for (i=0; i<CMD_LENGTH-1; i++) chksum+=rbuf[bufstart+i]; if (chksum != rbuf[bufstart+CMD_LENGTH-1]) { // no good, send NAK sbuf[0]=NAK; rtnval=FALSE; } else { /* looks good, send ACK */ sbuf[0]=ACK; rtnval=TRUE; } // don't set msg_address here. need to use it up above //msg_address = rbuf[bufstart+1]; // send response if message is addressed to me only if (msg_address==THIS_DEVICE) { // enable transmitter and send ser485Tx(); serDwrite(sbuf, 1); disable485whenDone(); } // If this message for me OR everyone then process it. if ((msg_address==THIS_DEVICE) || (msg_address==ALL_DEVICES)) { // message for me (and possibly others) /* return the command for processing */ message->device=msg_address; message->command=rbuf[bufstart+2]; message->station=rbuf[bufstart+3]; for (i=0; i<NUMDATA; i++) message->data[i]=rbuf[i+bufstart+4]; } else rtnval=FALSE; // command not for me! // Maybe shouldn't flush the buffer // serDrdFlush(); // flush the read buffer } } //else //{ printf("missing chars %d\n", charsinbuf); serDrdFlush(); } return rtnval; } /******************************************************************/ char isMyStation(char station) { //return (station2bit(station) & MY_STATIONS); return (station2bit(station) & THIS_DEVICE_b); } /******************************************************************/ void msDelay(unsigned int delay) { auto unsigned long start_time; start_time = MS_TIMER; if (delay < 500) while( (MS_TIMER - start_time) <= delay ); else while( (MS_TIMER - start_time) <= delay ) hitwd(); } nodebug char secTimeout(unsigned long ttime) { return (ttime > SEC_TIMER) ? FALSE : TRUE; } char Timeout(unsigned long start_time, unsigned long duration) { return ((MS_TIMER - start_time) < duration) ? FALSE : TRUE; } /*******************************************************/ // WATCHDOG AND POWER-LOW RESET COUNTERS /*******************************************************/ char valid_resets; // at myxdata+0 char watchdog_resets; // at myxdata+1 char powerlow_resets; // at myxdata+2 //xdata myxdata[10]; /*******************************************************/ char watchdogCount() { return watchdog_resets; } char powerlowCount() { return powerlow_resets; } /*******************************************************/ void incrementWDCount() { watchdog_resets++; //root2xmem( &watchdog_resets, myxdata+1, 1); } /*******************************************************/ void incrementPLCount() { powerlow_resets++; //root2xmem( &powerlow_resets, myxdata+2, 1); } /*******************************************************/ void loadResetCounters() { // read valid_resets and check //xmem2root( myxdata, &valid_resets, 1); if (valid_resets != 69) { // set to zero and mark valid watchdog_resets=0; //root2xmem( &watchdog_resets, myxdata+1, 1); powerlow_resets=0; //root2xmem( &powerlow_resets, myxdata+2, 1); valid_resets=69; //root2xmem( &valid_resets, myxdata, 1); } else { // Read watchdog and power-low counters //xmem2root( myxdata+1, &watchdog_resets, 1); //xmem2root( myxdata+2, &powerlow_resets, 1); } } int readParameterSettings(void) { // Read the parameter block param int rtn_code; rtn_code = readUserBlock(&param, 0, sizeof(param)); return rtn_code; } int writeParameterSettings(void) { // Write the parameter block param int rtn_code; rtn_code = writeUserBlock(0, &param, sizeof(param)); return rtn_code; } ////////////////////////// // USER ID FUNCTIONS ////////////////////////// int UID_Add(char *ID) { // add the given 12 byte UID to the list and return the position added (-1 if can't add) // first search to make sure ID doesn't already exist int i; char blank[UIDLen]; char enc[UIDLen]; if (UID_Encode(ID, enc) >= 0) { // failed to encode i = UID_Search(enc); if (i == -1) { // not found so add the first blank entry memset(blank, 0, UIDLen); // make blank for (i=0; i<UIDSize; i++) { // if (memcmp(param.UID[i], blank, UIDLen) == 0) { // stick it here and return i memcpy(param.UID[i], enc, UIDLen); printf("Adding id %d\n", i); return i; } } // what? no blanks?? } else { // already in there so return that index return i; } } return -1; } int UID_Del(char *ID) { // clear out one or all user UID's // ID is the 12 byte representation // return 0 if success, -1 if failed or not found char enc[UIDLen]; int i; if (strncmp(ID,"ALL",3)==0) { // erase all UID's for (i=0; i<UIDSize; i++) { memset(param.UID[i], 0, UIDLen); } printf("Deleting All id\n", i); param.UIDSync = 0; // reset sync timestamp return 0; } else { if (UID_Encode(ID, enc) >= 0) { i = UID_Search(enc); if (i >= 0) { memset(param.UID[i], 0, UIDLen); printf("Deleting id %d\n", i); return 0; } } } return -1; } int UID_Search(char *ID) { // search for the given 5-byte UID and return the position // returns index of match or -1 if no match int i; for (i=0; i<UIDSize; i++) { if (memcmp(param.UID[i], ID, UIDLen) == 0) { printf("Found id %d\n", i); return i; } } return -1; } int UID_Get(int UIndex) { // return the (6 or 12 byte)? UID at position UIndex } unsigned int UID_Cksum() { // calculate checksum of all valid UIDs } int UID_Encode(char *UID, char *Result) { // convert 12 byte string into 5 byte UID // Result must be sized to handle 5 bytes // Return -1 if invalid UID or 0 if success int i; int hval; int carry; int uidlen; unsigned long lval; unsigned long llast; unsigned long incr; char hdig[4]; // high 3 digits char ldig[10]; // low 9 digits // deal with length of number up to 12 digits uidlen = strlen(UID); if (uidlen < 10) { // simple math on 4 byte numbers hval = 0; lval = atol(UID); } else { // split after 9th digit and get decimal equivalents strncpy(hdig, UID, uidlen-9); hdig[3]=0; strcpy(ldig, &UID[uidlen-9]); hval = atoi(hdig); lval = atol(ldig); } // do the math incr = 1000000000; llast = lval; carry=0; for (i=0; i<hval; i++) { // long math loop lval = lval + incr; if (lval<llast) carry++; llast = lval; } // transfer back into Result Result[0] = (char)carry; Result[1] = (char)((lval >> 24) & 0xFF) ; Result[2] = (char)((lval >> 16) & 0xFF) ; Result[3] = (char)((lval >> 8) & 0XFF); Result[4] = (char)((lval & 0XFF)); return 0; } int UID_Decode(char *UID, char *Result) { // convert 5 byte UID into 12 byte string // Result must be sized to handle 12+1 bytes // Return -1 if invalid UID or 0 if success int i; unsigned long lval; unsigned long ba; unsigned long bm; unsigned long lo; int hi; int hval; // setup the math lval = (unsigned long)UID[1] << 24; lval = lval | (unsigned long)UID[2] << 16; lval = lval | (unsigned long)UID[3] << 8; lval = lval | (unsigned long)UID[4]; hval = (int)(UID[0]<<4) + (int)((lval & 0xF0000000)>>28); // how many times to loop lo = lval & 0x0FFFFFFF; // highest byte in hi hi=0; ba = 0x10000000; // add this bm = 1000000000; // mod this for (i=0; i<hval; i++) { // do the long math lo = lo + ba; // add hi += (int)(lo / bm); // mod lo = lo % bm; // div } // now put into string if (hi>0) { // longer than 9 digits snprintf(Result, 13, "%d%09lu", hi, lo); Result[12]=0; // null term } else { // less or equal to 9 digits sprintf(Result,"%lu", lo); } return 0; } int UID_Not_Zero(char *UID) { // checks if UID is all zeros or not // returns 0 if all zeros // returns 1 if not all zeros int i; int result; result=0; for (i=0; i<UIDLen; i++) { if (UID[i] > 0) result=1; } return result; } void UID_Clear(char *UID) { // Sets UID to all zeros memset(UID, 0, UIDLen); } void lcd_splashScreen(char view) { // view 0 for initial startup splash (no wait) // view 1 for help->about splash (wait for button) int loop_count, i; char sbuf[15]; int xoff; if (view==0) { for ( loop_count = 0; loop_count < 20; loop_count++) { if ( (i = lcd_Connect()) == lcd_SUCCESS ) break; hitwd(); // "hit" the watchdog timer } //if ( i!= lcd_SUCCESS ) exit (1); // exit if no comm with unit lcd_BeepVolume ( 100 ); // default of 200 is TOO loud lcd_Typematic ( 500, 330 ); // delay .5 secs, repeat 3/sec } // Logo splash screen lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); //lcd_screenSaver(LCD_BRIGHT); xoff = param.orientLandscape ? 0 : 40; // setup offset for orientation lcd_DispBitmap( BMP_COLOMBO_LOGO, 79-xoff, 30+xoff ); lcd_Font("16"); lcd_DispText("Colombo Pneumatic Tube Systems", 55-xoff, lcd_max_y-60, MODE_NORMAL); lcd_DispText("800-547-2820", 115-xoff, lcd_max_y-40, MODE_NORMAL); if (view) { //lcd_DispText("Software version ", 70, 225, MODE_NORMAL); lcd_Font("13"); lcd_DispText(FIRMWARE_VERSION, 108-xoff, lcd_max_y-20, MODE_NORMAL); // show phone numbers for admin, maint, and colombo msDelay(4000); // wait 4 seconds } else { // Please wait message msDelay(1000); lcd_ClearScreen (); lcd_Font("16B"); lcd_DispText("Colombo Pneumatic Tube Systems\n", 0, 0, MODE_NORMAL); //lcd_DispText("Pneumatic Tube System\n", 0, 0, MODE_NORMAL); //lcd_DispText("Software version ", 0, 0, MODE_NORMAL); lcd_DispText(FIRMWARE_VERSION, 0, 0, MODE_NORMAL); lcd_DispText(" ", 0, 0, MODE_NORMAL); lcd_DispText(__DATE__, 0, 0, MODE_NORMAL); lcd_Font("16"); lcd_DispText("\nby MS Technology Solutions, LLC", 0, 0, MODE_NORMAL); lcd_DispText("\nAvailable extended memory ",0,0,MODE_NORMAL); sprintf(sbuf, "%ld\n", xavail((long *)0)); lcd_DispText(sbuf,0,0,MODE_NORMAL); } lcd_Font("16"); } void set_lcd_limits() { // set max x,y based on orientation if (param.orientLandscape) { lcd_max_x = 319; // 0 - 319 lcd_max_y = 240; } else { lcd_max_x = 239; // 0 - 239 lcd_max_y = 320; } } void lcd_resetMsgBackColor(void) { lastBkColor = -1; } void lcd_drawScreen(char whichScreen, char *title) { // whichScreen: // 1: main screen with text boxes, unless title[0]=0 / "" // 2: menu header and bottom buttons // 3: menu header only // 4: menu header, keypad, OK, cancel // 5: header with exit button // 6: header keyboard, next, exit // 7: header clock up/downs, exit // 8: transaction log: pgup, pgdn, help, done // 9: header, keypad, next, exit // 10: header keyboard, OK, cancel int x, dx; int xpos, ypos; lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); lcd_PenWidth(1); lcd_Font("24"); lcd_resetMsgBackColor(); // draw title if needed if (whichScreen >=2) { lcd_BFcolorsB( lcd_BLUE, lcd_WHITE ); // inside color // lcd_Rectangle(5, 5, 235, 40, 1); // inside paint lcd_Rectangle(1, 1, lcd_max_x-1, 40, 1); // inside paint lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); // border color // lcd_Rectangle(5, 5, 235, 40, 0); // border paint lcd_Rectangle(0, 0, lcd_max_x, 40, 0); // border paint lcd_Font("24B"); lcd_DispText(title, lcd_Center(title, 1), 14, MODE_TRANS); } // offset for centering dx = (param.orientLandscape) ? 40 : 0; // now handle screen specific stuff switch (whichScreen) { case 1: if (title[0] != 0) // Buttons? (any) or not ("") { { // Draw boxes for bottom buttons //lcd_BFcolorsB( lcd_LBLUE, lcd_LBLUE ); // inside color // for send button ypos = (param.orientLandscape) ? 237 : 270; lcd_BFcolorsB( lcd_LBLUE, lcd_GREY); // inside color lcd_Rectangle(5, 179, lcd_max_x-4, ypos, 1); // inside paint 158 -> 140 lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(5, 179, lcd_max_x-4, ypos, 0); // border paint // for menu/help lcd_BFcolorsB( lcd_LBLUE, lcd_GREY ); // inside color lcd_Rectangle(5, 270, lcd_max_x-4, 317, 1); // inside paint lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(5, 270, lcd_max_x-4, 317, 0); // border paint // Draw bottom buttons lcd_BFcolorsD( lcd_BLACK, lcd_VLTGRAY_D ); lcd_Font("16B"); lcd_ButtonDef( BTN_MENU, BTN_MOM, // momentary operation BTN_TLXY, 13, lcd_max_y-40, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 300, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Menu", BTN_TXTOFFSET, 10, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_HELP, BTN_TLXY, lcd_max_x-69, lcd_max_y-40, BTN_TXTOFFSET, 12, 9, BTN_TEXT, "Help", BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_Font("32B"); lcd_BFcolorsB( lcd_WHITE, lcd_LGREY); // border color ypos = (param.orientLandscape) ? 190 : 204; xpos = (param.orientLandscape) ? 117 : 77; // make sure to sync positionn with button highlight in lcd_refreshScreen lcd_ButtonDef( BTN_SEND, BTN_TLXY, xpos, ypos, BTN_TEXT, "SEND", BTN_TXTOFFSET, 7, 3, BTN_BMP, BMP_92x40_button, BMP_92x40_button_dn, BTN_END ); } } // Draw LCD Message boxes lcd_BFcolorsB( lcd_LGREY, lcd_LGREY); // border color lcd_Rectangle(5, 5, lcd_max_x-4, 60, 1); // border paint lcd_BFcolorsB( lcd_BLUE, lcd_LGREY); // border color lcd_Rectangle(5, 5, lcd_max_x-4, 60, 0); // border paint lcd_Rectangle(5, 60, lcd_max_x-4, 130, 0); // border paint lcd_Rectangle(5, 130, lcd_max_x-4, 179, 0); // border paint // since this screen was just cleared, for a refresh of the lcd messages /// reset_msg_timer(NOW); break; case 2: // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_PREV, BTN_MOM, // momentary operation BTN_TLXY, 5, lcd_max_y-40, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "PgUp", BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_NEXT, BTN_TEXT, "PgDn", BTN_END ); /* lcd_ButtonDef( 1, BTN_TEXT, "", BTN_END ); lcd_ButtonDef( BTN_SAVE, BTN_TEXT, "", BTN_END ); */ lcd_ButtonDef( BTN_CANCEL, //BTN_TXTOFFSET, 5, 9, BTN_TLXY, lcd_max_x-69, lcd_max_y-40, // starting x,y for buttons BTN_TEXT, "Done", BTN_END ); break; case 3: break; case 4: lcd_ShowKeypad(0); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_OK, BTN_MOM, // momentary operation BTN_TLXY, 5, lcd_max_y-40, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "OK", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 14, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 5, 9, BTN_TLXY, lcd_max_x-69, lcd_max_y-40, BTN_TEXT, "Cancel", BTN_END ); break; case 5: // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_EXIT, BTN_MOM, // momentary operation BTN_TLXY, lcd_max_x-69, lcd_max_y-40, BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 6: // keyboard entry /// lcd_drawKeyboard(); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_NEXT, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Next", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, lcd_max_x-69, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 7: // clock with up/downs // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_SAVE, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // print date/time message lcd_Font("16x32i"); /// lcd_DispText(sys_message[MSG_DATE_TIME].msg, 30, 60, MODE_NORMAL); // Draw up/dn buttons lcd_ButtonDef( 0, // month + BTN_MOM, // momentary operation BTN_TLXY, 46, 100, // starting x,y for buttons BTN_MARGINS, 46, 264, // set left and right margins BTN_TYPE, BUTTON_RELEASE, BTN_SEP, 48, 40, // set up for button sep BTN_TEXT, "+", BTN_TXTOFFSET, 8, 1, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); // month lcd_ButtonDef( 2, BTN_MOM, BTN_TEXT, "+", BTN_END ); // day lcd_ButtonDef( 4, BTN_MOM, BTN_TEXT, "+", BTN_END ); // year lcd_ButtonDef( 6, BTN_MOM, BTN_TEXT, "+", BTN_END ); // hour lcd_ButtonDef( 8, BTN_MOM, BTN_TEXT, "+", BTN_END ); // min lcd_ButtonDef( 1, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 3, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 5, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 7, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 9, BTN_MOM, BTN_TEXT, "-", BTN_END ); break; case 8: // PgUp, PgDn, Help, Done // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_PREV, BTN_MOM, // momentary operation BTN_TLXY, 1, lcd_max_y-34, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 1, 330, // set left and right margins BTN_SEP, 60, 43, // set up for button sep BTN_TEXT, "PgUp", BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_NEXT, BTN_TEXT, "PgDn", BTN_END ); lcd_ButtonDef( BTN_HELP, BTN_TXTOFFSET, 12, 9, BTN_TEXT, "Help", BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TEXT, "Exit", BTN_END ); break; case 9: /// lcd_ShowKeypad(1); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_NEXT, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Next", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, lcd_max_x-63, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 10: // keyboard entry /// lcd_drawKeyboard(); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_OK, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "OK", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 14, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 5, 9, BTN_TLXY, lcd_max_x-63, 205, // starting x,y for buttons BTN_TEXT, "Cancel", BTN_END ); break; } } int lcd_Center(char * string, char font) { int temp; temp = param.orientLandscape ? 160 : 120; if (font==1) temp = temp - (int)(strlen(string) * 7); // "24" else if (font==2) temp = temp - (int)(strlen(string) * 4); // "16" else if (font==3) temp = temp - (int)(strlen(string) * 9); // "32" // if (temp < 6) temp = 6; if (temp < 2) temp = 2; return temp; } int lcd_RefreshScreen(char refresh) { // update system status and local status // refresh = 0: update screen only when status is changing // refresh else: rewrite all messages static char mydoor, mycic, myssm; char cicmsg; int ypos, dx; char buf[20]; struct tm time; static unsigned long lastclock; char flashSend; static char lastFlashSend; int bgColor; lcd_Font("32B"); dx = (param.orientLandscape) ? 40 : 0; // update system state message if ((systemStateMsg != myssm) || (refresh)) { // erase last message lcd_BFcolorsB( lcd_LGREY, lcd_LGREY); // color lcd_Rectangle(10, 10, 234+dx, 55, 1); // paint lcd_BFcolorsB( lcd_BLACK, lcd_LGREY); ypos=18; if (systemStateMsg == 8) { lcd_Font("24B"); lcd_DispText("WAIT FOR REMOVAL", 15+dx, ypos-5, MODE_NORMAL); lcd_Font("24B"); strcpy(buf, "AT "); strcat(buf, param.mainName); lcd_DispText(buf, lcd_Center(buf,1), ypos+15, MODE_NORMAL); } else if (systemStateMsg == 1) lcd_DispText("READY", 75+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 2) lcd_DispText("RECEIVING", 45+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 3) lcd_DispText("SENDING", 59+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 4) lcd_DispText("PAUSED", 65+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 5) lcd_DispText("BUSY", 80+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 6) lcd_DispText("ALARM", 75+dx, ypos, MODE_NORMAL); else if (systemStateMsg == 7) lcd_DispText("QUEUED", 65+dx, ypos, MODE_NORMAL); else lcd_DispText("UNKNOWN", 50+dx, 18, MODE_TRANS); //lcd_BFcolorsB( lcd_GREEN, lcd_LGREY); myssm = systemStateMsg; } // what is carrier status 1, 2, 3 // WHAT ABOUT IN-ROUTE TO (FROM) MAIN if (isMyStation(transStation)) { cicmsg = 5; bgColor = lcd_WHITE; // sending to/from main } else if (carrier_attn) { cicmsg = 1; bgColor = lcd_YELLOW; } else if (rts_latch) { cicmsg = 4; bgColor = lcd_MAGENTA; } else if (carrierInChamber(MY_STATIONS)) { cicmsg = 2; bgColor = lcd_GREEN; } else { cicmsg = 3; bgColor = lcd_WHITE; // no carrier nothing else active } // update carrier message if ((cicmsg != mycic) || refresh) { // status has changed, update message // draw colored box lcd_Font("32B"); lcd_BFcolorsB( bgColor, bgColor); lcd_Rectangle(6, 61, 234+dx+dx, 129, 1); // Fill the area lcd_BFcolorsB( lcd_BLACK, bgColor); if (cicmsg==3) // no carrier { // different message style for this lcd_Font("24B"); lcd_DispText("INSERT CARRIER", 32+dx, 70, MODE_NORMAL); lcd_DispText("AND PRESS SEND", 28+dx, 97, MODE_NORMAL); } else if (cicmsg==5) { // in route to main if (transDirection==DIR_SEND) strcpy(buf, "IN ROUTE FROM"); else strcpy(buf, "IN ROUTE TO"); lcd_DispText(buf, lcd_Center(buf,3), 67, MODE_NORMAL); lcd_DispText(param.mainName, lcd_Center(param.mainName,3), 97, MODE_NORMAL); refresh=TRUE; // Force update of door message } else { // 1st line "CARRIER" lcd_DispText("CARRIER", 60+dx, 67, MODE_TRANS); if (cicmsg==1) { // carrier arrival //lcd_BFcolorsB( lcd_RED, lcd_WHITE); lcd_DispText("ARRIVED ", 63+dx, 97, MODE_NORMAL); } else if (cicmsg==2) { // carrier in chamber //lcd_BFcolorsB( lcd_GREEN, lcd_WHITE); lcd_DispText(" READY ", 63+dx, 97, MODE_NORMAL); } else if (cicmsg==4) { // carrier in chamber //lcd_BFcolorsB( lcd_MAGENTA, lcd_WHITE); lcd_DispText("QUEUED ", 63+dx, 97, MODE_NORMAL); } } mycic = cicmsg; } // update door message if ((doorClosed(MY_STATIONS) != mydoor) || refresh) { // door status has changed or forced refresh lcd_Font("32B"); if (doorClosed(MY_STATIONS)) { // door is closed lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); lcd_Rectangle(6, 131, 234+dx+dx, 178, 1); // Fill the area lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); if (isMyStation(transStation)) { // busy, do not use lcd_Font("24B"); lcd_DispText("BUSY DO NOT USE", 20+dx, 140, MODE_TRANS); } else { // normal lcd_DispText("DOOR CLOSED", 20+dx, 140, MODE_TRANS); } } else { // door is opened lcd_BFcolorsB( lcd_YELLOW, lcd_YELLOW); lcd_Rectangle(6, 131, 234+dx+dx, 178, 1); // Fill the area lcd_BFcolorsB( lcd_BLACK, lcd_YELLOW); lcd_DispText("DOOR OPEN", 40+dx, 140, MODE_TRANS); } mydoor = doorClosed(MY_STATIONS); } // EMPHASIZE SEND BUTTON WHEN THE PLANETS ALIGN // CIC, DOOR CLOSED, SYSTEM READY) if ((cicmsg==2) && (doorClosed(MY_STATIONS)) && (systemStateMsg == 1)) { // highlight send flashSend=TRUE; } else { // regular send flashSend=FALSE; } if ((flashSend != lastFlashSend) || refresh) { // state changed if (flashSend) { lcd_BFcolorsB( lcd_BLACK, lcd_GREEN ); } else { lcd_BFcolorsB( lcd_WHITE, lcd_LGREY ); } lcd_Font("32B"); ypos = (param.orientLandscape) ? 193 : 207; // should be button ypos + 3 // make sure this highlight syncs with the button pos in lcd_drawScreen lcd_DispText("SEND", 84+dx, ypos, MODE_NORMAL); lastFlashSend=flashSend; } // show station name and clock if (SEC_TIMER != lastclock) { lastclock=SEC_TIMER; lcd_Font("13B"); lcd_BFcolorsB( lcd_BLACK, lcd_LBLUE); lcd_DispText(param.stationName, lcd_Center(param.stationName,2), 276, MODE_NORMAL); tm_rd(&time); // read all time data sprintf(buf, "%02d/%02d/%02d", time.tm_mon, time.tm_mday, time.tm_year%100); lcd_DispText(buf, 88+dx, 289, MODE_NORMAL); sprintf(buf, "%02d:%02d:%02d", time.tm_hour, time.tm_min, time.tm_sec); lcd_DispText(buf, 90+dx, 302, MODE_NORMAL); } } char lcd_stationButton; void lcd_ProcessButtons(void) { char button; button = lcd_GetTouch(1); if (isMyStation(transStation)) { // ignore buttons when busy } else { // ok to process buttons if (button > 0) { if (button == BTN_SEND) { lcd_stationButton=1; } else if (button == BTN_MENU) { // enter setup menu lcd_enterSetupMode(1); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen lcd_RefreshScreen(1); } else if (button == BTN_HELP) { lcd_helpScreen(0); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen lcd_RefreshScreen(1); } } } } char lcd_SendButton(void) { // returns the lcd_stationButton char rtnVal; #GLOBAL_INIT { lcd_stationButton=0; } rtnVal = lcd_stationButton; lcd_stationButton=0; // reset whenever it is accesses return rtnVal; } /******************************************************************/ // MAKING DESIGN ASSUMPTION --> MNU_xxx value is the same as the index in menu[] // define menu item numbers enum MenuItems { MNU_COMM_STAT, MNU_SETPASSWORD, MNU_CLEARPASSWORDS, MNU_DEF_STATIONS, MNU_RESET, MNU_ADMIN_FEATURES, MNU_MAINT_FEATURES, MNU_SYSTEM_CONFIG, MNU_VIEW_LOGS, MNU_VIEW_TLOG, // Transaction log MNU_VIEW_SLOG, // Summary log MNU_VIEW_ELOG, // Event log MNU_VIEW_ALOG, // Alarm log MNU_CHECK_SFLASH, MNU_ANALYZE_LOG, MNU_LCD_CALIBRATE, MNU_SHOW_IPADDR, MNU_SHOW_INPUTS, MNU_SET_STATION, MNU_RARRIVAL_BEEP, MNU_LCD_ORIENTATION, MNU_LAST }; // Define bitmasks for activation of menu items #define MNU_ADV 0x0E #define MNU_STD 0x01 #define MNU_ALRM 0x10 #define MNU_NONE 0x00 // Define parameter types #define MNU_FLAG 01 #define MNU_VAL 02 #define MNU_TIME 03 #define MNU_CLK 04 #define MNU_OTHR 05 // define parameter menu char NOch; // dummy/temporary character place holder const struct{ char item; // menu item //char usage; // when available to the user char *msg1; // pointer to message char partype; // parameter type (flag, clock, integer value, other) char *parval; // parameter value unsigned long min; // parameter minimum unsigned long max; // parameter maximum (or don't save flag changes [=0]) char units[4]; // parameter units display } menu[] = { MNU_COMM_STAT, "SHOW COMMUNICATIONS",MNU_OTHR, &NOch, 0, 0, "", MNU_SETPASSWORD, "SET PASSWORD", MNU_OTHR, &NOch, 0, 0, "", MNU_CLEARPASSWORDS, "CLEAR PASSWORDS", MNU_OTHR, &NOch, 0, 0, "", MNU_DEF_STATIONS, "SET ACTIVE STATIONS",MNU_OTHR, &NOch, 0, 0, "", MNU_RESET, "RESTART SYSTEM", MNU_OTHR, &NOch, 0, 0, "", MNU_ADMIN_FEATURES, "ADMIN FEATURES", MNU_OTHR, &NOch, 0, 0, "", MNU_MAINT_FEATURES, "MAINT FEATURES", MNU_OTHR, &NOch, 0, 0, "", MNU_SYSTEM_CONFIG, "SYSTEM CONFIG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_LOGS, "VIEW LOGS", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_TLOG, "VIEW TRANSACTIONS", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_SLOG, "VIEW SUMMARY LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_ELOG, "VIEW EVENT LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_ALOG, "VIEW RECENT ALARMS", MNU_OTHR, &NOch, 0, 0, "", MNU_CHECK_SFLASH, "CHECK SERIAL FLASH", MNU_OTHR, &NOch, 0, 0, "", MNU_ANALYZE_LOG, "ANALYZE EVENT LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_LCD_CALIBRATE, "CALIBRATE SCREEN", MNU_OTHR, &NOch, 0, 0, "", MNU_SHOW_IPADDR, "SHOW IP ADDRESS", MNU_OTHR, &NOch, 0, 0, "", MNU_SHOW_INPUTS, "SHOW INPUTS", MNU_OTHR, &NOch, 0, 0, "", MNU_SET_STATION, "SET STATION NUMBER", MNU_VAL, (char *)&param.stationNum, 1, 7, "", MNU_RARRIVAL_BEEP, "SET AUDIBLE ALERT", MNU_FLAG, &param.remoteAudibleAlert, 0, 1, "", MNU_LCD_ORIENTATION,"ORIENT LANDSCAPE", MNU_FLAG, &param.orientLandscape, 0, 1, "", MNU_LAST, "END", MNU_NONE, &NOch, 0, 0, "" }; char menuOrder[25]; void setupMenuOrder(char menuLevel) { char i; i=0; // content of menu depends on if passwords are enabled or not switch (menuLevel) { case 0: // ALARM break; case 1: // Basic User menuOrder[i++]=MNU_VIEW_LOGS; //menuOrder[i++]=MNU_MAINT_FEATURES; //menuOrder[i++]=MNU_ADMIN_FEATURES; // do allow admin for slave menuOrder[i++]=MNU_SYSTEM_CONFIG; menuOrder[i++]=MNU_RARRIVAL_BEEP; break; case 2: // Administrator break; case 3: // Maintenance break; case 4: // System configuration (Colombo only) menuOrder[i++]=MNU_SET_STATION; //menuOrder[i++]=MNU_DEF_STATIONS; //menuOrder[i++]=MNU_SHOW_IPADDR; menuOrder[i++]=MNU_SHOW_INPUTS; menuOrder[i++]=MNU_SETPASSWORD; menuOrder[i++]=MNU_CLEARPASSWORDS; menuOrder[i++]=MNU_LCD_ORIENTATION; //menuOrder[i++]=MNU_CHECK_SFLASH; //menuOrder[i++]=MNU_ANALYZE_LOG; menuOrder[i++]=MNU_LCD_CALIBRATE; menuOrder[i++]=MNU_RESET; break; case 5: // view logs menuOrder[i++]=MNU_VIEW_SLOG; // transaction summary menuOrder[i++]=MNU_VIEW_TLOG; // transaction log //menuOrder[i++]=MNU_VIEW_ELOG; // event log menuOrder[i++]=MNU_VIEW_ALOG; // alarm log break; case 6: // secure card setup //menuOrder[i++]=MNU_SECURE_ENABLE; //menuOrder[i++]=MNU_CARDID_ENABLE; //menuOrder[i++]=MNU_SERVER_ADDRESS; //menuOrder[i++]=MNU_SYNC_INTERVAL; //menuOrder[i++]=MNU_RESYNC_USERS; //menuOrder[i++]=MNU_CARD_FORMAT; //menuOrder[i++]=MNU_SECURE_R9MAX; //menuOrder[i++]=MNU_SECURE2_L3DIGITS; //menuOrder[i++]=MNU_SECURE2_R9MIN; //menuOrder[i++]=MNU_SECURE2_R9MAX; break; } menuOrder[i]=MNU_LAST; } //#define PAGE_SIZE 7 const char * const title[7] = { "ALARM MENU", "MENU", "ADMIN MENU", "MAINTENANCE MENU", "CONFIG MENU", "LOGS MENU","SECURE TRANS MENU" }; char lcd_ShowMenu(char menuLevel, char page) { // returns if a next page is available char i, j; char rtnval; int row, count, button; char ttl; char btnX; // menu item x position char PAGE_SIZE; // 5 for landscape, 7 for portrait if (param.orientLandscape) { PAGE_SIZE=5; btnX=40; } else { PAGE_SIZE=7; btnX=0; } rtnval=TRUE; setupMenuOrder(menuLevel); ttl = (menuLevel<7) ? menuLevel : 0; // which title to show lcd_drawScreen(2,title[ttl]); // show the screen & title // make sure we can handle the page size if (page >= 1) { i = page * PAGE_SIZE; // count backwards and reduce i if needed for (j=i; j>0; j--) if (menuOrder[j]==MNU_LAST) i=j-1; } else i=0; count=0; lcd_Font("16B"); while ((menuOrder[i] != MNU_LAST) && (count < PAGE_SIZE)) { row = 47 + count*30; // put up text //lcd_DispText(sys_message[menu[menuOrder[i]].msg1].msg, row, 50, MODE_TRANS); // put up button lcd_ButtonDef( BTN_MNU_FIRST+menuOrder[i], // menu items at 21+ BTN_MOM, // momentary operation BTN_TLXY, btnX, row, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 315, BTN_TEXT, menu[menuOrder[i]].msg1, BTN_TXTOFFSET, 10, 6, BTN_BMP, BMP_long_button, BMP_long_button_dn, BTN_END ); i++; count++; } // show page # at the bottom j=0; while (menuOrder[j] != MNU_LAST) j++; count = ((j-1) / PAGE_SIZE) + 1; lcd_showPage(page+1, count); // is there another page to show? //if ( (menuOrder[i] == MNU_LAST) || (menuOrder[i+1] == MNU_LAST) ) rtnval=FALSE; if ( (menuOrder[i] == MNU_LAST) ) rtnval=FALSE; return rtnval; } char lcd_ProcessMenuItem(char menu_idx, char *menu_level) { // can modify menu_level using advanced configuration menu item // returns true if a flash parameter changed unsigned long clock_in_seconds; char work; char maxDigits; unsigned long temp_ulong; static char parChanged; parChanged=FALSE; // assume not switch (menu[menu_idx].partype) { case MNU_VAL: //lcd_drawScreen(4);sys_message[menu[menuOrder[i]].msg1].msg if (menu[menu_idx].max > 999) { // unsigned long data type maxDigits = 9; // 9 digits max temp_ulong = *(unsigned long*)menu[menu_idx].parval; // type is ulong } else { // character data type maxDigits = 3; // only 3 digits max temp_ulong = *menu[menu_idx].parval; // type is character } if (lcd_GetNumberEntry(menu[menu_idx].msg1, &temp_ulong, menu[menu_idx].min, menu[menu_idx].max, menu[menu_idx].units, maxDigits, 0)) { if (menu[menu_idx].max > 999) // cast unsigned long *(unsigned long*)menu[menu_idx].parval = temp_ulong; else // cast character *menu[menu_idx].parval = (char)temp_ulong; parChanged=TRUE; } break; case MNU_FLAG: parChanged=lcd_SelectChoice(menu[menu_idx].parval, menu[menu_idx].msg1, "YES", "NO"); // Some flags don't require parameters to be saved (when max=0); if (menu[menu_idx].max == 0) parChanged=0; // Don't save parameter change to flash //if (menu[menu_idx].item == MNU_ALARM_SOUND) alarm(ON); // update alarm if needed break; case MNU_OTHR: switch (menu[menu_idx].item) { case MNU_ADMIN_FEATURES: // get pin for next menu level if (lcd_enableAdvancedFeatures(2, menu[menu_idx].msg1)) *menu_level=2; break; case MNU_MAINT_FEATURES: // get pin for next menu level if (lcd_enableAdvancedFeatures(3, menu[menu_idx].msg1)) *menu_level=3; break; case MNU_SYSTEM_CONFIG: // get pin for next menu level if (lcd_enableAdvancedFeatures(4, menu[menu_idx].msg1)) *menu_level=4; break; case MNU_VIEW_LOGS: *menu_level=5; // Logs menu items break; case MNU_DEF_STATIONS: // define active stations //parChanged=lcd_defineActiveStations(); break; case MNU_SETPASSWORD: // set new password // get the PIN for the given menu level //if (*menu_level==2) parChanged |= lcd_getPin(param.adminPassword, "SET ADMIN PASSWORD"); //else if (*menu_level==3) parChanged |= lcd_getPin(param.maintPassword, "SET MAINT PASSWORD"); //else if (*menu_level==4) parChanged |= lcd_getPin(param.cfgPassword, "SET CONFIG PASSWORD"); break; case MNU_CLEARPASSWORDS: // reset passwords ///param.adminPassword[0]=0; ///param.maintPassword[0]=0; parChanged=TRUE; break; case MNU_COMM_STAT: //show_comm_test(1); // wait for button press break; case MNU_VIEW_SLOG: lcd_showTransSummary(); break; case MNU_VIEW_TLOG: lcd_showTransactions(0); break; case MNU_VIEW_ALOG: lcd_showTransactions(1); break; case MNU_SHOW_IPADDR: //show_ip_address(); break; case MNU_SHOW_INPUTS: lcd_show_inputs(); break; case MNU_RESET: // go into long loop to allow watchdog reset clock_in_seconds = SEC_TIMER; lcd_drawScreen(3, menu[menu_idx].msg1); lcd_Font("24"); lcd_DispText("SYSTEM RESTARTING", 5, 85, MODE_NORMAL); #asm ipset 3 ; disable interrupts so that the periodic ISR doesn't hit the watchdog. ld a,0x53 ; set the WD timeout period to 250 ms ioi ld (WDTCR),a #endasm while (SEC_TIMER - clock_in_seconds < 5); lcd_DispText("UNABLE TO RESET", 50, 115, MODE_NORMAL); msDelay(1000); break; } } return parChanged; } /******************************************************************/ char lcd_GetNumberEntry(char *description, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units, char max_digits, char nc_as_ok) { // Allows numeric keypad entry using the touch screen // return value is 0 = *no change or cancel or timeout // 1 = valid number entered and updated to par_value // * no change returns 1 if nc_as_ok is true int button; char keepLooping; unsigned long inval; char number[11]; // for display of numeric text char numDigits; char rtnval; int xref, yref; char i; inval=0; keepLooping=TRUE; numDigits=0; rtnval=0; // assume no good // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; // draw screen with keypad lcd_drawScreen(4, "ENTER VALUE"); // print title and place to print the number xref=80; // x pos of input box yref=76; lcd_Font("18BC"); lcd_DispText(description, lcd_Center(description, 2)-20, 50, MODE_NORMAL); // hack position with -10 lcd_DispBitmap( BMP_input_box, xref, yref ); lcd_DispText(par_units, xref+67, yref+8, MODE_NORMAL); // show actual, min and max lcd_Font("16B"); lcd_DispText("Min = ", 20, 110, MODE_NORMAL); lcd_DispText(ltoa((long)par_min, number), 0, 0, MODE_NORMAL); lcd_DispText("; Current = ", 0, 0, MODE_NORMAL); lcd_DispText(ltoa((long)*par_value, number), 0, 0, MODE_NORMAL); lcd_DispText("; Max = ", 0, 0, MODE_NORMAL); lcd_DispText(ltoa((long)par_max, number), 0, 0, MODE_NORMAL); // Setup for first character to display number[0]=0; number[1]=0; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= '0') && (button <= '9') && (numDigits < max_digits)) { // add the digit to the string number[numDigits]=button; numDigits++; number[numDigits]=0; // trailing null lcd_DispText(number, xref+5, yref+7, MODE_TRANS); // show the number } else if ((button == BTN_DEL) && (numDigits > 0)) { numDigits--; number[numDigits]=0; // trailing null // reprint the screen lcd_DispBitmap( BMP_input_box, xref, 80 ); lcd_DispText(number, xref+5, yref+7, MODE_TRANS); // show the number } else if (button == BTN_CANCEL) { keepLooping=FALSE; } else if (button == BTN_OK) { // was anything entered? if (numDigits==0) { // no entry if (nc_as_ok) { // return nc as ok rtnval=1; } else { lcd_DispText("NO CHANGE MADE", 65, 265, MODE_REV); msDelay(750); } keepLooping=FALSE; } else { inval = (unsigned long)atol(number); if ((inval >= par_min) && (inval <= par_max)) { keepLooping=FALSE; *par_value = inval; rtnval=1; } else { lcd_DispText("OUTSIDE RANGE", 65, 265, MODE_REV); msDelay(750); numDigits=0; number[0]=0; number[1]=0; lcd_DispBitmap( BMP_input_box, xref, yref ); lcd_DispText(number, xref+5, yref+7, MODE_TRANS); // show the number } } } } } return rtnval; } void lcd_enterSetupMode(char operatorLevel) { int button; char mych; char keepLooping; char menu_idx; char page; char anotherPage; char showPage; char newLevel; char changed; keepLooping=TRUE; page=0; changed=FALSE; // None yet // clear the button input buffer lcd_GetTouch(1); anotherPage = lcd_ShowMenu(operatorLevel, page); // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands // inKey = getKey(); showPage=FALSE; button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= BTN_MNU_FIRST) && (button <= BTN_MNU_FIRST+MNU_LAST)) { menu_idx = button-BTN_MNU_FIRST; newLevel = operatorLevel; changed |= lcd_ProcessMenuItem(menu_idx, &newLevel); // Did we advance to a new menu if (newLevel != operatorLevel) { operatorLevel = newLevel; page=0; } // continue to show menu? if (operatorLevel==99) keepLooping=FALSE; // update display of menu items? if (!secTimeout(menu_timeout)) showPage=TRUE; } else if (button == BTN_PREV) { if (page>0) { page--; showPage=TRUE;} } else if (button == BTN_NEXT) { if (anotherPage) { page++; showPage=TRUE;} } //else if (button == BTN_SAVE) else if (button == BTN_CANCEL) // DONE { if (changed) { // save changes if needed lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); lcd_Font("24"); lcd_DispText("SAVING CHANGES ...", 10, 50, MODE_NORMAL); if (writeParameterSettings() == 0) lcd_DispText("\nCHANGES SAVED", 0, 0, MODE_NORMAL); else lcd_DispText("\nERROR SAVING CHANGES", 0, 0, MODE_REV); msDelay(800); //sendParametersToLogger(); // send parameters to data logger } keepLooping = FALSE; } //else if (button == BTN_CANCEL) keepLooping = FALSE; // show the same or next menu page if needed if (showPage && keepLooping) anotherPage = lcd_ShowMenu(operatorLevel, page); } } } nodebug char lcd_enableAdvancedFeatures(char menu_level, char * description) { // get password for the requested level char reqdPW[5]; char altPW[5]; // for non-settable cfg (Colombo) PW char enteredPW[5]; char rtnVal; strcpy(altPW, "xxxx"); // start with pin that can't be entered // determine which password to compare with switch (menu_level) { // case 2: strcpy(reqdPW, param.adminPassword); break; // case 3: strcpy(reqdPW, param.maintPassword); break; // case 4: strcpy(reqdPW, param.cfgPassword); default: reqdPW[0]=0; } strcpy(altPW, "<PASSWORD>"); // 2321 is always available rtnVal=FALSE; // assume no good if (strlen(reqdPW)==0) rtnVal=TRUE; else { // get the password/pin if (lcd_getPin(enteredPW, description)) { // allow entry of settable or alternate/fixed pin if ( (strcmp(enteredPW, reqdPW)==0) || (strcmp(enteredPW, altPW)==0) ) rtnVal=TRUE; else { // sorry charlie lcd_BFcolorsB( lcd_WHITE, lcd_RED); lcd_Font("24"); lcd_DispText(" INCORRECT PIN ", 17, 160, MODE_NORMAL); msDelay(2000); } } } return rtnVal; } nodebug char lcd_getPin(char *PIN, char *description) { // get a 4 digit pin from the touch screen int button; char keepLooping; char number[5]; // for storing entered digits char asteric[5]; // for display on screen char numDigits, maxDigits; char rtnval; char i; keepLooping=TRUE; numDigits=0; maxDigits=4; rtnval=0; // assume no good // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; // draw screen with keypad lcd_drawScreen(4, description); // print title and place to print the number lcd_Font("18BC"); lcd_DispText("ENTER 4 DIGIT PIN", 20, 50, MODE_NORMAL); lcd_DispBitmap( BMP_input_box, 45, 80 ); // show actual, min and max lcd_Font("32B"); // Setup for first character to display number[0]=0; number[1]=0; asteric[0]=0; asteric[1]=0; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= '0') && (button <= '9') && (numDigits < maxDigits)) { // add the digit to the string number[numDigits]=button; asteric[numDigits]='*'; numDigits++; number[numDigits]=0; // trailing null asteric[numDigits]=0; lcd_DispText(asteric, 50, 87, MODE_TRANS); // show the number } else if ((button == BTN_DEL) && (numDigits > 0)) { numDigits--; number[numDigits]=0; // trailing null asteric[numDigits]=0; // reprint the screen lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_DispText(asteric, 50, 87, MODE_TRANS); // show the number } else if (button == BTN_CANCEL) { keepLooping=FALSE; } else if (button == BTN_OK) { strcpy(PIN, number); keepLooping=FALSE; rtnval=1; } } } return rtnval; } void lcd_show_inputs() { // shows digital inputs on-screen for diagnosis char done; char i, j, col, msgbuf[25]; char inKey; int button; lcd_drawScreen(5, "SHOW INPUTS"); //strcpy(msgbuf, sys_message[MSG_BLANK].msg); // buffer to show stations done=FALSE; // Loop until done or timeout while ((done==FALSE) && !secTimeout(menu_timeout)) { maintenance(); // watchdog, led activity, UDP commands menu_timeout = SEC_TIMER + 60; // never timeout like this button = lcd_GetTouch(100); // If BTN_SAVE, save changes if (button == BTN_EXIT) // Exit button { done=TRUE; } lcd_DispText("Arrival: ", 20, 50, MODE_NORMAL); lcd_DispText(di_carrierArrival ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nIn Chamber: ", 0, 0, MODE_NORMAL); lcd_DispText(di_carrierInChamber ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nDoor: ", 0, 0, MODE_NORMAL); lcd_DispText(di_doorClosed ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nSend Button: ", 0, 0, MODE_NORMAL); sprintf(msgbuf, "%X ", di_requestToSend); lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); lcd_DispText("\nDiverter Pos: ", 0, 0, MODE_NORMAL); //sprintf(msgbuf, "%X ", di_diverterPos); //lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); lcd_DispText("\nRaw Inputs: ", 0, 0, MODE_NORMAL); strcpy(msgbuf,""); // blank out j=readDigBank(0); for (i=0; i<8; i++) strcat(msgbuf, (j & 1<<i) ? "1" : "0"); strcat(msgbuf, " "); j=readDigBank(1); for (i=0; i<8; i++) strcat(msgbuf, (j & 1<<i) ? "1" : "0"); lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); lcd_DispText("\nIP address: ",0,0,MODE_NORMAL); lcd_DispText(myIPaddress,0,0,MODE_NORMAL); } } void lcd_ShowKeypad(char opts) { // display 0..9 in a keypad arrangement on the screen // opts = 0 = no '-' button // 1 = use '-' button char i; char btn[2]; int x1, x2, y1; i=1; // first digit 1 btn[0]=49; btn[1]=0; if (param.orientLandscape) { x1=200; x2=300; y1=55; } else { x1=120; x2=190; y1=120; } // draw first button lcd_Font("16B"); lcd_ButtonDef( '0'+i, BTN_MOM, // momentary operation BTN_TLXY, x1, y1, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, x1, x2, // set left and right margins BTN_SEP, 35, 35, // set up for button sep BTN_TEXT, btn, BTN_TXTOFFSET, 11, 9, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); // draw 2-9 for (i=2; i<10; i++) { btn[0]++; lcd_ButtonDef( '0'+i, BTN_TEXT, btn, BTN_END ); } // draw last buttons if (opts==1) // use '-' button { i='-'; btn[0]='-'; lcd_ButtonDef( i, BTN_TEXT, btn, BTN_END ); } // draw '0' i=0; btn[0]=48; lcd_ButtonDef( '0'+i, BTN_TEXT, btn, BTN_END ); // draw 'Del' lcd_ButtonDef( BTN_DEL, BTN_TXTOFFSET, 5, 9, BTN_TEXT, "Del", BTN_END ); } void lcd_showPage(long thisPage, long lastPage) { // show page x of y char buf[25]; return; sprintf(buf, "Page %ld of %ld ", thisPage, lastPage); lcd_Font("6x9"); lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_DispText(buf, 145, 218, MODE_NORMAL); } int lcd_SelectChoice(char *choice, char *label, char *optZero, char *optOne) { // Show label and two choices and allow selection // choice is modified as TRUE (optZero) or FALSE (optOne) based on selection // function returns 0 if cancel or 1 if a choice is made int button; int x1; x1 = param.orientLandscape ? 150 : 110; lcd_drawScreen(3, "MENU"); lcd_Font("24"); lcd_DispText(label, lcd_Center(label, 1), 50, MODE_NORMAL); lcd_DispText(optZero, x1, 85, MODE_NORMAL); lcd_DispText(optOne, x1, 115, MODE_NORMAL); // show optZero choice x1 = x1 - 40; lcd_ButtonDef( BTN_YES_ON, BTN_LAT, // latching operation BTN_TLXY, x1, 80, // starting x,y for buttons BTN_TYPE, (*choice) ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show optOne choice lcd_ButtonDef( BTN_NO_OFF, BTN_TLXY, x1, 110, // starting x,y for buttons BTN_TYPE, (*choice) ? BUTTON_LAT_0 : BUTTON_LAT_1, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show Cancel button lcd_Font("16B"); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, lcd_max_x - 63, lcd_max_y - 35, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Cancel", BTN_TXTOFFSET, 5, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // wait for button press & release menu_timeout = SEC_TIMER + 60; while( ((button = lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); // handle selection if (button == 256+BTN_NO_OFF) { // update screen *choice=FALSE; } else if (button == 256+BTN_YES_ON) { // update screen *choice=TRUE; } if ((button == BTN_CANCEL) || (button == -1)) return 0; // cancel or timeout else { // update scren to show choice lcd_ButtonDef( BTN_YES_ON, BTN_LAT, // latching operation BTN_TLXY, x1, 80, // starting x,y for buttons BTN_TYPE, *choice ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show optZero choice lcd_ButtonDef( BTN_NO_OFF, BTN_TLXY, x1, 110, // starting x,y for buttons BTN_TYPE, *choice ? BUTTON_LAT_0 : BUTTON_LAT_1, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); msDelay(500); // wait so you can see the choice return 1; // got a choice } } void lcd_helpScreen(char view) { // view 0 - main screen help // 1 - log screen help int button; // Logo splash screen lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); if (param.orientLandscape) lcd_Font("10"); else lcd_Font("13"); // lcd_DispText(param.station_name[SYSTEM_NAME].name, 10, 5, MODE_NORMAL); lcd_DispText("Remote Station - ", 10, 5, MODE_NORMAL); lcd_DispText(FIRMWARE_VERSION, 0, 0, MODE_NORMAL); if (view==0) { // main screen help lcd_DispText("\nTo send a carrier:", 0, 0, MODE_NORMAL); lcd_DispText("\nInsert carrier into tube and close the door", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the send button send it", 0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Menu button for system features", 0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); lcd_DispText("\nHelp Phone Numbers", 0, 0, MODE_NORMAL); lcd_DispText("\nSystem Administrator: ", 0, 0, MODE_NORMAL); // lcd_DispText(param.phoneNum[ADMIN_PHONE], 0, 0, MODE_NORMAL); lcd_DispText("\nMaintenance: ", 0, 0, MODE_NORMAL); // lcd_DispText(param.phoneNum[MAINT_PHONE], 0, 0, MODE_NORMAL); lcd_DispText("\nColombo Pneumatic Tube Systems:\n800-547-2820", 0, 0, MODE_NORMAL); } else if (view==1) { // log screen help lcd_DispText("\nDATE TIME of event start", 0, 0, MODE_NORMAL); lcd_DispText("\nDUR is duration in seconds", 0, 0, MODE_NORMAL); lcd_DispText("\nDIR is direction", 0, 0, MODE_NORMAL); lcd_DispText("\nSTATUS codes", 0, 0, MODE_NORMAL); lcd_DispText("\n 0 = normal status", 0, 0, MODE_NORMAL); lcd_DispText("\n 1 = diverter timeout", 0, 0, MODE_NORMAL); lcd_DispText("\n 2 = carrier exit (lift) timeout", 0, 0, MODE_NORMAL); lcd_DispText("\n 3 = delivery overdue timeout", 0, 0, MODE_NORMAL); lcd_DispText("\n 4 = blower timeout", 0, 0, MODE_NORMAL); lcd_DispText("\n 5 = station not ready or cancel dispatch", 0, 0, MODE_NORMAL); lcd_DispText("\n 6 = transaction cancelled/aborted", 0, 0, MODE_NORMAL); lcd_DispText("\n 64 = Door opened event", 0, 0, MODE_NORMAL); lcd_DispText("\nFLAGS (hexidecimal)", 0, 0, MODE_NORMAL); lcd_DispText("\n xxxx xxx1 = Stat Transaction", 0, 0, MODE_NORMAL); lcd_DispText("\n xxxx xx1x = Carrier return function", 0, 0, MODE_NORMAL); lcd_DispText("\n xxxx x1xx = Auto return activated", 0, 0, MODE_NORMAL); lcd_DispText("\n xxxx 1xxx = Door opened in transaction", 0, 0, MODE_NORMAL); lcd_DispText("\n xxx1 xxxx = Auto return performed", 0, 0, MODE_NORMAL); lcd_DispText("\n xx1x xxxx = Secure transaction", 0, 0, MODE_NORMAL); } // done button lcd_Font("16B"); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TXTOFFSET, 10, 9, BTN_TLXY, lcd_max_x-69, lcd_max_y-40, // starting x,y for buttons BTN_TEXT, "Done", BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // wait for a button press menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); } struct logInfoType { char spare[4]; // available open space for data unsigned long xSF_Head; // Not used unsigned long xSF_Tail; // Not used unsigned long Head; // points to latest entry unsigned long Tail; // points to first entry (if both equal 0 then log is empty) char Ver; char spare2; // available open space for data } logInfo; unsigned long logInfoXaddr; // address to xmem for logInfo unsigned long logXaddr; // address to xmem for data log int SFAvailable; // Indicates if serial flash is available #define XMemLogMax 100 #define SFLogMax 500000 long MaxLogEntries; // maximum number of events in either log #define LOG_VERSION 3 xmem void initTransLog(void) { struct trans_log_type trans; int status; int sf; long memOffset; char sbuf[80]; // allocate the xmem for header and log logInfoXaddr = xalloc(sizeof(logInfo)); // was 10, added 12 more (size of trans) logXaddr = xalloc(XMemLogMax * sizeof(trans)); lcd_Font("16"); // check for and init the serial flash (only in run mode) //// NO SF IN REMOTE: if (OPMODE == 0x80) sf = SF1000Init(); else sf = -3; sf=-3; // FORCE UNUSED if (sf==0) // will use SF instead of XMEM { SFAvailable=TRUE; MaxLogEntries=SFLogMax; lcd_DispText("Using Serial Flash for event log",0,0,MODE_NORMAL); } else { SFAvailable=FALSE; MaxLogEntries=XMemLogMax; lcd_DispText("Using xmem for event log",0,0,MODE_NORMAL); } // get the header to determine head and tail status = xmem2root( &logInfo, logInfoXaddr, sizeof(logInfo)); if (status != 0) { // error reading xmem sprintf(sbuf,"\nError %d initializing transaction log", status); lcd_DispText(sbuf,0,0,MODE_NORMAL); //printf("\nError %d initializing transaction log", status); } // if log version does not match then initialize log if (logInfo.Ver != LOG_VERSION) { // reinit log // start over from scratch logInfo.Tail=0; logInfo.Head=0; lcd_DispText("\nTransaction log reset\n",0,0,MODE_NORMAL); //printf("\nTransaction log reset\n"); // save the logInfo data logInfo.Ver = LOG_VERSION; root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } // make sure head/tail are plausible // either tail=0 and head=0..MaxLogEntries-1 // or tail=1..MaxLogEntries-1 and head=tail-1 else if ((logInfo.Tail<=logInfo.Head) && (logInfo.Head<MaxLogEntries)) { // OK sprintf(sbuf, "\nTrans log contains %ld entries\n", logInfo.Head-logInfo.Tail); lcd_DispText(sbuf,0,0,MODE_NORMAL); } else if ((logInfo.Tail>logInfo.Head) && (logInfo.Tail<MaxLogEntries)) { // OK sprintf(sbuf, "\nTrans log contains %ld entries\n", logInfo.Head + (MaxLogEntries-logInfo.Tail)); lcd_DispText(sbuf,0,0,MODE_NORMAL); } else { // NOT OK so reinitialize head and tail sprintf(sbuf,"\nTrans log reset due to inconsistent tail: %ld and head: %ld\n", logInfo.Tail, logInfo.Head); lcd_DispText(sbuf,0,0,MODE_NORMAL); logInfo.Tail=0; logInfo.Head=0; root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } } void analyzeEventLog() { // Check consistency of entries in the log and reset tail/head if needed // Valid entries have a date/time between 850,000,000 (Dec-2006) and current date/time (+ 1 month) // In case of log wrap-around, the date/time of a previous valid entry is greater than the next valid entry unsigned long lastTransDateTime; unsigned long newTail; unsigned long newHead; unsigned long savedTail; struct trans_log_type trans; long entry; int button; int foundStart; char myline[80]; // line to send to the lcd lastTransDateTime=0; entry=0; newTail=0; // assume for now it will be at the start newHead=0; savedTail=logInfo.Tail; lcd_drawScreen(5, "ANALYZE EVENT LOG"); lcd_Font("8x12"); lcd_DispText("Checking Log Consistency", 10, 50, MODE_NORMAL); sprintf(myline, "\nCurrent first entry %ld", logInfo.Tail); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nCurrent last entry %ld", logInfo.Head); lcd_DispText(myline, 0, 0, MODE_NORMAL); logInfo.Tail=0; // have to set tail to zero to get absolute entry references foundStart=FALSE; // Not yet while (entry < MaxLogEntries) { if (entry%100==0) { // update progress sprintf(myline, "Checking Entry %ld", entry); lcd_DispText(myline, 10, 110, MODE_NORMAL); maintenance(); } getTransaction(entry, &trans); if ((trans.start_tm > 850000000) && (trans.start_tm < SEC_TIMER+2592000)) { // good entry foundStart=TRUE; // is it before or after last entry if (trans.start_tm < lastTransDateTime) { // assume it is wrap around of the log newHead=entry-1; newTail=entry; } entry++; } else { // invalid entry if (foundStart) { // already found a good entry so stop now if (entry>0)newHead=entry; entry=MaxLogEntries+1; } else { // didn't find start yet so keep going entry++; newTail=entry; // Hope we find the start } } } logInfo.Tail=savedTail; // reset saved tail // show last entry checked sprintf(myline, "Checking Entry %ld", MaxLogEntries); lcd_DispText(myline, 10, 110, MODE_NORMAL); // Show new head and tail and ask if it should be retained sprintf(myline, "\nDetected first entry %ld", newTail); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nDetected last entry %ld", newHead); lcd_DispText(myline, 0, 0, MODE_NORMAL); // if it changed then ask if it should be kept if ((logInfo.Tail != newTail) || (logInfo.Head != newHead)) { lcd_DispText("\nAccept Detected Entries?", 0, 0, MODE_NORMAL); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 9, 9, BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TEXT, "Accept", BTN_END ); } else {lcd_DispText("\nEntries are consistent", 0, 0, MODE_NORMAL);} // wait for any button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); // Was Accept button pressed if (button==BTN_CANCEL) { // keep the new entries logInfo.Tail = newTail; logInfo.Head = newHead; // save head/tail back to xmem root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } } // TEMPORARY REMOVE UNTIL CARD SCANNING IS NEEDED /* void addSecureTransaction(struct secure_log_type secTrans) { // map secure trans data into trans log and save // also works for standard card scans struct trans_log_type trans; char extra; // used for station # trans.trans_num = secTrans.trans_num; trans.start_tm = secTrans.start_tm; trans.duration = (secTrans.sid[1] << 8) + secTrans.sid[0]; trans.source_sta = secTrans.sid[2]; trans.dest_sta = secTrans.sid[3]; trans.status = secTrans.status; trans.flags = secTrans.sid[4]; extra = secTrans.flags; // contains the station # if (secTrans.scanType == 2) { trans.status = ESTS_CARD_SCAN; trans.trans_num = transactionCount(); // maybe just temporary sendUDPtransaction(trans, extra); // just send, don't log } else if (secTrans.scanType == 3) { trans.status = ESTS_UNAUTH_CARD; trans.trans_num = transactionCount(); // maybe just temporary sendUDPtransaction(trans, extra); // just send, don't log } else addTransaction(trans, extra); // add to log and send } */ void addTransaction(struct trans_log_type trans, char xtra) { long memOffset; int sf; // Push the transaction into local xmem memOffset = logInfo.Head * sizeof(trans); // if (SFAvailable) // { // write to serial flash // while ( (sf=SF1000Write ( memOffset, &trans, sizeof(trans) )) == -3 ); // } // else // { // write to xmem root2xmem( logXaddr+memOffset, &trans, sizeof(trans)); sf=0; // } if (sf==0) // did we save ok? { // update the log pointers logInfo.Head++; // increment logHead if (logInfo.Head==MaxLogEntries) logInfo.Head=0; // check for wraparound if (logInfo.Head==logInfo.Tail) // check for full log { logInfo.Tail++; // bump the tail if (logInfo.Tail==MaxLogEntries) logInfo.Tail=0; // check for wraparound } } // save head/tail back to xmem root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); printf("\nAdded transaction at %ld with status %d and flags %d\n", SEC_TIMER, (int)trans.status, (int)trans.flags); // now send out the UDP message // sendUDPtransaction( trans, xtra ); } long sizeOfTransLog(void) { // how many entries in the log if ((logInfo.Tail<=logInfo.Head) && (logInfo.Head<MaxLogEntries)) { // OK return logInfo.Head-logInfo.Tail; } else if ((logInfo.Tail>logInfo.Head) && (logInfo.Tail<MaxLogEntries)) { // OK, head before tail return logInfo.Head + (MaxLogEntries-logInfo.Tail); } else return 0; } int getTransaction(long entry, struct trans_log_type *trans) { // returns the n'th entry in the trans log (flash or xmem) // entry can be 0 .. sizeOfLog-1 // return value = 0 if success or 1 if entry non-existant long memOffset; if (entry >= MaxLogEntries) return 1; memOffset = ((logInfo.Tail+entry) % MaxLogEntries) * sizeof(*trans); // if (SFAvailable) SF1000Read ( memOffset, trans, sizeof(*trans)); // else xmem2root( trans, logXaddr+memOffset, sizeof(*trans)); xmem2root( trans, logXaddr+memOffset, sizeof(*trans)); if (entry >= sizeOfTransLog()) return 1; else return 0; } long findTransaction(unsigned long transNum) { // search the trans log for first trans equal to transNum // and return the position in the log as entry // if not found will return 0 long entry; struct trans_log_type log; int found; entry = sizeOfTransLog(); found = 0; while ((entry > 0) && (found == 0)) { // loop backwards to find transNum getTransaction(entry, &log); if (log.trans_num < transNum) { // found one lower, so return entry+1 found=1; entry++; } else { // didn't find it yet, go back one more entry--; } } // either way, return entry return entry; } //#define TRANS_PER_PAGE 14 int TRANS_PER_PAGE; void lcd_showTransactions(char format) { // shows the transaction log on the screen // format = 1 = only show alarms long page; long lastPage; int button; int transPerPage; // count how many pages we can show page=0; TRANS_PER_PAGE = (param.orientLandscape) ? 10 : 14; lastPage = sizeOfTransLog() / TRANS_PER_PAGE; if (format==1) lastPage = 0; lcd_drawScreen(8, "TRANSACTION LOG"); // redraw main screen lcd_showTransPage(page, lastPage, format); button=0; while ((button != BTN_CANCEL) && !secTimeout(menu_timeout)) { maintenance(); button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_PREV: if (page > 0) page--; else page=lastPage; // allow wraparound lcd_showTransPage(page, lastPage, format); break; case BTN_NEXT: if (page < lastPage) page++; else page=0; // allow wraparound lcd_showTransPage(page, lastPage, format); break; case BTN_HELP: lcd_helpScreen(1); lcd_drawScreen(8, "TRANSACTION LOG"); // redraw main screen lcd_showTransPage(page, lastPage, format); break; } } } } void lcd_showTransPage(long page, long lastPage, char format) { // page 0 shows the last transaction int x; int y, dy; long entry; char j; char buf[80]; char UID[UIDLen]; char UIDstr[13]; struct trans_log_type trans; struct tm time; //strcpy(buf, "mm/dd/yy hh:mm:ss sourcesta.. -> destinsta.. sss sec"); entry = sizeOfTransLog() -1 - page * TRANS_PER_PAGE; j=0; y=44; dy=14; x=5; lcd_Font("6x9"); // print header sprintf(buf, "DATE TIME DUR DIR STATUS FLAGS"); lcd_DispText(buf, x, y, MODE_NORMAL); y+=dy; while ( (j < TRANS_PER_PAGE) && (entry >= 0) ) //< sizeOfTransLog())) { if (getTransaction(entry, &trans) == 0) { mktm(&time, trans.start_tm); lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); if (trans.status <= LAST_TRANS_EVENT) { // This is a transaction sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %3d %-3s %2x %2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, // trans.source_sta < SYSTEM_NAME ? param.station_name[trans.source_sta].name : "??", // trans.dest_sta < SYSTEM_NAME ? param.station_name[trans.dest_sta].name : "??", trans.duration, trans.source_sta == DIR_SEND ? "RCV" : "SND", (int) trans.status, (int) trans.flags ); if (trans.status != 0) lcd_BFcolorsB( lcd_RED, lcd_WHITE); // alarm trans colors else if (trans.flags & (FLAG_STAT | FLAG_SECURE)) lcd_BFcolorsD( 0xAA0, 0xFFF); //lcd_BFcolorsB( lcd_YELLOW, lcd_WHITE); // stat trans colors else if (trans.flags & (FLAG_CRETURN | FLAG_ARETURN | FLAG_ARETURNING)) lcd_BFcolorsB( lcd_GREEN, lcd_WHITE); // c.return trans colors //else lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); } else if (trans.status == ESTS_DOOROPEN) { // This is a door open event sprintf(buf, " %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_hour, time.tm_min, time.tm_sec, "DOOR OPEN IN TRANS", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_MAGENTA, lcd_WHITE); } else if (trans.status == ESTS_MANPURGE) { // This is a manual purge event sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "MANUAL PURGE", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); } else if (trans.status == ESTS_AUTOPURGE) { // This is an automatic purge event sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "AUTOMATIC PURGE", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); } else if (trans.status == ESTS_SECURE_REMOVAL) { // This is a secure transaction removal event // sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-11s %-10s %6ld %2x%2x", // time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, // trans.flags < SYSTEM_NAME ? param.station_name[trans.flags].name : "??", // "SECURE ID", // (* (unsigned long*) &trans.duration) - CARDBASE, // (int) trans.status, (int) trans.flags ); UID[0] = (char) trans.duration >> 8; UID[1] = (char) trans.duration && 0xFF; UID[2] = trans.source_sta; UID[3] = trans.dest_sta; UID[4] = trans.flags; UID_Decode(UID, UIDstr); sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-10s %-12s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "SECURE ID", UIDstr); lcd_BFcolorsD( 0xAA0, 0xFFF); } else { // unknown entry type sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "UNKNOWN STATUS", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_GREY, lcd_WHITE); } // Display record unless it is blank or supressed by format if (trans.status != ESTS_BLANK) { if ((format==0) || (trans.status>0 && trans.status<LAST_TRANS_EVENT)) { // ok to show lcd_DispText(buf, x, y, MODE_NORMAL); y+=dy; j++; } } } entry--; } if (j < TRANS_PER_PAGE) { // clear the rest of the work area lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); lcd_Rectangle(1, y, 320, 204, 1); // fill left side progress lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); } lcd_showPage(page+1, lastPage+1); } void lcd_showTransSummary() { // uses structure statistics : system summary statistics char myline[80]; // line to send to the lcd char * instr; // work pointer into myline long subtot; // total of transactions or alarms int button; button=0; while ( (button != BTN_EXIT) && !secTimeout(menu_timeout) ) { lcd_drawScreen(5, "SUMMARY LOG"); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 9, 9, BTN_TLXY, 8, lcd_max_y-40, // starting x,y for buttons BTN_TEXT, "Reset", BTN_END ); lcd_Font("8x12"); lcd_DispText(param.stationName, 10, 50, MODE_NORMAL); lcd_DispText("\nTRANSACTIONS:", 0, 0, MODE_NORMAL); sprintf(myline, "\nIncoming: %ld", statistics.trans_in); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nOutgoing: %ld", statistics.trans_out); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nTotal Transactions: %ld", statistics.trans_in + statistics.trans_out); lcd_DispText(myline, 0, 0, MODE_NORMAL); //sprintf(myline, "\n Grand Total: %ld", transactionCount()); //lcd_DispText(myline, 0, 0, MODE_NORMAL); lcd_DispText("\n\nALARMS", 0, 0, MODE_NORMAL); sprintf(myline, "\nDoor Open During Use: %d", statistics.door_alarm); lcd_DispText(myline, 0, 0, MODE_NORMAL); // sprintf(myline, "\nIncomplete Delivery: %d", statistics.deliv_alarm); // lcd_DispText(myline, 0, 0, MODE_NORMAL); //sprintf(myline, "\nDiverter Timeout: %d", statistics.divert_alarm); //lcd_DispText(myline, 0, 0, MODE_NORMAL); // sprintf(myline, "\nCarrier Lift Timeout: %d", statistics.cic_lift_alarm); // lcd_DispText(myline, 0, 0, MODE_NORMAL); //subtot=statistics.deliv_alarm+statistics.divert_alarm+statistics.cic_lift_alarm; // subtot=statistics.deliv_alarm+statistics.cic_lift_alarm; // sprintf(myline, "\nTotal Alarms: %ld", subtot); // lcd_DispText(myline, 0, 0, MODE_NORMAL); // wait for any button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); if (button==BTN_CANCEL) { // Ask: Are You Sure? lcd_Font("16B"); lcd_BFcolorsB( lcd_LGREY, lcd_LGREY); // unfill color lcd_Rectangle(20, 100, 220, 160, 1); // fill white lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_Rectangle(20, 100, 220, 160, 0); // outline lcd_DispText("Press Reset again to confirm\nor Exit to cancel", 30, 115, MODE_TRANS); menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); if (button==BTN_CANCEL) { // OK to reset resetStatistics(); } else button=0; // don't really exit, just repaint the screen } } } unsigned long transaction_count; static unsigned long transCountXaddr; // physical memory address /*******************************************************/ unsigned long transactionCount() { return transaction_count; } /*******************************************************/ nodebug void incrementCounter() { transaction_count++; //setCountMessage(); root2xmem( transCountXaddr, &transaction_count, 4); //root2xmem( transCountXaddr+4, &statistics, sizeof(statistics)); // also save stats to xmem //syncTransCount(); // send to the slave } /*******************************************************/ void loadTransactionCount() { #GLOBAL_INIT { transCountXaddr = 0; } // allocate xmem if not already done if (transCountXaddr == 0) transCountXaddr = xalloc(32); // Read transaction counter xmem2root( &transaction_count, transCountXaddr, 4); //xmem2root( &statistics, transCountXaddr+4, sizeof(statistics)); // also read stats if (transaction_count < 0 || transaction_count > 10000000) { resetTransactionCount(0); } //setCountMessage(); //syncTransCount(); // send to the slave } /******************************************************************/ void resetTransactionCount(unsigned long value) { transaction_count=value; //setCountMessage(); root2xmem( transCountXaddr, &transaction_count, 4); //syncTransCount(); // send to the slave } void resetStatistics() { // reset system statistics statistics.trans_in=0; statistics.trans_out=0; statistics.deliv_alarm=0; statistics.divert_alarm=0; statistics.cic_lift_alarm=0; statistics.door_alarm=0; } <file_sep>/**************************************************************** MAINSTREAM_MAIN_V4xx.C Purpose: Main station master control program for Pneumatic Tube Control System Works with MAINSTREAM_REMOTE_V3xx. Target: Z-World BL2500 Rabbit Language: Dynamic C 8.x Created: Jun 12, 2006 by <NAME> (C) MS Technology Solutions History: 12-Jun-06 v301 Original version created from UW-PSTS_V228 13-Sep-06 v302 Change logic state of inputs using bank reads 21-Sep-06 v303 Fix menu selection for local diverter (make on/off instead of yes/no) 24-Sep-06 v304 Incorrect order of initialization leading to ram overwriting 25-Sep-06 v305 Set blwrIDLE = 0 for standard blower configuration 04-Oct-06 v306 Implement working system reset function in the menu 22-Oct-06 v307 Further integration of keypad 23-Oct-06 v308 Fix keypad input in menus, replace F1/F2 with +/- 26-Oct-06 v309 Reactivate the use of ArrivalEnable to stop false arrival triggers Show message status of arrival optics 06-Nov-06 v310 Fix missing LED initialization - now using GLOBAL_INIT 12-Dec-06 v311 Preparing for integration of dual-main system General code cleanup, refactoring 08-Jan-07 v312 Bug fixes: slave loop not starting; std trans remains pending 10-Jan-07 v313 Still tweaking. Could not set activeMain off. Separated ALL_DEVICES from availableDevices. Slave device address is now 8. Remotes can use 1-7. 11-Jan-07 v314 Slave not registering as a device or stations 17-Jan-07 v315 Slave messages duplicated as remote messages: Fix -> LAST_STATION = 7 (not 8) Cleaned up diverter processing at the slave (no diverter, always ready) 19-Jan-07 v316 Fix to show actual setting of activeMain 21-Jan-07 v317 Delay communications to eliminate lost packets 24-Jan-07 v318 Still optimizing communications 25-Jan-07 v319 Enable TX control a bit sooner to improve communications HD & slave both known at station 8, so ready/not-ready commands now return devAddr 27-Jan-07 v320 Various improvements while @ Colombo 28-Jan-07 v321 Prevent loss of communication to toggle remote inputs 03-Feb-07 v322 Bug fix with last change 04-Feb-07 v323 Begin color touchscreen integration 09-Feb-07 v324 Ongoing touchscreen development 10-Feb-07 v325 Fix for main to main transfers and other improvements @ Colombo 11-Feb-07 v326 Add main to send station names to slave Consistently show RCV @ activemain message Handle CIC in slave loop Show if slave has a blocked inline optic Blocked optic at head diverter shows as being at head diverter Process arrival alert and apu blower (if installed) even while in setup menu 12-Feb-07 v327 Hold off transaction timeout while door is open Ongoing development of menu using color touch screen 19-Feb-07 v328 Ongoing development of menu using color touch screen 20-Feb-07 v329 Hit the watchdog during touchscreen initialization 25-Feb-07 v330 Release menu items for define stations, edit station names, set clock 26-Feb-07 v331 Minor adjustments, Help->About, cleanup bitmaps, CIC lcd lamp 01-Mar-07 v332 Complete removal of calls to RN1600 keypad/lcd 04-Mar-07 v333 Cleanup of existing functions, add transaction summary to logs Auto Purge to slave added, update message on set active main 05-Mar-07 v334 Allocate extended xmem for transaction logging Basic transaction display 06-Mar-07 v335 Fix for slave entering setup menu in proper mode (std or alarm) 11-Mar-07 v336 Fix Auto-purge message for purging to slave Fix Auto-purge exit to make sure blowers shut off right away Show CIC on screen at slave Slave shows help if state is idle Removed <Cancel> button from main menu. Save is automatic if changes occured. 12-Mar-07 v337 Misc cleanup while at Colombo 13-Mar-07 v338 Change font of summary log Reverse order of transaction log Save statistics to xmem to retain after power reset Allow resetting of statistics from their viewing screen 14-Mar-07 v339 Center RCV @ message Create <Directory> function Add pin / password capability Add lcd backlight saver 19-Mar-07 v340 Show slave phone number in directory Improve slave handling of button presses Put auto-return timer in menu - function not yet implemented Start development of smartPrompt - held off for now due to faulty behavior Auto-exit menu after performing alarm reset Adjust position of waiting for reset message Remove remaining calls to old lcd_print function Increase communication message receive timeout from 50 to 70 msec Don't flash menu update when exiting due to menu timeout Show time units (sec or min) for numeric parameters 25-Mar-07 v341 Fix slave processing of touchscreen buttons Move main arrival beep from operator to admin menu On a door open alarm the alarm sound will be on 2 sec and off 5 27-Mar-07 v342 Invert state of carrier in chamber and arrival optics 31-Mar-07 v343 Revert to original state of cic and arrival Show main station on slave directory Made Directory a large button Implemented STAT and carrier-return buttons on the main screen Flushed the lcd button presses when entering setup mode because slave sometimes cancels out right away 04-Apr-07 v344 Implement editing of phone numbers Reset "RCV @ xxx" message after editing station names Make sure transaction progress bar clears at the end of a transaction On slave startup, if no main communication, send a reset command Mask out unused stations from slave push-to-send Initialize the menu timeout when entering the show directory function 07-Apr-07 v345 Continue improvements to editing phone numbers Showing CIC status on station directory Slave Carrier-return implemented 10-Apr-07 v346 Change C.Return button to Return Don't blank out progress bar after screen is drawn at Final-Command Fix handling of lcd directory buttons to send main-to-main Phone numbers are sent to the slave unit 15-Apr-07 v347 Pass CIC data to slave so it can show CIC on the station directory Pass slave stat button info to main in order to toggle stat on and off 16-Apr-07 v348 Fixed bug with initialization of default station names - affected new controllers only 30-Apr-07 v349 Leave backlight at dim level Move CIC bitmap and rearrange main screen buttons Show STAT button in amber/yellow Fix bug when transaction progress blanks out in CIC area between blower-on and CIC exit Fix bug in edit phone numbers where maintenance incompletely overwrites administrator Implement download of transaction log Put auto-return button on the screen, even if not implemented 14-May-07 v350 Implement download of communication statistics Remove slave main buttons during a transaction Allow purging to slave station from the slave manual purge Show introductory help information using Help button Additional level of confirmation for auto-purge Remove slave buttons during a transaction 21-May-07 v351 Update transaction log to provide future growth Show all events and transaction status on screen and in download 28-May-07 v352 Implement auto-return feature 29-May-07 v353 Log cancelled transactions Bug fix in checking if slave is ready in autoReturnCarrier() Fix slave response timing when removing buttons at start of trans 31-May-07 v354 Initialize slaveAvailable to false to prevent false logic on slave, esp when showing directory Fix auto-return processing for slave request - check was in the wrong place Put additional delay before sending command to sync transaction count 04-Jun-07 v355 Implement redundant incrementing of transaction count at the slave Allow setting of the system config password, but still allow fixed 2321 08-Jun-07 v356 Disable resetting of slave serial port at the end of slaveProcessCommand This may be affecting communications performance MUST MAKE SURE COM IS NOT NEGATIVELY AFFECTED BY THIS CHANGE!!! Fix for slave alarm sometimes not going off after alarm reset Add system name to the heading of transaction log download Remove view-event-log from logs menu item Continuously enable arrival interrupt while waiting for main arrival to fix missed arrivals Add translog flag for door open: had the door open event but not the flag in the transaction log entry Shrink "Page x of y" so it doesn't cover the "Exit" button Allow PageUp and PageDn to wrap around paging on the transaction log Implement 5 minute timeout on manual purge 20-Jun-07 v357 More fun with trying to improve interrupts Eliminate maint and admin menus at the slave 15-Jul-07 v358 Flash inuse for slave when cic and not main stacking Integration of SF1008 serial flash for permanent extended event logging Implement feature for remote alternate address request-to-send, to send to master or slave 22-Jul-07 v359 Allow reset of log head/tail from the checkSerialFlash function 25-Jul-07 v360 Add display of diverter_status when manual purge has diverter timeout 27-Jul-07 v361 Fix missing check for stat button press from slave 06-Aug-07 v362 Block RTS2 inputs when subStaAddressing is off Fix for diverter not setting after SW reload - have to setup diverter mapping after reading parameters 29-Aug-07 v363 IN DEVELOPMENT Make blower type menu selectable (STD or APU) and communicate it to the remote units 27-Oct-07 v364 IN DEVELOPMENT Add point to point capability to run as a single stand-alone controller - Blower at main - One remote station, I/O hard wired to main - No diverter Add secondary blower output to come on 2 seconds after first blower output (multi-stage blower packs) 27-Dec-07 v365 Remove point to point capability Add programmable port mapping in the setup menu Improve sync of parameters with remote devices 15-Mar-08 v366 Implement TCP/IP stack Support for reporting blower errors Reduce blower timeout to 12 seconds so it happens before carrier lift timeout 16-Apr-08 v367 Fix mistake in initBlower: blowerPosition==0 --> blowerPosition()==0 Implement check for blower @ idle before starting a transaction Flash slave light for main if cic at main and no stacking allowed 29-Apr-08 v368 Fix overflow in transaction log page number, change int's to long's 09-Sep-08 v400 Prepare for new gen supporting dedicated remotes, TCP/IP, and swipe cards Add UDP configuration Add system number Add LCD calibration to setup menu 05-Oct-08 v401 Change LCD_GetNumberEntry so that <OK> with no entry is like cancel 18-Oct-08 v402 Add transaction number into log entry, reduced max entries to 500k Change transaction end_tm to duration in seconds 16-Nov-08 v403 Begin setup for handling secure transactions 06-Dec-08 v404 Added handling of secure transaction 18-Dec-08 v405 Added option to enable/disable secure transaction 30-Dec-08 v406 Updates to trans and event log, secure_removal=32 03-Jan-09 v407 Cleanup secure handling eg stacking and messaging 04-Jan-09 v408 Improvements to UDP data log content Don't start a transaction if arrival optic is blocked Fix reach.lib for lost button presses 01-Mar-09 v409 Add menu items for ID card parameters: left 3 digits, right 9 min, max Communicate card parameters to the sub stations Add display of secure pins on station directory 22-Mar-09 v410 Transmit full parameter set over TCP/IP 09-Apr-09 v411 Fix for reset of arrival alerts when carrier not present within X seconds Some stations could have up to a 10 second time window from arrival until CIC 03-May-09 v412 Fix for alarm sound reset 26-May-09 v413 Add date range to log download Change LCD_GetNumberEntry so caller decides if <OK> with no entry is like cancel 30-Jun-09 v414 Improve logging of purge events by saving the purged-to stations Dest_sta contains the first purged-to station and Flags contain bit mask of all purged-to stations 08-Aug-09 v415 Cancel of auto purge needs to turn off the blower Auto purge direction message to be dynamic on configuration 21-Nov-10 v416 Bug fix in using local diverter. Timeout not calculated properly. 26-Mar-11 v417 Implement tube drying mode to run vacuum constant 29-Jul-13 v418 Bug fix in using local diverter. divertersReady() to use flag diverter_attention instead of raw input. 07-Sep-13 v419 Implement dual card range parameter sets 22-Sep-13 v420 Enable use of TCP/IP drivers, add Visual Alert option and take over output 15 from CIC light Changed alert menu text, Added option to disable tube dryer mode, make MainAudibleAlert sticky 12-Dec-13 v421 Force remote arrival alert on if transaction is set for auto-return (like stat does) Include first TCP server request 20-Dec-13 v422 Add individual user identification NOT YET RELEASED 06-Jun-14 v423 Log every card scan 15-Aug-14 v424 Improve com when sending UID's; Set limit to 1100 users *****************************************************************/ #define FIRMWARE_VERSION "Mainstream V4.24" #define VERS 4 #define SUBVERS 24 #define MYDEBUG nodebug #define STDIO_DISABLE_FLOATS #define STDIO_ENABLE_LONG_STRINGS // define PRINT_ON for additional debug printing via printf #define PRINT_ON 1 #define USE_TCPIP 1 #memmap xmem // Required to reduce root memory usage #class auto #use "bl25xx.lib" Controller library #use "rn_cfg_bl25.lib" Configuration library #use "rnet.lib" RabbitNet library #use "rnet_driver.lib" RabbitNet library //#use "rnet_keyif.lib" RN1600 keypad library //#use "rnet_lcdif.lib" RN1600 LCD library // #use "RS232.lib" // setup for serial flash interface on programming port #define SPI_SER_A #define SPI_CLK_DIVISOR 10 #define SF1000_CS_PORT GOCR #define SF1000_CS_PORTSHADOW GOCRShadow #define SF1000_CS_BIT 4 // need to invert the chip select for serial port a #define CS_ENABLE BitWrPortI ( SF1000_CS_PORT, &SF1000_CS_PORTSHADOW, 0, SF1000_CS_BIT );\ SPIxor = 0xFF; // invert the received bits #define CS_DISABLE BitWrPortI ( SF1000_CS_PORT, &SF1000_CS_PORTSHADOW, 1, SF1000_CS_BIT ); #use SF1000.lib // setup for Reach color LCD #define LCD_USE_PORTE // tell Reach library which serial port to use #use Reach101.lib // Setup interrupt handling for carrier arrival input // Set equal to 1 to use fast interrupt in I&D space #define FAST_INTERRUPT 0 char latchCarrierArrival; void my_isr1(); void arrivalEnable(char how); /* Declare data structures */ #define NUMDATA 6 struct iomessage // communications message packet { char devAddr; // device board # char command; // command instruction char station; // carrier station # char data[NUMDATA]; // process data }; struct stats_type // transaction summary statistics { long trans_in; // incoming transactions long trans_out; // outgoing transactions int deliv_alarm; // incomplete delivery timeout alarm int divert_alarm; // diverter timeout alarm int cic_lift_alarm; // carrier lift timeout alarm }; struct trans_log_type // transaction logging info { unsigned long trans_num; // transaction number unsigned long start_tm; // time of departure unsigned int duration; // duration of event in seconds // time of arrival (or alarm) char source_sta; // where it came from char dest_sta; // where it went to char status; // transaction status (0-63) or other event (64-255) // 0 = no malfunction or other transaction status // 1 = diverter timeout // 2 = carrier exit (lift) timeout // 3 = delivery overdue timeout // 4 = blower timeout // 5 = station not ready after setting diverter or cancel dispatch // 6 = transaction cancelled/aborted (future) // 64 = Door opened event char flags; // transaction flags // xxxx xxx1 = Stat Transaction // xxxx xx1x = Carrier return function // xxxx x1xx = Auto return function // xxxx 1xxx = Door opened in transaction // other event flags defined elsewhere // IF TRANSLOG GROWS MAKE SURE UDP COMMAND CAN HOLD IT ALL (NUMUDPDATA) }; struct secure_log_type // transaction logging info for secure ID { // NO LONGER must be identical in size to trans_log_type unsigned long trans_num; // transaction number unsigned long start_tm; // time of departure char sid[5]; char status; // secure removal event = 68 char flags; // transaction flags, probably 0 char scanType; // type of scan (0=none; 1=secure; 2=standard; 3=unauth) }; // define transaction and event logging status and flags #define STS_DIVERTER_TOUT 1 #define STS_DEPART_TOUT 2 #define STS_ARRIVE_TOUT 3 #define STS_BLOWER_TOUT 4 #define STS_TRANS_CANCEL 5 #define STS_CANCEL_BY_SEND 6 #define STS_CANCEL_BY_CIC 7 #define STS_CANCEL_BY_REMOTE 8 #define STS_CANCEL_BY_STACK 9 #define LAST_TRANS_EVENT 31 #define FLAG_STAT 0x01 #define FLAG_CRETURN 0x02 #define FLAG_ARETURN 0x04 #define FLAG_DOOROPEN 0x08 #define FLAG_ARETURNING 0x10 #define FLAG_SECURE 0x20 // define event logging status and flags #define ESTS_DOOROPEN 64 #define EFLAG_MAINDOOR 0x01 #define EFLAG_SUBSDOOR 0x02 #define EFLAG_EXTRA_CIC 0x04 #define ESTS_MANPURGE 65 #define ESTS_AUTOPURGE 66 #define ESTS_SECURE_REMOVAL 32 #define ESTS_CARD_SCAN 33 #define ESTS_BLANK 255 #define NUMUDPDATA 294 struct UDPmessageType // UDP based messages { char device; char devType; // M for main station char command; // can be heartbeat, event, transaction char station; unsigned long timestamp; // MS_TIMER char data[NUMUDPDATA]; }; // Define communications using TCP/IP (UDP) #ifdef USE_TCPIP // #define USE_ETHERNET #define TCPCONFIG 106 #define TCP_MODE_ASCII 1 #define MAX_UDP_SOCKET_BUFFERS 1 #define MAX_TCP_SOCKET_BUFFERS 1 //#define DISABLE_TCP // Not using TCP #define MY_STATIC_IP "192.168.0.9" #define MY_BASE_IP "192.168.0.%d" char myIPaddress[18]; // string to hold runtime IP address #define MY_IP_NETMASK "255.255.255.0" #define LOCAL_PORT 1236 #define REMOTE_IP "192.168.0.101" // web server //#define REMOTE_IP "0.0.0.0" //255.255.255.255" /*broadcast*/ #define REMOTE_PORT 1236 #use "dcrtcp.lib" // #use “http.lib” tcp_Socket tcpsock; char tcpBuffer[1024]; int tcpServerCheck(void); udp_Socket sock; int sendUDPHeartbeat(char sample); int sendUDPcommand(struct UDPmessageType message); void sendUDPtransaction(struct trans_log_type, char xtra); #endif // Including parameter block structure // All parameters here are read to / written from FLASH #define UIDSize 1100 // UIDLen more than 5 is not supported by UID_Send due to command length limit #define UIDLen 5 struct par_block_type { // Define all parameters that are saved in flash // They are r/w by readParameterSettings() and writeParameterSettings() char sysid; char names_init; char stacking_ok[2]; char remoteAudibleAlert; char localDiverter; // local diverter configuration char activeStations; // active station set int autoPurgeTimer; // auto purge timer in seconds int deliveryTimeout; // delivery timeout in seconds char headDiverter; char pw_enabled; char admPassword[5]; // password for administration functions - APPEARS UNUSED struct {char name[12];} station_name[10]; // 0=main; 1-7=remote; 8=slave; 9=system; char slaveController; // master (0) or slave (>0); who am I char activeMain; // master (0) or slave (>0); who is active char adminPassword[5]; // password for administrative functions char maintPassword[5]; // password for maintenance functions char cfgPassword[5]; // password for system config (Colombo only) char phoneNum[11][9]; // phone numbers for stations, admin, maintenance char autoReturnTimer; // how long to wait on unremoved carrier until auto-return char mainAudibleAlert; char manPurgeTimeout; // how long in minutes to run manual purge before timeout - currently fixed / non-settable char subStaAddressing; // If destination addressing by substations is allowed/enabled char blowerType; // standard or APU blower char portMapping[9]; // port map index for remote controllers; array index = remote address char systemNum; // ID for multi-system configurations, also defines IP address char secureEnabled; // If secure transaction feature is enabled char areturn_arrive_alert; // Beep on auto-return // char cardL3Digits; // Constant left 3 digits of valid secure cards // unsigned long cardR9Min; // Secure card ID minimum value for the right 9 digits // unsigned long cardR9Max; // Secure card ID maximum value for the right 9 digits // char card2L3Digits; // Constant left 3 digits of valid secure cards // unsigned long card2R9Min; // Secure card ID minimum value for the right 9 digits // unsigned long card2R9Max; // Secure card ID maximum value for the right 9 digits // char version; // Main version // char subversion; // Main subversion char serverID[20]; // server IP or resolvable name char mainVisualAlert; // enable visual alert at main char enableTubeDryOpt; // enable menu item selection char syncInterval; // how often in minutes to ping server for refresh char cardCheckEnabled; // to enable individual card checking instead of range // -->> BE SURE to change NUMUDPDATA if more parameters are added <<-- // -->> AND BE SURE to reduce reserved[] for every addl parameter above <<-- char reserved[98]; // to separate standard parameters from the user id's unsigned long UIDSync; // timestamp (seconds) since last good block int UIDRecNo; // record number of last sent UID char UID[UIDSize][UIDLen]; } param; #define SYSTEM_NAME 9 // last one is the system name char station_names[12][8]; #define ADMIN_PHONE 9 #define MAINT_PHONE 10 // ------------------------------ // MISCELLANEOUS DEFINITIONS HERE // ------------------------------ char alarm_silenced_flag; char diverter_map[9]; // to assign diverter positions to stations unsigned long diverter_start_time; // these used primarily by diverter functions int diverter_status; unsigned long menu_timeout; char diverter_setting; char diverter_attention; char printlog_active; // whether printout of trans log is enabled char printer_error; // stops printing on printer_wait timeout #define HEADDIVERTERSTATION 0x80 // 8=headdiverter station bit // ------------------------------ // ------------------------------ ////// // RabbitNet Setup //int DevRN1600; // Rabbit Net Device Number Keypad/LCD int DevRN1100; // Rabbit Net Device Number Digital I/O #define OUTCONFIG 0xFFFF //configure outputs to sinking safe state ///// //local macros ///// #define ON 0xFF #define OFF 0x00 #define FLASH 0x01 #define READY 0x01 #define NOT_READY 0xFF // macros for I/O processing functions #define INIT 0 #define RUN 1 #define OPERATE 2 #define TRIGGERED 3 #define RUNNING 4 #define HOLD 5 #define ALL_STATIONS 0xFF // hardware will support 8 stations #define LAST_STATION 7 // # of bits from STATION_SET (DON'T COUNT SLAVE FOR NOW)!!! char STATION_SET; // active stations //char activeStations; // as programmed from the menu char FIRST_DEVADDR; char LAST_DEVADDR; char availableDevices; #define ALL_DEVICES 0xFF #define MAX_DEVADDRS 8 // maximum number of remote devices #define MASTER 0x00 // Station number of the master #define SLAVE 0x08 // Station number of the slave #define SLAVE_b 0x80 // Bit representation #define SLAVE_DEVADDR 8 #define HEADDIV_DEVADDR 7 ////////////////////////// // Master/slave variables & function calls char slaveAvailable; // char slaveData[NUMDATA];// special storage for slave status data char slave_cic, slave_doorClosed, slave_rts, slave_rtncarrier, slave_autoReturn; // char main2mainTrans; // 0=std.trans; DIR_SEND=mast->slave; DIR_RETURN=slave->mast char slaveReturnStatus; char mainStation; char destMain; char main2main_trans; unsigned long lastComTime; char rts_latch; /* Used for latching requestToSend */ char activeMainHere; // ONLY FOR USE IN SETUP MENU MYDEBUG void setActiveMainMsg(void); MYDEBUG void setActiveMain(char setToMaster); MYDEBUG void syncDateAndTime(void); // for master to send clock to slave MYDEBUG void syncTransCount(void); // for master to send transaction count to slave MYDEBUG void displayRemoteMsgs(char * message_num); // for master to send lcd msgs to slave void sendParametersToLogger(void); // to send parameter settings to the data logger void deliverComControl(char *system_state); // for master to hand over com to slave void slaveProcessCommand(struct iomessage message); void slaveProcessIO(void); void slaveProcessState(void); void slaveSyncTransCount(char *p); // for slave to receive transaction count void slaveEnableCommands(void); char slaveGetCommand(struct iomessage *message); void slaveSendResponse(struct iomessage message); char slaveComActive(void); // for slave to know if communication is active void slaveFinishTransaction(void); void initTransLog(void); void downloadTransLog(int numDays); // to local serial port void uploadTransLog(); // to datalog server void addTransaction(struct trans_log_type trans, char xtra); void addSecureTransaction(struct secure_log_type); int getTransaction(long entry, struct trans_log_type *trans); MYDEBUG long sizeOfTransLog(void); void checkSerialFlash(void); void analyzeEventLog(void); /* Serial communications send and receive commands */ #define NAK 0x15 #define ACK 0x06 #define STX 0x02 #define ETX 0x03 #define DINBUFSIZE 63 #define DOUTBUFSIZE 63 #define FINBUFSIZE 63 #define FOUTBUFSIZE 127 /* Remote communication commands */ #define SET_DIVERTER 'A' #define DIVERTER_STATUS 'B' #define REMOTE_PAYLOAD 'C' #define SECURE_REMOVAL 'C' #define ACK_SECURE_REMOVAL 'D' #define RETURN_INPUTS 'E' #define INPUTS_ARE 'E' // set equal to RETURN_INPUTS (v2) #define SET_OUTPUTS 'G' #define CLEAR_OUTPUTS 'H' #define SET_MODE 'I' #define ARE_YOU_READY 'J' #define RETURN_EXTENDED 'K' #define SET_TRANS_COUNT 'L' #define SET_DATE_TIME 'M' #define SET_STATION_NAME 'N' #define CANCEL_PENDING 'O' #define TAKE_COMMAND 'P' #define DISPLAY_MESSAGE 'Q' #define SET_PHONE_NUMS 'R' #define SET_PARAMETERS 'S' #define SET_CARD_PARAMS 'T' #define UID_ADD 'U' #define UID_DEL 'u' #define SYSTEM_EVENT 'V' #define ESECURE_REMOVAL 'W' #define ECARD_SCAN 'w' #define TRANS_COMPLETE 'X' #define RESET 'Y' #define MALFUNCTION 'Z' // Declare constant system timeouts #define DIVERTER_TIMEOUT 30000 // How long to set diverter in msec #define CIC_EXIT_TIMEOUT 15000 // How long for carrier to escape #define MALFUNC_TIMEOUT 30000 // How long in malfunction loop #define STAT_TIMEOUT 60 // Priority reset in seconds #define PASSWORD_TIMEOUT 10000 // Timeout for operator entry /* Declare I/O device indexes */ #define devInUseSolid 0 #define devInUseFlash 1 #define devAlert 2 #define devAlarm 3 char outputvalue[4]; // digital output buffers /* Array index values for remote data returned by INPUTS_ARE command. */ #define REMOTE_CIC 0 #define REMOTE_DOOR 1 #define REMOTE_ARRIVE 2 #define REMOTE_RTS 3 #define REMOTE_RTS2 4 // Digital I/O definitions // INPUTS int readDigInput(char channel); // dio_ON|OFF must be used ONLY in primatives readDigInput and setDigOutput // they reflect the real state of the logic inputs and outputs #define dio_ON 0 #define dio_OFF 1 // Menu/Next button assigned to input I-0 #define di_carrierArrival readDigInput(0) #define di_carrierInChamber readDigInput(1) #define di_doorClosed readDigInput(2) #define di_priorityRequest readDigInput(3) #define di_returnCarrier readDigInput(4) //#define di_pushButton(value) !readDigInput(5+value) //#define di_P2P_carrierArrival readDigInput(5) //#define di_P2P_carrierInChamber readDigInput(6) //#define di_P2P_doorClosed readDigInput(7) //#define di_requestToSend ((~digBankIn(1)) & STATION_SET) #define di_requestToSend ((~digBankIn(1)) & 0xFF) #define di_diverterPos (readDigInput(16) | (readDigInput(17) << 1)) // NEED TO DEFINE INPUT FOR SHIFTER POSITIONS #define di_shifterPosIdle readDigInput(0) #define di_shifterPosPrs readDigInput(0) #define di_shifterPosVac readDigInput(0) MYDEBUG char carrierArrival(char whichMain); // 0=MASTER; 8=SLAVE MYDEBUG char carrierInChamber(char whichMain); MYDEBUG char doorClosed(char whichMain); // OUTPUTS MYDEBUG void setDigOutput(int channel, int value); #define do_shift 0 #define do_closeDoorAlarm(value) setDigOutput(6+do_shift,value) #define do_blowerVac(value) setDigOutput(12+do_shift,value) #define do_blowerPrs(value) setDigOutput(13+do_shift,value) //#define do_blowerALT(value) setDigOutput(9+do_shift,value) #define do_blower(value) setDigOutput(9+do_shift,value) #define do_blowerDly(value) setDigOutput(16+do_shift,value) //#define do_audibleAlert(value) setDigOutput(11+do_shift,value & param.mainAudibleAlert) #define do_audibleAlert(value) setDigOutput(11+do_shift,value) #define do_diverter(value) setDigOutput(8+do_shift,value) //#define do_alarmLight(value) setDigOutput(9+do_shift,value) #define do_alarmSound(value) setDigOutput(10+do_shift,value) #define do_priorityLight(value) setDigOutput(14+do_shift,value) #define do_CICLight(value) ((void)0) #define do_visualAlert(value) setDigOutput(15+do_shift,value) void setAlerts(char how); // sets both audible and visual alerts //#define do_P2P_CICLight(value) setDigOutput(17+do_shift,value) //#define do_P2P_alert(value) setDigOutput(18+do_shift,value) #define beep(value) rn_keyBuzzerAct(DevRN1600, value, 0) MYDEBUG void inUse(char how, char station_b); MYDEBUG void alarm(char how); //void alert(char how, char station_b); MYDEBUG char getKey(void); // Functions for digital input based keys //char functionButton(char which, char how); #define FUNC_BUTT 0x00 #define FUNC_F1 0x01 #define FUNC_F2 0x02 #define FUNC_TRIG 0x01 // triggered (latched) mode #define FUNC_CURR 0x02 // current button state #define FUNC_HELD 0x03 // auto repeat key #define FUNC_DELAY 1000 // auto repeat delay #define FUNC_RATE 100 // auto repeat rate // LCD definitions #define DISPROWS 4 //number of lines in display #define DISPCOLS 16 //number of columns in display MYDEBUG void initializeMessages(void); MYDEBUG void message_add(char lcd, char msg1, char msg2, char how); MYDEBUG void message_del(char lcd, char msg1, char msg2); MYDEBUG void message_show(char how); MYDEBUG void message_refresh(void); MYDEBUG void refresh_dynamic_message(char msg); MYDEBUG void refresh_PIN_message(char msg1, char msg2); void lcd_initialize(void); void lputs(char line, char* msg); void reset_msg_timer(char how); void lcd_print(char lcd, char line, char* message); void lcd_show_cursor(char lcd, char line, char pos); MYDEBUG void setTimeMessages(char message, unsigned long timedate); MYDEBUG void setFlagMessage(char flag); MYDEBUG void setParValueMessage(char MSG_message, unsigned long par_value, char * par_units); void update_cic_door_msgs(void); void maintenance(void); #define EMPTY 255 // empty message #define QUEUESIZE 20 // max number of messages per lcd #define SCROLLTIME 2000 // 2 seconds #define NOW 1 // show message immediately #define NEXT 2 // show message next #define ONESHOT 3 // show message once right now #define ONESHOTA 4 // show message once first of 2 oneshots #define LCDCOUNT 2 // how many lcds connected #define TRANSLCD 0 // Trasaction Status display #define SYSTEMLCD 1 // System Status display /* Define STATIC LCD messages */ #define MSGCOUNT 106 const char * const sysmsg[MSGCOUNT] = { "Insert Carrier and"," Press Send Button", " NEXT TRANSACTION "," STAT PRIORITY ", " LOG TO PRINTER "," LOCAL DIVERTER ", " ENTER PASSWORD "," VERIFY PASSWORD ", " TRANS TIMEOUT "," PLEASE WAIT... ", " SYSTEM ALARM "," SEE MAINTENANCE ", " SETTING DIVERTER "," DOOR OPEN ", "CARRIER IN CHAMBER","DELIVERY UNREMOVED", " DELIVERY OVERDUE "," CARRIER RETURN ", " MANUAL PURGE ","TRANSACTN CANCELED", " NO COMMUNICATION "," FROM DEVICE # ", " WAITING FOR "," SYSTEM CONFIG "," SET TIME & DATE ", " PENDING DELIVERY "," IN ROUTE "," AT HEAD DIVERTER ", " TIMEOUT "," ERROR "," REMOTE STATION "," FUNCTION MODE ", " SET HOURS "," SET MINUTES "," SET SECONDS ", " SET DAY "," SET MONTH "," SET YEAR ", " (+)=UP (-)=DOWN "," (+)=ON (-)=OFF "," AUTO PURGE TIMER ", " BEEP ON ARRIVAL "," SILENCE ALARM "," RESET ALARM ", " SYSTEM RESET "," SYSTEM IS BUSY ", " CAN NOT SEND ","can't send reason ", " empty 3 xxxxxxx "," empty 4 xxxxxxx ", " empty 5 xxxxx "," OPTIC BLOCKED ", " @M ", " @1 "," @2 "," @3 "," @4 ", " @5 "," @6 "," @7 "," @8 ", " <M ", " <1 "," <2 "," <3 "," <4 ", " <5 "," <6 "," <7 "," <8 ", " >M ", " >1 "," >2 "," >3 "," >4 ", " >5 "," >6 "," >7 "," >8 ", "SECURE PIN = #### "," empty 6 xxxxx ", " empty 7 xxxxxxx "," empty 8 xxxxxx "," empty 9 xxxxxx ", " --END OF MENU--- "," NOT READY "," ERROR SAVING ", " STACK AT MAIN "," STACK AT REMOTE "," RESET COUNTER ", " TIME: HR:MN "," DATE: MO/DY/YR "," ", " CURRENTLY Oxx "," MO/DY/YR HR:MN "," DO NOT USE ", " CHECKING SERVER "," PLEASE WAIT ... ", " HEAD DIVERTER "," SETTING BLOWER ", " PARAMETER VALUE "," empty 12 xxxxxxx ", "SECURE TRANSACTION"," SET AS SLAVE "," SET ACTIVE MAIN ", " "}; // last element always blank // Define message indexes into rom or ram messages enum messageIDs { MSG_SDEFAULT = 0, MSG_SDEFAULT2, MSG_STAT, //MSG_STAT2 MSG_LOG2PRINTER = 4, MSG_LOCALDIVERTER, MSG_ENTERPW, // no 7 MSG_SET_TIMEOUT = 8, MSG_WAIT, MSG_ALARM, // no 11 MSG_SETTING = 12, MSG_DROPEN, MSG_CIC, MSG_ARVALRT, MSG_ODUE, MSG_RTRN, MSG_PURGE, // no 19 MSG_NOCOMM = 20, // no 21,22 MSG_SYS_CONFIG = 23, MSG_SET_CLOCK, MSG_PENDING, MSG_INROUTE, MSG_AT_HEADDIV, MSG_TIMEOUT, MSG_ERROR, MSG_REMOTESTA, MSG_FUNCTION, MSG_SET_HOURS, // no 33-37 MSG_INC_DEC = 38, MSG_ON_OFF, MSG_APURGE_TIMER, MSG_ARRIVE_SND, MSG_ALARM_SND, MSG_ALARM_RESET, MSG_RESET, MSG_SYSBUSY, MSG_CANT_SEND, MSG_CANT_WHY, MSG_empty3_xxx, MSG_empty4_xxx, MSG_empty5_xxx, MSG_OPTIC_BLOCKED, MSG_AT, // points to message before station 1 // no 53-60 MSG_FROM = 61, // .. // no 62-69 MSG_TO = 70, // .. // no 71-78 MSG_PIN = 79, MSG_empty6_xxx, MSG_empty7_xxx, MSG_empty8_xxx, MSG_empty9_xxx, MSG_END_OF_MENU, MSG_NOT_READY, MSG_SAVE_ERROR, MSG_MSTACKING, MSG_RSTACKING, MSG_RESET_COUNT, MSG_TIME, MSG_DATE, MSG_TRANS_COUNT, MSG_FLAG_SET, // on/off flag setting MSG_DATE_TIME, MSG_DONTUSE, MSG_CHECKING_SERVER1, MSG_CHECKING_SERVER2, MSG_HEADDIVERTER, MSG_BLOWER, MSG_PAR_VALUE, MSG_empty12_xxx, MSG_SECURE, MSG_SETASSLAVE, MSG_SETACTIVEMAIN, MSG_BLANK // always the last message }; #define MSG_TDEFAULT MSG_DATE_TIME #define MSG_TDEFAULT2 MSG_TRANS_COUNT // Define structure and array for variable type messages // message length is 16 or 20 (18?) (+1 for null terminator \n) #define MSG_LEN 18 // Define leader offset into messages (0 for 16 char lcd, 2 for 20 char lcd) #define MSG_OFFSET 1 struct msgbuftype {char msg[MSG_LEN+1];} sys_message[MSGCOUNT]; // Diagnostic Menu/Setup/Parameters function definitions //void displayFunctionMessage(char mnu_base, char msg_item, char msg_value); char functionSetTime(char what_timer, char index, unsigned long *time_val); char functionSetParValue(char menu_item, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units); char functionDefineStations(void); MYDEBUG int readParameterSettings(void); MYDEBUG int writeParameterSettings(void); MYDEBUG int syncParametersToRemote(void); // USER ID MANAGEMENT DEFINITIONS int UID_Add(char *ID); int UID_Del(char *ID); int UID_Search(char *ID); int UID_Get(int UIndex); int UID_Send(char *ID, char how); unsigned int UID_Cksum(); int UID_Decode(char *UID, char *Result); int UID_Encode(char *UID, char *Result); int UID_Parse(char *UIDBuffer); int UID_ResyncAll(void); int UID_Not_Zero(char *UID); void UID_Clear(char *UID); void UID_Copy(char *Udest, char *Usrc); unsigned long cvtTime(char *timestring, char setRTC); unsigned long pingTimer; int Sync_Clock(char *Buffer); void Param_Flash_Write(char command); int UID_GetAddOnly; // General/Misc definitions char init_communication(void); void print_comstats(void); MYDEBUG void showactivity(void); MYDEBUG void msDelay(unsigned int delay); MYDEBUG char secTimeout(unsigned long ttime); MYDEBUG char Timeout(unsigned long start_time, unsigned long duration); MYDEBUG void toggleLED(char LEDDev); MYDEBUG void initialize_system(void); MYDEBUG char bit2station(char station_b); MYDEBUG char station2bit(char station); MYDEBUG char firstBit(char bitdata); //void diverter(char how); MYDEBUG void set_diverter(char station); MYDEBUG void check_diverter(void); MYDEBUG char divertersReady(char station, char headDiverter, char mainDiverter); MYDEBUG void setDiverterConfiguration(void); MYDEBUG char valid_send_request(char station_b); // transaction request queue functions USE BIT VALUES MYDEBUG void queueAdd(char source, char dest); // adds request to queue MYDEBUG void queueDel(char source, char dest); // deletes request from queue MYDEBUG void queueNext(char *source, char *dest); // returns next queue entry MYDEBUG char queueVerify(char cic_data, char door_data); // validate queue entries char send_n_get(struct iomessage message, struct iomessage *response); char send_command(struct iomessage); char get_response(struct iomessage *); MYDEBUG void incrementCounter(void); MYDEBUG void reset_statistics(void); MYDEBUG void buildStationNames(void); //void initializeMessages(void); unsigned long transactionCount(void); MYDEBUG void loadTransactionCount(void); MYDEBUG void resetTransactionCount(unsigned long value); MYDEBUG void resetStatistics(void); MYDEBUG void show_extended_data(void); char extendedData[9][4]; // Extended remote data, devices 0-8 void purgeSystem(char purge_mode); #define PURGE_MANUAL 0 #define PURGE_AUTOMATIC 1 #define PURGE_DRYING 2 void exercise_outputs(void); void show_comm_status(void); void show_comm_test(char wait); void show_ip_address(void); void checkRemoteConfiguration(void); // PRINTER FUNCTIONS //void print_line(char *buf); //void printer_wait(void); //void print_transaction(struct trans_log_type log); //void print_summary(struct stats_type stats, char how); //void print_malfunction(struct trans_log_type log); void print_event(char *event); long nextAutoPrint; //void reset_printer(void); //void check_auto_report(struct stats_type stats); //void reset_auto_print(void); void time2string(unsigned long time, char *buf, int format); void lcd_splashScreen(char view); void lcd_helpScreen(char view); void lcd_drawScreen(char whichScreen, char *title); void lcd_displayMsgs(char * message_num); // to show msgs on touch screen void lcd_resetMsgBackColor(void); void lcd_printMessage(char line, char * msg); void lcd_processTouchScreen(int button); void lcd_enterSetupMode(char operatorLevel); void lcd_ShowTransactionProgress(char source, char dest, char direction, int progress, unsigned long transTimer); int lcd_SelectChoice(char *choice, char *label, char *optZero, char *optOne); char lcd_GetNumberEntry(char *description, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units, char max_digits, char nc_as_ok); char lcd_enableAdvancedFeatures(char menu_level, char * description); char lcd_getPin(char *PIN, char *description); int lcd_Center(char * string, char font); void lcd_clearMiddle(void); void lcd_ShowKeypad(char opts); void lcd_drawKeyboard(void); char lcd_editStationNames(void); char lcd_editServerName(void); char lcd_editPhoneNums(void); char lcd_editPortMapping(char * title); void lcd_showCIC(char forceit); void lcd_setClock(void); char lcd_defineActiveStations(void); void lcd_showTransSummary(void); void lcd_showDirectory(char mode); void lcd_showPage(long thisPage, long lastPage); void lcd_showTransPage(long page, long lastPage, char format); void lcd_showTransactions(char format); void lcd_show_inputs(void); char lcd_sendTo(void); char lcd_returnCarrier(void); char lcd_autoReturn(void); //void lcd_screenSaver(char brightness); //void lcd_smartPrompt(char promptNum); char * ltrim(char * text); char echoLcdToTouchscreen; // to control echo of lcd messages to the touch screen #define lcd_NO_BUTTONS "" #define lcd_WITH_BUTTONS " " #define LCD_DIM 0 #define LCD_BRIGHT 4 #define BMP_COLOMBO_LOGO 1 #define BMP_green_light 2 #define BMP_red_light 3 #define BMP_check_box 4 #define BMP_check_box_click 5 #define BMP_button_on 6 #define BMP_button_off 7 #define BMP_button_up 8 #define BMP_button_dn 9 #define BMP_input_box 10 #define BMP_med_button 11 #define BMP_med_button_dn 12 #define BMP_long_button 13 #define BMP_long_button_dn 14 #define BMP_92x32_button 15 #define BMP_92x32_button_dn 16 #define BMP_med_red_button 17 #define BMP_med_red_button_dn 18 #define BMP_med_grn_button 19 #define BMP_med_grn_button_dn 20 #define BMP_92x40_button 21 #define BMP_92x40_button_dn 22 #define BMP_med_yel_button 23 #define BMP_med_yel_button_dn 24 #define BMP_ltgrey_light 25 #define BTN_MENU 1 #define BTN_DIRECTORY 2 //#define BTN_HELP 3 #define BTN_STAT 4 #define BTN_CRETURN 5 #define BTN_ARETURN 6 #define BTN_SECURE 7 #define BTN_FUTURE 8 #define BTN_OK 10 #define BTN_CANCEL 11 #define BTN_SAVE 12 #define BTN_PREV 13 #define BTN_NEXT 14 #define BTN_HELP 15 #define BTN_YES_ON 16 #define BTN_NO_OFF 17 #define BTN_DEL 18 #define BTN_EXIT 19 #define BTN_MNU_FIRST 21 // State Processing definitions void processSystemIO(void); //char processKeyInput(void); MYDEBUG void processCycleTime(void); void processMainArrivalAlert(void); void processStatPriority(void); //void processOutputLamps(char olOperation); char checkDoorWhileRunning(char calling_state); /* Declare system states */ #define IDLE_STATE 0x01 #define PREPARE_SEND 0x02 #define WAIT_FOR_DIVERTERS 0x03 #define BEGIN_SEND 0x04 #define WAIT_FOR_MAIN_DEPART 0x05 #define WAIT_FOR_REM_ARRIVE 0x06 #define HOLD_TRANSACTION 0x07 #define WAIT_FOR_REM_DEPART 0x08 #define WAIT_FOR_MAIN_ARRIVE 0x09 #define WAIT_FOR_HEADDIVERTER 0x0A #define SHIFT_HEADDIVERTER 0x0B #define CANCEL_STATE 0x0C #define MALFUNCTION_STATE 0x0D #define FINAL_COMMAND 0x0E #define DIR_SEND 1 #define DIR_RETURN 2 // Declare blower interfaces #define blwrType_STD 1 #define blwrType_APU 2 #define blwrOFF 0 // in standard blower systems blwrIDLE and blwrOFF are both 0 = OFF. // in APU blower systems blwrIDLE is 1 #define blwrIDLE 1 #define blwrVAC 2 #define blwrPRS 3 char blwrConfig; // later to become parameter from eeprom char blwrError; char remoteBlwrPos; void blower(char blowerOperatingValue); // use blwrOFF, blwrIDLE, blwrVAC, blwrPRS char processBlower(void); char blowerPosition(void); void initBlower(void); char blowerReady(void); // Blower state is based on system_state -> [system_state][blwrConfig] // blwrConfig is either standard straight through system (0) or head-diverter (1) // independent of blower type standard or APU const char blowerStateTable[15][2] = { blwrOFF, blwrOFF, // Undefined state 0 blwrIDLE, blwrIDLE, // 0x01 (Idle) blwrIDLE, blwrIDLE, // 0x02 blwrIDLE, blwrIDLE, // 0x03 blwrIDLE, blwrIDLE, // 0x04 blwrPRS, blwrVAC, // 0x05 (Main departure) blwrPRS, blwrPRS, // 0x06 (Remote arrival) blwrIDLE, blwrIDLE, // 0x07 blwrVAC, blwrVAC, // 0x08 (Remote departure) blwrVAC, blwrPRS, // 0x09 (Main arrival) blwrIDLE, blwrVAC, // 0x0A (Wait for headdiverter) blwrIDLE, blwrIDLE, // 0x0B blwrIDLE, blwrIDLE, // 0x0C blwrOFF, blwrOFF, // 0x0D blwrIDLE, blwrIDLE };// 0x0E // Globals, system parameters, variables for process state information char op_mode, saved_state; unsigned long arrival_time; unsigned long state_timer; char diagnostic_mode; char system_state, systemStation, systemStationb, malfunctionActive; char statTrans, system_direction, memory_state; char secureTrans, autoRtnTrans; int securePIN[10]; // 0=in_process; 1-7=station; 8=slave // offset to get printed card id number #define CARDBASE 0xE8777C00 // offsets to handle whole 38 bits #define CARDHBOFFSET 119 #define CARDLBOFFSET 3676144640 struct secure_log_type secureTransLog[10]; char secureAck; char checkSecureRemoval(void); char btnStatFlag; char btnSecureFlag; char btnAReturnFlag; char arrival_from; char arrival_alert; // flag to track unremoved deliveries unsigned long autoReturnTime[10]; // timers for handling auto-return feature unsigned long arrivalTime[10]; // timers for when remote arrivals occur char autoReturnCarrier(void); // function to determine if an auto-return is ready to go unsigned long main_arrival; unsigned long slave_arrival; unsigned long stat_expire; static struct stats_type statistics; void main() { //char mybuf[13]; /* Declare local variables */ struct iomessage testcmd, testrsp; unsigned long testtime, t1, t2, comfail; char i; char tcpHeartBeat; char * genptr; auto rn_search newdev; int status; unsigned long lastHeartBeat; //unsigned long TCPCheckTimer; tcpHeartBeat=0; // Initialize the controller brdInit(); // Initialize the controller rn_init(RN_PORTS, 1); // Initialize controller RN ports // Verify that the Rabbitnet boards are connected newdev.flags = RN_MATCH_PRDID; newdev.productid = RN1100; if ((DevRN1100 = rn_find(&newdev)) == -1) { printf("\n no RN1100 found\n"); } else status = rn_digOutConfig(DevRN1100, OUTCONFIG); //configure safe state // show startup screen lcd_splashScreen(0); // allocate xmem for transaction log initTransLog(); hitwd(); // "hit" the watchdog timer /* Initialize digital outputs */ inUse(OFF, ALL_STATIONS); setAlerts(OFF); alarm(OFF); initBlower(); init_communication(); // Initialize serial communications /* Initialize LCD displays */ hitwd(); //lcd_initialize(); //lcd_splashScreen(0); //lcd_print(TRANSLCD, 0, FIRMWARE_VERSION); //lcd_print(TRANSLCD, 1, "PLEASE WAIT... "); hitwd(); // Initialize other system configuration initialize_system(); initializeMessages(); // Initialize dynamic (RAM) messages loadTransactionCount(); // Read transaction counter from EEPROM setDiverterConfiguration(); // setup diverter mappings. #ifdef USE_TCPIP // move sock_init up here to avoid unexpected interrupt from calling tcp_tick before sock_init if(sock_init()) printf("IP sock_init() failed\n"); // Initialize UDP communications #endif /* Exercise all lighted outputs except on watchdog reset */ // if (!wderror()) if (1) // don't have way to check if reset was by watchdog { // show missing H/W on LCD if (DevRN1100 == -1) { //lcd_print(1, 0, "NO RN1100 FOUND... "); lcd_DispText("NO RN1100 DETECTED\n",0, 0, MODE_NORMAL); //msDelay(1000); } // Perform bulb check lcd_DispText("Indicator Check\n",0, 0, MODE_NORMAL); exercise_outputs(); if (param.slaveController == 0) { checkRemoteConfiguration(); // how many remotes, etc. // get and show extended data testcmd.devAddr=ALL_DEVICES; testcmd.command=RETURN_EXTENDED; testcmd.station=0; testcmd.data[0]=0; testcmd.data[1]=0; testcmd.data[2]=0; send_n_get(testcmd, &testrsp); // Show extended data show_extended_data(); hitwd(); // send message for 3 seconds and show statistics testcmd.command=RETURN_INPUTS; for (i=0; i<3; i++) { hitwd(); testtime=MS_TIMER; while (MS_TIMER-testtime < 1000) { msDelay(7); send_n_get(testcmd, &testrsp); } } show_comm_test(0); // don't wait syncDateAndTime(); // put the clock out on the com bus if (syncParametersToRemote()) { lcd_DispText("REMOTES NOT SYNC'D",0, 0, MODE_REV); msDelay(800); } sendParametersToLogger(); // send to logger if (slaveAvailable) setActiveMain(ON); // default to receive here } else { // what to do for slave startup system_state=IDLE_STATE; STATION_SET = 0; // incoming commands will set this up setActiveMain(OFF); // default to not receive here } // setActiveMainMsg(); // enable or disable active main message } else { //lcd_print(SYSTEMLCD, 0, " SYSTEM RESET "); //lcd_print(SYSTEMLCD, 1, "WATCHDOG TIMEOUT "); //msDelay(3000); } // setup interrupt handler for arrival optics #if __SEPARATE_INST_DATA__ && FAST_INTERRUPT interrupt_vector ext1_intvec my_isr1; #else SetVectExtern3000(1, my_isr1); // re-setup ISR's to show example of retrieving ISR address using GetVectExtern3000 //SetVectExtern3000(1, GetVectExtern3000(1)); #endif arrivalEnable(OFF); // disable interrupt and clear latch #ifdef USE_TCPIP // setup default static IP using THIS_DEVICE (myIPaddress = MY_BASE_IP + THIS_DEVICE) sprintf(myIPaddress, MY_BASE_IP, param.systemNum); //printf("My static IP address: %s\n", myIPaddress); // configure the interface //if(sock_init()) printf("IP sock_init() failed\n"); // Initialize UDP communications ifconfig(IF_ETH0, IFS_DHCP, 1, IFS_IPADDR,aton(myIPaddress), IFS_NETMASK,aton(MY_IP_NETMASK), IFS_DHCP_FALLBACK, 1, IFS_UP, IFS_END); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); //lcd_print(1, 0, "No IP Communications"); msDelay(1000); } // wait a little till the interface is up while (!ifstatus(IF_ETH0)) {tcp_tick(NULL); msDelay(100); printf("-"); } // setup timer to poll server //TCPCheckTimer = SEC_TIMER; #endif // Setup standard display of color touchscreen lcd_drawScreen(1,lcd_WITH_BUTTONS); message_del(0, EMPTY, EMPTY); // initialize both lcd queues /* BEGIN MAIN LOOP */ if (param.slaveController==0) { while(1) { maintenance(); // watchdog, led activity, UDP commands, inUse lights //rn_keyProcess(DevRN1600, 0); // process keypad device showactivity(); // flashes the board led show_comm_status(); // update lcd with comm status // process touch buttons before updating lcd display lcd_processTouchScreen(-2); // get a new button press message_show(NEXT); // show next message in queue processSystemIO(); // check system processes if (SEC_TIMER != lastHeartBeat) { // Send a tcp heartbeat once per second sendUDPHeartbeat(tcpHeartBeat++); lastHeartBeat = SEC_TIMER; } } } else // SLAVE MAIN LOOP { slaveEnableCommands(); while(1) { maintenance(); // watchdog, led activity, UDP commands, inUse lights //rn_keyProcess(DevRN1600, 0); // process keypad device showactivity(); // flashes the board led slaveProcessIO(); } } } nodebug root interrupt void my_isr1() { latchCarrierArrival=TRUE; // never deactivate the interrupt during the service routine //WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 } void arrivalEnable(char how) { // should call this routine once to enable interrupt and once to disable latchCarrierArrival=FALSE; // clear existing latch if (how) { //outport(ITC,(inport(ITC))|0x02); // enable INT1 //WrPortI(I1CR, &I1CRShadow, 0x09); // enable external INT1 on PE1, rising edge, priority 1 WrPortI(I1CR, &I1CRShadow, 0x0E); // enable external INT1 on PE1, rising and falling edge, priority 2 } else { //outport(ITC,(inport(ITC))&~0x02); // disable INT1 WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 } } void initialize_system() { // Setup system i/o processing routine char i; if ( readParameterSettings() != 0) { //lcd_print(1, 0, "ERROR READING PARAMS"); lcd_DispText("ERROR LOADING PARAMETERS",0, 0, MODE_NORMAL); //msDelay(800); } // data type mismatch, force two parameters to char param.deliveryTimeout &= 0xFF; param.autoPurgeTimer &= 0xFF; // make sure systemNum is valid if (param.systemNum > 20) param.systemNum=1; // default to 1 //param.version = VERS; //param.subversion = SUBVERS; // Set default for 2nd card range if not yet initialized // if (param.card2L3Digits == 255) // { param.card2L3Digits = 155; // param.card2R9Min = 437355717; // param.card2R9Max = 437357715; // } // setup other globals if (param.syncInterval > 0) pingTimer = SEC_TIMER + (60 * (int)param.syncInterval); // timer for sync with server else pingTimer = 0xFFFFFFFF; // Never statTrans=0; autoRtnTrans=0; secureTrans=0; slaveAvailable = FALSE; // ASSUME NOT btnStatFlag=0; btnSecureFlag=0; btnAReturnFlag=0; for (i=0; i<4; i++) { outputvalue[i]=0; } // clear expansion bus output buffers arrival_alert=0; for (i=0; i<10; i++) { autoReturnTime[i]=0; arrivalTime[i]=0; } // initialize auto-return, arrival timers main_arrival=0; arrival_from=0; systemStation=0; systemStationb=0; //param.mainAudibleAlert=TRUE; make sticky v4.20 alarm_silenced_flag=FALSE; malfunctionActive=FALSE; echoLcdToTouchscreen=TRUE; latchCarrierArrival=FALSE; // clear latch param.manPurgeTimeout = 5; // fixed at 5 minutes reset_statistics(); queueDel(0,0); // initialize request queue for (i=0; i<NUMDATA; i++) slaveData[i]=0; // init slave i/o // check headdiverter configuration and make sure it is valid if ((param.headDiverter != TRUE) && (param.headDiverter != FALSE)) param.headDiverter=FALSE; if (param.headDiverter) param.activeStations |= 0x80; // station 8 programmed by headdiverter setting STATION_SET = param.activeStations; // check sub station addressing to make sure it is valid if (param.subStaAddressing != TRUE) param.subStaAddressing=FALSE; // make sure passwords are valid (4 digits, trailing null) for (i=0; i<4; i++) { if ((param.adminPassword[i] < '0') || (param.adminPassword[i] > '9')) param.adminPassword[0]=0; // reset pw if ((param.maintPassword[i] < '0') || (param.maintPassword[i] > '9')) param.maintPassword[0]=0; // reset pw if ((param.cfgPassword[i] < '0') || (param.cfgPassword[i] > '9')) strcpy(param.cfgPassword, "<PASSWORD>"); // reset pw } // make sure phone numbers are valid for (i=0; i<11; i++) { if (strlen(param.phoneNum[i]) > 9) param.phoneNum[i][0]=0; } // setup transaction count message setParValueMessage(MSG_TRANS_COUNT, transactionCount(), ""); // init variables for secure transactions secureAck=0; for (i=0; i<10; i++) { UID_Clear(secureTransLog[i].sid); secureTransLog[i].start_tm=0; secureTransLog[i].scanType=0; securePIN[i]=-1; } param.UIDRecNo = 0; // initially no limit on UID record paging Param_Flash_Write(1); // reset timer UID_GetAddOnly = 0; // ok to accept deletes } void processCycleTime() { // calculate and display cycle time statistics #define CYCLETIME_UPDATE 2000 static int ct_min, ct_avg, ct_max; static int ct_loops; static unsigned long cycle_start; static unsigned long ct_last; unsigned long cycle_time; if (MS_TIMER - cycle_start >= CYCLETIME_UPDATE) { if (ct_loops > 0) ct_avg = (int)((MS_TIMER - cycle_start) / ct_loops); printf("\n n=%d min=%d avg=%d max=%d", ct_loops, ct_min, ct_avg, ct_max); ct_max=0; ct_min=32767; ct_loops=0; cycle_start=MS_TIMER; print_comstats(); } else { cycle_time = MS_TIMER - ct_last; ct_loops = ct_loops + 1; if (cycle_time > ct_max) ct_max = (int)cycle_time; if (cycle_time < ct_min) ct_min = (int)cycle_time; } ct_last = MS_TIMER; } char remote_data[5]; // event log is modified in multiple modules so make global struct trans_log_type eventlog; void processSystemIO() { struct iomessage command, response, xtended; static struct iomessage finalcmd; char received, k, kbit, XtraCic, FirstXtraCic; static char new_state; static char systemStartup; char func, menu_item, func_mode; static char first_time_here; static char lcd_is_bright; char tempData; //char remote_data[4]; static struct trans_log_type translog; // int safetyStatus; static unsigned long auto_purge_timer; static unsigned long lastComTimer; static int transProgress; static unsigned long doorOpenTimer; // How long door is open during a transaction in seconds char key; char mainFlashAtSlave; char prev_arrival_alert; // setup structure for handling transaction types and info lookup enum TRANTYPES { TT_NONE = 0, TT_MAIN2REMOTE, TT_REMOTE2MAIN, TT_SLAVE2REMOTE, TT_REMOTE2SLAVE, TT_MAIN2SLAVE, TT_SLAVE2MAIN }; enum TRANSINFOS { TT_MAINSTATION = 0, TT_MAIN2MAIN_TRANS, TT_SYSTEM_DIRECTION, TT_FROM, // For head diverter alignment TT_TO // For head diverter alignment }; enum TRANSLOCS { TT_MAIN = 1, TT_REMOTE, TT_SLAVE }; static char transactionType; // create lookup table for transaction parameters static const char transTypeInfo[7][5] = { // mainStation, main2main_trans, system_direction, from, to 0, 0, 0, 0, 0, // NONE MASTER, 0, DIR_SEND, TT_MAIN, TT_REMOTE, // MAIN TO REMOTE MASTER, 0, DIR_RETURN, TT_REMOTE, TT_MAIN, // REMOTE TO MAIN SLAVE, 0, DIR_SEND, TT_SLAVE, TT_REMOTE, // SLAVE TO REMOTE SLAVE, 0, DIR_RETURN, TT_REMOTE, TT_SLAVE, // REMOTE TO SLAVE MASTER, DIR_SEND, DIR_SEND, TT_MAIN, TT_SLAVE, // MAIN TO SLAVE SLAVE, DIR_RETURN, DIR_SEND, TT_SLAVE, TT_MAIN }; // SLAVE TO MAIN #GLOBAL_INIT { first_time_here = TRUE; system_state=CANCEL_STATE; new_state=system_state; state_timer=MS_TIMER; lastComTimer=0; transProgress=101; // handle CIC only; use 999 to clear the area systemStartup=TRUE; // resets after getting through FINAL_COMMAND lcd_is_bright=TRUE; remote_data[REMOTE_CIC]=0; // clear out because slave will use it and it may not be initialized } // First process items always needing attention check_diverter(); // processBlower(); NOW HANDLED IN maintenance() processCycleTime(); //processMainArrivalAlert(); NOW HANDLED IN maintenance() // check for secure removals checkSecureRemoval(); if (secureAck) { // send message to remotes to acknowledge secure id received command.devAddr=ALL_DEVICES; command.command=ACK_SECURE_REMOVAL; command.data[0]=secureAck; if (send_command(command)) secureAck = 0; } lcd_ShowTransactionProgress(mainStation, systemStation, system_direction, transProgress, SEC_TIMER-translog.start_tm); key = getKey(); // processKeyInput(); // Handle STAT processing processStatPriority(); // if main door open, add message, else del. if ( di_doorClosed ) { message_del(TRANSLCD, MSG_DROPEN, MSG_AT); } else { message_add(TRANSLCD, MSG_DROPEN, MSG_AT, NEXT); } // show carrier in chamber if ( di_carrierInChamber ) { //message_add(SYSTEMLCD, MSG_CIC, MSG_AT, NEXT); message_add(TRANSLCD, MSG_CIC, MSG_AT, NEXT); // and check to flash light 8 at slave if main has CIC if (param.stacking_ok[0]) mainFlashAtSlave=0; else mainFlashAtSlave=SLAVE_b; } else { //message_del(SYSTEMLCD, MSG_CIC, MSG_AT); message_del(TRANSLCD, MSG_CIC, MSG_AT); message_del(TRANSLCD, MSG_CANT_SEND, MSG_CANT_WHY); // no CIC, no reason mainFlashAtSlave=0; } // Also handle CIC and Door messages in the TRANSLCD // IF YOU DELETE NEXT LINE THEN REMOVE THE FUNCTION // update_cic_door_msgs(); // show if arrival optic is blocked if ( di_carrierArrival && (system_state==IDLE_STATE) ) message_add(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT, NEXT); else message_del(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT); // DON'T RUN COMMUNICATIONS ANY MORE THAN THE BUS CAN HANDLE if (MS_TIMER - lastComTime > 10) { lastComTime = MS_TIMER; // P2P WORK TO BE DONE HERE // Check some remote inputs ... sends some data also command.devAddr=ALL_DEVICES; command.command=RETURN_INPUTS; if (param.subStaAddressing) command.station=mainStation; else command.station=param.activeMain; // send the main arrival state to indicate not ready for transaction if (main_arrival || slave_arrival) command.data[0]=arrival_from; else command.data[0]=0; // send the system_state (for headdiverter controller to operate blower) command.data[1]=system_state; command.data[2]=outputvalue[devInUseSolid] & ~mainFlashAtSlave; // was system_direction; command.data[3]=(outputvalue[devInUseFlash] & ~SLAVE_b) | mainFlashAtSlave; command.data[4]=STATION_SET; if (send_n_get(command, &response)) { if (response.command==INPUTS_ARE) { // store remote response in local var for (k=0; k<5; k++) { tempData = response.data[k]; tempData &= response.station; // Turn off unused bits remote_data[k] |= (tempData & response.station); // ON Bits remote_data[k] &= ~(tempData ^ response.station); // OFF bits } // force unused doors closed (on) and other unused inputs off remote_data[REMOTE_DOOR] |= ~STATION_SET; remote_data[REMOTE_CIC] &= STATION_SET; remote_data[REMOTE_RTS] &= STATION_SET; remote_data[REMOTE_ARRIVE] &= STATION_SET; if (param.subStaAddressing && slaveAvailable) remote_data[REMOTE_RTS2] &= STATION_SET; else remote_data[REMOTE_RTS2] = 0; // store slave response in local vars if (slaveAvailable) { if (slaveData[0] & 0x01) // slave carrier in chamber { slave_cic = TRUE; message_add(SYSTEMLCD, MSG_CIC, MSG_AT+SLAVE, NEXT); } else { slave_cic=FALSE; message_del(SYSTEMLCD, MSG_CIC, MSG_AT+SLAVE); } if (slaveData[0] & 0x02) // slave door { slave_doorClosed = TRUE; // closed remote_data[REMOTE_DOOR] |= SLAVE_b; message_del(SYSTEMLCD, MSG_DROPEN, MSG_AT+SLAVE); } else { slave_doorClosed = FALSE; message_add(SYSTEMLCD, MSG_DROPEN, MSG_AT+SLAVE, NEXT); } if (slaveData[0] & 0x04) // show message if slave optic blocked { message_add(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT+SLAVE, NEXT); } else { message_del(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT+SLAVE); } if (slaveData[0] & 0x08) btnStatFlag=1; // Set stat from slave if (slaveData[0] & 0x10) btnStatFlag=2; // clear stat from slave if (slaveData[0] & 0x20) btnSecureFlag=1; // Set secure from slave if (slaveData[0] & 0x40) btnSecureFlag=2; // clear secure from slave slave_rts = slaveData[1]; // slave request to send slaveReturnStatus = slaveData[2]; // slave status // check status change request if (system_state==IDLE_STATE || system_state==MALFUNCTION_STATE) { if (slaveReturnStatus & 0x02) param.activeMain=SLAVE; if (slaveReturnStatus & 0x04) param.activeMain=MASTER; if (slaveReturnStatus & 0x06) // active main changed { // logActiveChange(8); setActiveMainMsg(); activeMainHere = (param.activeMain==MASTER); // FOR SETUP MENU } if (slaveReturnStatus & 0x08) deliverComControl(&system_state); if (slaveReturnStatus & 0x20) system_state=CANCEL_STATE; if (slaveReturnStatus & 0x40) slave_rtncarrier=TRUE; else slave_rtncarrier=FALSE; if (slaveReturnStatus & 0x80) slave_autoReturn=TRUE; else slave_autoReturn=FALSE; } // flash inuse when cic and not stacking if (slave_cic && !param.stacking_ok[0]) { // flash those with carriers unless stacking is allowed if (malfunctionActive) inUse(FLASH, SLAVE_b); else inUse(FLASH, SLAVE_b & ~systemStationb); } else { // no carrier or stacking OK so don't flash unless system station if (systemStationb != SLAVE_b) inUse(OFF, SLAVE_b); } // check for remote to cancel transaction if (slaveReturnStatus & 0x01 && (mainStation==SLAVE)) system_state=CANCEL_STATE; // cancel immediately } else slave_doorClosed = TRUE; // need to close unused door // flash inuse when cic and not stacking if (remote_data[REMOTE_CIC] && !param.stacking_ok[1]) { // flash those with carriers unless stacking is allowed if (malfunctionActive) inUse(FLASH, remote_data[REMOTE_CIC]); else inUse(FLASH, remote_data[REMOTE_CIC] & ~systemStationb); } // turn others off except system station if (malfunctionActive) inUse(OFF, ~(remote_data[REMOTE_CIC]|SLAVE_b)); else inUse(OFF, ~remote_data[REMOTE_CIC] & ~(systemStationb|SLAVE_b)); // for each with the door open and no cic, clear the arrival-alert and auto-return timer if (arrival_alert) { prev_arrival_alert = arrival_alert; // save to see what has changed arrival_alert &= (remote_data[REMOTE_CIC] | remote_data[REMOTE_DOOR]) & ~systemStationb; // for each zero bit clear the auto-return timer, secure log, and PIN message for (k=1; k<=LAST_STATION; k++) { kbit=station2bit(k); // setup bit equivalent // if arrived more than 15 seconds ago and no CIC then clear alert if (((SEC_TIMER-arrivalTime[k]) > 15) && ((remote_data[REMOTE_CIC] & kbit)==0)) { // then clear only based on CIC without regard for the door arrival_alert &= ~kbit; } // deal with reset of arrival alert(s) if ((arrival_alert & kbit)==0) { // is this a change in state if (prev_arrival_alert & kbit) securePIN[k]=-1; // clear the pin // reset auto return timer autoReturnTime[k]=0; arrivalTime[k]=0; //secureTransLog[k].sid=0; //secureTransLog[k].start_tm=0; message_del(SYSTEMLCD, MSG_PIN, MSG_AT+k); // delete PIN message } } } // clear slave arrival alert as necessary if (slave_arrival) { if ( (slave_doorClosed==FALSE && slave_cic==FALSE) || ((mainStation==SLAVE) && (system_direction==DIR_SEND)) ) { slave_arrival=0; message_del(SYSTEMLCD, MSG_ARVALRT, MSG_AT+SLAVE); message_del(SYSTEMLCD, MSG_PIN, MSG_AT+SLAVE); arrival_from=0; autoReturnTime[SLAVE]=0; } } // FOR EACH STATION WITH ACK SECURE, LOG THE BADGE ID AND REMOVE PIN MESSAGE // message_add(SYSTEMLCD, MSG_PIN, MSG_AT+systemStation); // for each station, check several conditions. for (k=1; k<=LAST_STATION; k++) { kbit=station2bit(k); // setup bit equivalent // if station not reporting and it should, show a message if (((kbit & response.station)==0) && (kbit & param.activeStations)) message_add(SYSTEMLCD, MSG_NOCOMM, MSG_AT+k, NEXT); else message_del(SYSTEMLCD, MSG_NOCOMM, MSG_AT+k); // for each with a door open, add door message, else del. if (remote_data[REMOTE_DOOR] & kbit) message_del(SYSTEMLCD, MSG_DROPEN, MSG_AT+k); else message_add(SYSTEMLCD, MSG_DROPEN, MSG_AT+k, NEXT); // for each with a carrier, add carrier message ... else del. if (remote_data[REMOTE_CIC] & kbit) message_add(SYSTEMLCD, MSG_CIC, MSG_AT+k, NEXT); else message_del(SYSTEMLCD, MSG_CIC, MSG_AT+k); // for each with a request-to-send, add pending message, else del. if ((remote_data[REMOTE_RTS] & kbit) || (remote_data[REMOTE_RTS2] & kbit)) message_add(SYSTEMLCD, MSG_PENDING, MSG_FROM+k, NEXT); else message_del(SYSTEMLCD, MSG_PENDING, MSG_FROM+k); // for each with arrival-alert, add warning, else del. if (arrival_alert & kbit) message_add(SYSTEMLCD, MSG_ARVALRT, MSG_AT+k, NEXT); else { message_del(SYSTEMLCD, MSG_ARVALRT, MSG_AT+k); } // for each with blocked arrival optic add message if (remote_data[REMOTE_ARRIVE] & kbit) message_add(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT+k, NEXT); else message_del(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT+k); } // check for head diverter blocked optic if (param.headDiverter) { if (remote_data[REMOTE_ARRIVE] & 0x80) // HARD CODE TO BIT 8 message_add(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT_HEADDIV, NEXT); else message_del(SYSTEMLCD, MSG_OPTIC_BLOCKED, MSG_AT_HEADDIV); } } } } // end if DON'T RUN COMMUNICATIONS ANY MORE THAN THE BUS CAN HANDLE // if system_reset (Abort) and state is not normal|malfunc, cancel // DON'T HAVE A GOOD WAY TO DO THIS AT THE MOMENT //while ( functionButton(FUNC_BUTT, FUNC_CURR) // && functionButton(FUNC_F1, FUNC_CURR) // && functionButton(FUNC_F2, FUNC_CURR) // && (system_state != IDLE_STATE) // && (system_state != MALFUNCTION_STATE)) system_state=CANCEL_STATE; // LAST REMOTE COMMAND BEFORE PROCESSING MUST BE "RETURN_INPUTS" switch (system_state) { case IDLE_STATE: //lcd_screenSaver(LCD_DIM); // handle backlight screen saver transactionType = TT_NONE; // make sure we start with no request destMain = MASTER; transProgress=101; // no activity doorOpenTimer=0; translog.flags = 0; translog.status = 0; eventlog.flags = 0; eventlog.status = 0; // Check carrier return function if (di_returnCarrier || lcd_returnCarrier()) { // determine which carrier to return systemStationb = (di_requestToSend | station2bit(lcd_sendTo())) & STATION_SET; systemStation=bit2station(systemStationb); if ( di_doorClosed && ( ( systemStation!=SLAVE && (systemStationb & remote_data[REMOTE_CIC] & remote_data[REMOTE_DOOR])) || ( systemStation==SLAVE && slave_doorClosed && slave_cic) ) ) { translog.flags = FLAG_CRETURN; UID_Clear(secureTransLog[systemStation].sid); // clear secure handling secureTransLog[systemStation].start_tm=0; if ((systemStation==SLAVE) && (slave_cic)) { transactionType = TT_SLAVE2MAIN; } else if ( (systemStation!=SLAVE) && ( systemStationb & remote_data[REMOTE_CIC] & remote_data[REMOTE_DOOR]) ) { transactionType = TT_REMOTE2MAIN; } } } // check slave carrier_return request next else if (slaveAvailable && slave_rtncarrier && slave_doorClosed) // carrier return function { // first check for master to slave systemStation=bit2station(slave_rts); translog.flags = FLAG_CRETURN; UID_Clear(secureTransLog[systemStation].sid); // clear secure handling secureTransLog[systemStation].start_tm=0; if ((systemStation==SLAVE) && di_carrierInChamber) { transactionType = TT_MAIN2SLAVE; } // otherwise check for carrier return from remote else if ( (systemStation!=SLAVE) && (slave_rts & remote_data[REMOTE_CIC] & remote_data[REMOTE_DOOR]) ) { transactionType = TT_REMOTE2SLAVE; } } // check slave outbound requests next else if (slaveAvailable && !statTrans && (slave_rts & STATION_SET) && slave_cic) { // slave station outbound to remote if ( !(remote_data[REMOTE_CIC] & slave_rts & STATION_SET) || param.stacking_ok[1]) { systemStation=firstBit(slave_rts); // check for main to main transaction if (systemStation==SLAVE) { transactionType = TT_SLAVE2MAIN; } else { transactionType = TT_SLAVE2REMOTE; } // check if the slave requested an auto-return if (slave_autoReturn) translog.flags = FLAG_ARETURN; } else { // not ready for dispatch - tell slave to clear rts_latch command.devAddr=ALL_DEVICES; command.command=CANCEL_PENDING; send_command(command); } } // check remote requests next else if (!statTrans && (remote_data[REMOTE_RTS] & STATION_SET)) { // which active main? if (param.activeMain==SLAVE && slaveAvailable) { // send to slave if ( ((slave_cic==FALSE && slave_arrival==0) || param.stacking_ok[0]) && (slave_doorClosed==TRUE) ) { transactionType = TT_REMOTE2SLAVE; systemStation=firstBit(remote_data[REMOTE_RTS]); } } else // active_main == MASTER { // only if (no carrier and no arrival_alert) or (stacking is ok) if ( (di_carrierInChamber==FALSE && main_arrival==0) || param.stacking_ok[0]) { // OK if main door is closed otherwise signal alert if (di_doorClosed) { transactionType = TT_REMOTE2MAIN; systemStation=firstBit(remote_data[REMOTE_RTS]); } else { setAlerts(ON); } } } } // check for sub station addressing else if (!statTrans && (remote_data[REMOTE_RTS2] & STATION_SET)) { // can only be to slave, make sure parameter is set if (param.subStaAddressing && slaveAvailable) { // send to slave if ( ((slave_cic==FALSE && slave_arrival==0) || param.stacking_ok[0]) && (slave_doorClosed==TRUE) ) { transactionType = TT_REMOTE2SLAVE; systemStation=firstBit(remote_data[REMOTE_RTS2]); } } } // Check auto-return function else if (autoReturnCarrier()) { systemStationb = autoReturnCarrier(); // doors & cic already checked systemStation=bit2station(systemStationb); UID_Clear(secureTransLog[systemStation].sid); // clear secure handling secureTransLog[systemStation].start_tm=0; translog.flags = FLAG_ARETURNING; if (systemStation==SLAVE) { transactionType = TT_SLAVE2MAIN; } else { transactionType = TT_REMOTE2MAIN; } } else if (SEC_TIMER > pingTimer) // check with server { pingTimer = SEC_TIMER + (60 * (int)param.syncInterval); tcpServerCheck(); } else { // check main request systemStationb = (di_requestToSend | station2bit(lcd_sendTo())) & STATION_SET; // proceed if good send request, no carrier or stacking ok except when secure // OR LAST UNREMOVED WAS SECURE secureTransLog[i].start_tm <> 0 // OR LAST UNREMOVED IS AUTO RETURN autoReturnTime[station] <> 0 // && ( !(remote_data[REMOTE_CIC] & systemStationb) || (param.stacking_ok[1] && !secureTrans))) if (valid_send_request(systemStationb)==0) { systemStation=bit2station(systemStationb); // count how many are hard button versus soft button // if (di_requestToSend) {rtsHardCount++;} else {rtsSoftCount++;} // check for main to main transaction if (systemStation==SLAVE) { transactionType = TT_MAIN2SLAVE; } else { transactionType = TT_MAIN2REMOTE; } // Set the auto-return flag if requested /// why?? if (lcd_autoReturn() || autoRtnTrans) translog.flags = FLAG_ARETURN; } } // do we have a transaction to process? if (transactionType != TT_NONE) { // setup to process a transaction request mainStation = transTypeInfo[transactionType][TT_MAINSTATION]; main2main_trans = transTypeInfo[transactionType][TT_MAIN2MAIN_TRANS]; system_direction = transTypeInfo[transactionType][TT_SYSTEM_DIRECTION]; systemStationb = station2bit(systemStation); inUse(FLASH, systemStationb); new_state=PREPARE_SEND; arrivalEnable(OFF); // make sure we clear every time if ((transactionType == TT_MAIN2SLAVE) || (transactionType == TT_REMOTE2SLAVE)) destMain=SLAVE; // leaving this s } else // check for directory display { k=di_requestToSend; if (k & STATION_SET) { systemStationb=k; systemStation=bit2station(systemStationb); if (systemStation) message_add(TRANSLCD, MSG_REMOTESTA, MSG_AT+systemStation, ONESHOT); } // nothing else to do here so reset systemStation systemStation=0; systemStationb=0; } FirstXtraCic=TRUE; // Used in HOLD_TRANSACTION // when leaving this state blank out the menu buttons and reset screensaver if (new_state != system_state) { lcd_drawScreen(1,lcd_NO_BUTTONS); //lcd_screenSaver(LCD_BRIGHT); } break; case PREPARE_SEND: // does job for send and return transProgress=10; // % progress // turn off priority if it was on // priority = FALSE; TURN OFF LATER (v2.47) message_add(SYSTEMLCD, MSG_SYSBUSY, MSG_DONTUSE, NEXT); message_del(SYSTEMLCD, MSG_STAT, MSG_STAT+1); setAlerts(OFF); do_priorityLight(OFF); message_add(TRANSLCD, MSG_SETTING, MSG_TO+systemStation, NOW); // save transaction data translog.trans_num = transactionCount()+1; eventlog.trans_num = translog.trans_num; translog.start_tm = SEC_TIMER; translog.duration = 0; translog.source_sta=mainStation; translog.dest_sta=mainStation; if (system_direction==DIR_SEND) { translog.dest_sta=systemStation; // some things only when sending if (autoRtnTrans) translog.flags |= FLAG_ARETURN; if (statTrans) translog.flags |= FLAG_STAT; //0x10; if (secureTrans) { translog.flags |= FLAG_SECURE; //0x20 // setup secure transaction log secureTransLog[systemStation].trans_num = translog.trans_num; secureTransLog[systemStation].start_tm = translog.start_tm; // will add delta-t's later UID_Clear(secureTransLog[systemStation].sid); // will come later from the card swipe secureTransLog[systemStation].status = ESTS_SECURE_REMOVAL; secureTransLog[systemStation].flags = 0; // station will be set later systemStation; // setup the secure pin securePIN[systemStation] = securePIN[0]; // move into position securePIN[0]=-1; // update the messages on the screen message_add(SYSTEMLCD, MSG_PIN, MSG_AT+systemStation, NEXT); message_del(TRANSLCD, MSG_STAT, MSG_PIN); } else securePIN[systemStation]=-1; // otherwise no PIN } else translog.source_sta=systemStation; if (transactionType == TT_SLAVE2MAIN) translog.dest_sta=MASTER; // tell all system(s) to get ready (set diverters) set_diverter(systemStation); command.devAddr=ALL_DEVICES; command.command=SET_DIVERTER; command.station=systemStation; command.data[0]=transTypeInfo[transactionType][TT_FROM]; // For head diverter command.data[1]=mainStation; // For slave command.data[2]=param.subStaAddressing; command.data[3]=param.blowerType; //command.data[4]=0xFF; // to help ident main messages command.data[4]=translog.flags; received=send_command(command); if (received) new_state=WAIT_FOR_DIVERTERS; else new_state=CANCEL_STATE; break; case WAIT_FOR_DIVERTERS: // does job for send and return transProgress=20; // % progress // Ready? if (divertersReady(systemStation, transTypeInfo[transactionType][TT_FROM], mainStation) && blowerReady()) { new_state=BEGIN_SEND; // serves both directions if ((system_direction==DIR_SEND) && (main2main_trans==0)) { message_add(TRANSLCD, MSG_INROUTE, MSG_TO+systemStation, NOW); }else if (system_direction==DIR_RETURN && main2main_trans==0) { message_add(TRANSLCD, MSG_INROUTE, MSG_FROM+systemStation, NOW); }else if (main2main_trans==DIR_SEND) { message_add(TRANSLCD, MSG_INROUTE, MSG_TO+SLAVE, NOW); } else { message_add(TRANSLCD, MSG_INROUTE, MSG_TO, NOW); } message_del(TRANSLCD, MSG_SETTING, MSG_TO+systemStation); } // only wait for a little time if ((MS_TIMER-state_timer >= DIVERTER_TIMEOUT) || (blwrError==TRUE)) { // timeout new_state=MALFUNCTION_STATE; if (blowerReady()==TRUE) { // diverter timeout statistics.divert_alarm++; translog.status=STS_DIVERTER_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); message_add(TRANSLCD, MSG_TIMEOUT, MSG_SETTING, NEXT); } else { // blower timeout statistics.divert_alarm++; translog.status=STS_BLOWER_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); message_add(TRANSLCD, MSG_TIMEOUT, MSG_BLOWER, NEXT); } } // while waiting, if different request to send, cancel. if (di_requestToSend && (systemStationb != di_requestToSend) && (system_direction==DIR_SEND)) { // Cancel the transaction translog.status=STS_CANCEL_BY_SEND; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_transaction( translog ); addTransaction( translog , 0); //msDelay(1000); // wait so input doesn't trigger another trans right away new_state=CANCEL_STATE; } break; case BEGIN_SEND: // works for both directions transProgress=30; // % progress // remote should be ready now, but set timeout just in case if (MS_TIMER-state_timer >= 2000) { new_state=MALFUNCTION_STATE; // Remote not ready or cancel dispatch translog.status=STS_TRANS_CANCEL; translog.duration=(int)(SEC_TIMER-translog.start_tm); } // before sending start command double check for cic/stacking command.data[0]=FALSE; if (system_direction==DIR_SEND && main2main_trans==0) { // main to remote -- check remote carrier or remote stacking if ( !(remote_data[REMOTE_CIC] & systemStationb) || param.stacking_ok[1] ) command.data[0]=TRUE; // ok to continue } else if (system_direction==DIR_SEND && main2main_trans==DIR_SEND) { // main to slave if ( param.stacking_ok[0] || !carrierInChamber(SLAVE)) command.data[0]=TRUE; // ok to continue } else if (system_direction==DIR_SEND && main2main_trans==DIR_RETURN) { // slave to main if ( param.stacking_ok[0] || !carrierInChamber(MASTER)) command.data[0]=TRUE; // ok to continue } else { // all other cases check main carrier or main stacking (master or slave) if ( param.stacking_ok[0] || !carrierInChamber(mainStation)) command.data[0]=TRUE; // ok to continue } // are we ok to send? if (command.data[0] == TRUE) { // make sure remotes are ready command.devAddr=ALL_DEVICES; command.command=ARE_YOU_READY; command.station=systemStation; command.data[0]=system_direction; command.data[1]=mainStation; command.data[2]=main2main_trans; //command.data[3]=translog.flags; if (send_n_get(command, &response)) { // if ((response.data[0] & STATION_SET) == STATION_SET) // all stations ok? if (response.data[0] == availableDevices) // all stations ok? { // turn on blower inUse(ON, systemStationb); message_del(TRANSLCD, MSG_REMOTESTA, MSG_NOT_READY); if (system_direction==DIR_SEND) { if (carrierInChamber(mainStation)) { //blower(blowerSend); new_state=WAIT_FOR_MAIN_DEPART; }else { print_event("TRANSACTION CANCELED - CARRIER REMOVED"); translog.status=STS_CANCEL_BY_CIC; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_transaction( translog ); addTransaction( translog, 0 ); new_state=CANCEL_STATE; } }else { if (remote_data[REMOTE_CIC] & systemStationb) { //blower(blowerReturn); new_state=WAIT_FOR_REM_DEPART; }else { print_event("TRANSACTION CANCELED - CARRIER REMOVED"); translog.status=STS_CANCEL_BY_REMOTE; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_transaction( translog ); addTransaction( translog, 0 ); new_state=CANCEL_STATE; } } } else { // remote door? message_add(TRANSLCD, MSG_REMOTESTA, MSG_NOT_READY, NOW); print_event("STATION(S) NOT READY FOR DISPATCH"); translog.status=STS_CANCEL_BY_REMOTE; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_transaction( translog ); addTransaction( translog, 0 ); new_state=CANCEL_STATE; } } } else { new_state=CANCEL_STATE; // no stacking allowed translog.status=STS_CANCEL_BY_STACK; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_transaction( translog ); addTransaction( translog, 0 ); } break; case WAIT_FOR_MAIN_DEPART: // check for doors opening new_state=checkDoorWhileRunning(system_state); // wait for carrier to exit if (carrierInChamber(mainStation)) { if (MS_TIMER-state_timer >= CIC_EXIT_TIMEOUT) { // been waiting too long, cancel statistics.cic_lift_alarm++; translog.status=STS_DEPART_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_malfunction( translog ); addTransaction( translog, 0 ); if (blwrError==TRUE) { // blower timeout error new_state=MALFUNCTION_STATE; } else { // just cancel new_state=CANCEL_STATE; } } // else, keep waiting } else { transProgress=40; // % progress if (param.headDiverter==TRUE) new_state=WAIT_FOR_HEADDIVERTER; else { new_state=WAIT_FOR_REM_ARRIVE; transProgress=60; // % progress } } break; case WAIT_FOR_REM_ARRIVE: // keep polling remote status until received, or timeout //if (remote_data[REMOTE_ARRIVE] & 0x7F) // at any station 1-7 (exclude headdiverter) if (remote_data[REMOTE_ARRIVE] & systemStationb) // at THE station { // handle arrival, transaction complete inUse(OFF, systemStationb); message_del(TRANSLCD, MSG_INROUTE, MSG_TO+systemStation); message_del(SYSTEMLCD, MSG_SYSBUSY, MSG_DONTUSE); arrival_alert |= systemStationb; // set arrival arrivalTime[systemStation] = SEC_TIMER; // set arrival time // shall we set the auto return timer? if (translog.flags & FLAG_ARETURN) autoReturnTime[systemStation] = SEC_TIMER; // print transaction data statistics.trans_out++; translog.duration = (int)(SEC_TIMER-translog.start_tm); // if secure trans add duration to secure log (PROBABLY IRRELEVANT NOW) if (translog.flags & FLAG_SECURE) secureTransLog[systemStation].start_tm += translog.duration; //if (printlog_active) print_transaction(translog); addTransaction( translog, 0 ); // notify destination of completion finalcmd.command=TRANS_COMPLETE; finalcmd.station=systemStation; finalcmd.data[0]=DIR_SEND; // check if (stat alert is active) or (auto return is active) or (alert always) if ( (statTrans==TRUE) || (autoRtnTrans==TRUE) || (param.remoteAudibleAlert==TRUE) ) { finalcmd.data[1]=1; } else { finalcmd.data[1]=0; } new_state=FINAL_COMMAND; systemStation=0; systemStationb=0; transProgress=90; // % progress } else { // check for doors opening new_state=checkDoorWhileRunning(system_state); // Check for timeout //if (MS_TIMER-state_timer >= DELIVER_TIMEOUT) if ((int)(SEC_TIMER-translog.start_tm) > param.deliveryTimeout + doorOpenTimer) { message_add(TRANSLCD, MSG_ODUE, MSG_TO+systemStation, NEXT); new_state=MALFUNCTION_STATE; statistics.deliv_alarm++; translog.status=STS_ARRIVE_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); //blower(OFF); } } break; case WAIT_FOR_REM_DEPART: transProgress=40; // % progress // check for doors opening new_state=checkDoorWhileRunning(system_state); // wait for carrier to exit if (MS_TIMER-state_timer >= CIC_EXIT_TIMEOUT) { // been waiting too long, cancel statistics.cic_lift_alarm++; //blower(OFF); translog.status=STS_DEPART_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); //print_malfunction( translog ); addTransaction( translog, 0 ); if (blwrError==TRUE) { // blower timeout error new_state=MALFUNCTION_STATE; } else { // just cancel new_state=CANCEL_STATE; } } if (~remote_data[REMOTE_CIC] & systemStationb) { if (param.headDiverter==TRUE) new_state=WAIT_FOR_HEADDIVERTER; else { new_state=WAIT_FOR_MAIN_ARRIVE; if (destMain == MASTER) arrivalEnable(ON); // enable arrival interrupt transProgress=60; // % progress } } break; case WAIT_FOR_HEADDIVERTER: // check for doors opening new_state=checkDoorWhileRunning(system_state); // wait for arrival at headdiverter controller if (remote_data[REMOTE_ARRIVE] & HEADDIVERTERSTATION) // at headdiverter { // shift headdiverter diverter message_add(TRANSLCD, MSG_SETTING, MSG_TO+systemStation, NOW); // tell all system(s) to get ready (set diverters) set_diverter(systemStation); command.devAddr=ALL_DEVICES; command.command=SET_DIVERTER; command.station=systemStation; command.data[0]=transTypeInfo[transactionType][TT_TO]; // For head diverter command.data[1]=mainStation; // For slave?? command.data[2]=param.subStaAddressing; command.data[3]=param.blowerType; received=send_command(command); if (received) new_state=SHIFT_HEADDIVERTER; else new_state=CANCEL_STATE; } // check for timeout if ((int)(SEC_TIMER-translog.start_tm) > param.deliveryTimeout + doorOpenTimer) { message_add(TRANSLCD, MSG_ODUE, MSG_AT+systemStation, NEXT); statistics.deliv_alarm++; new_state=MALFUNCTION_STATE; translog.status=STS_ARRIVE_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); //blower(OFF); } break; case SHIFT_HEADDIVERTER: transProgress=50; // % progress // wait for headdiverter diverter to be set // check for timeout if (MS_TIMER-state_timer >= DIVERTER_TIMEOUT) { // timeout statistics.divert_alarm++; new_state=MALFUNCTION_STATE; translog.status=STS_DIVERTER_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); message_add(TRANSLCD, MSG_TIMEOUT, MSG_SETTING, NEXT); } // wait for headdiverter diverter to be set if (divertersReady(systemStation, transTypeInfo[transactionType][TT_TO], mainStation)) { // new_state=WAIT_FOR_xxx_ARRIVE; // serves both directions if ((system_direction==DIR_SEND) && (main2main_trans == 0)) { // message_add(TRANSLCD, MSG_INROUTE, MSG_TO+systemStation, NOW); new_state=WAIT_FOR_REM_ARRIVE; }else { // message_add(TRANSLCD, MSG_INROUTE, MSG_FROM+systemStation, NOW); if (destMain == MASTER) arrivalEnable(ON); // enable arrival interrupt new_state=WAIT_FOR_MAIN_ARRIVE; } transProgress=60; // % progress message_del(TRANSLCD, MSG_SETTING, MSG_TO+systemStation); } break; case WAIT_FOR_MAIN_ARRIVE: // check for doors opening new_state=checkDoorWhileRunning(system_state); // Check for timeout //if (MS_TIMER-state_timer >= DELIVER_TIMEOUT) if ((int)(SEC_TIMER-translog.start_tm) > param.deliveryTimeout + doorOpenTimer) { message_add(TRANSLCD, MSG_ODUE, MSG_FROM+systemStation, NEXT); statistics.deliv_alarm++; new_state=MALFUNCTION_STATE; translog.status=STS_ARRIVE_TOUT; translog.duration=(int)(SEC_TIMER-translog.start_tm); } // if tube arrived ... if (carrierArrival(destMain) || latchCarrierArrival) { // handle arrival, transaction complete inUse(OFF, systemStationb); arrivalEnable(OFF); // disable arrival interrupt message_del(TRANSLCD, MSG_INROUTE, MSG_FROM+systemStation); message_del(TRANSLCD, MSG_INROUTE, MSG_TO+destMain); if (destMain==MASTER) { if (translog.flags & FLAG_ARETURNING) main_arrival=1; // constant on alert else main_arrival=SEC_TIMER; // set equal to current time for pulsed alert } else slave_arrival=SEC_TIMER; // shall we set the auto return timer? if (translog.flags & FLAG_ARETURN) autoReturnTime[destMain]=SEC_TIMER; //lcd_smartPrompt(3); // remove CIC arrival_from|=systemStationb; message_add(SYSTEMLCD, MSG_ARVALRT, MSG_AT+destMain, NEXT); message_del(SYSTEMLCD, MSG_SYSBUSY, MSG_DONTUSE); // print transaction data statistics.trans_in++; translog.duration = (int)(SEC_TIMER-translog.start_tm); //if (printlog_active) print_transaction(translog); addTransaction( translog, 0 ); // notify destination of completion finalcmd.command=TRANS_COMPLETE; finalcmd.station=systemStation; finalcmd.data[0]=DIR_RETURN; finalcmd.data[1]=0; // no remote alert finalcmd.data[2]=mainStation; new_state=FINAL_COMMAND; systemStation=0; systemStationb=0; transProgress=90; // % progress } else { // always re-activate the interrupt controller to attempt to fix spurious lost arrivals // WrPortI(I1CR, &I1CRShadow, 0x0E); // enable external INT1 on PE1, rising edge, priority 1 } break; case HOLD_TRANSACTION: // serves both send and return translog.flags|=FLAG_DOOROPEN; // restore send when both doors close if ((remote_data[REMOTE_DOOR] & systemStationb) && doorClosed(mainStation) && doorClosed(destMain)) { // check if user inserted a new carrier while the door was open XtraCic = FALSE; if ((memory_state == WAIT_FOR_REM_ARRIVE) && carrierInChamber(mainStation)) XtraCic = TRUE; if ((memory_state == WAIT_FOR_MAIN_ARRIVE) && (remote_data[REMOTE_CIC] & systemStationb)) XtraCic = TRUE; if (memory_state == WAIT_FOR_HEADDIVERTER) { if ((system_direction == DIR_SEND) && carrierInChamber(mainStation)) XtraCic = TRUE; if ((system_direction == DIR_RETURN) && (remote_data[REMOTE_CIC] & systemStationb)) XtraCic = TRUE; } if (XtraCic) { // stay in the alert/alarm mode if (FirstXtraCic) { print_event("EXTRA CARRIER INSERTED IN CHAMBER IN TRANSACTION FROM SOURCE"); FirstXtraCic=FALSE; eventlog.flags |= EFLAG_EXTRA_CIC; } } else { // no problem, resume transaction new_state=memory_state; setAlerts(OFF); // Turn off remote alert command.devAddr=ALL_DEVICES; command.command=SET_OUTPUTS; command.station=systemStation; command.data[devInUseSolid]=0; command.data[devInUseFlash]=0; command.data[devAlert]=0; command.data[devAlarm]=0; send_command(command); print_event("TRANSACTION RESUMED"); FirstXtraCic=TRUE; doorOpenTimer += ((MS_TIMER - state_timer)/1000); // door open timer in seconds // capture and log event information eventlog.duration=(int)(SEC_TIMER-eventlog.start_tm); addTransaction( eventlog, 0 ); // transaction resumed, log the event eventlog.flags=0; // clear flags after logging } } // was there an arrival while the door is opened? // else if ( ((memory_state == WAIT_FOR_REM_ARRIVE) && // ||((memory_state == WAIT_FOR_MAIN_ARRIVE) && // ||((memory_state == WAIT_FOR_HEADDIVERTER) && // { // carrier arrival while the door was opened so continue right away // } else { // otherwise toggle alert on 2 off 5 if (((MS_TIMER-state_timer) % 7) >= 2) setAlerts(OFF); else setAlerts(ON); } // Check for timeout //if (MS_TIMER-state_timer >= DELIVER_TIMEOUT) /* v327: don't timeout a transaction while the door is open (UNLESS ITS A REALLY LONG TIME???) if ((int)(SEC_TIMER-translog.start_tm) > param.deliveryTimeout + doorOpenTimer) { new_state=MALFUNCTION_STATE; statistics.deliv_alarm++; translog.flags|=3; translog.duration=SEC_TIMER; } */ break; case CANCEL_STATE: // reset all outputs and return to normal inUse(OFF, systemStationb); setAlerts(OFF); alarm(OFF); arrivalEnable(OFF); // disable arrival interrupt alarm_silenced_flag=FALSE; // reset alarm sound for next alarm blwrError=FALSE; // clear lcd message buffer unless just starting up if (systemStartup==FALSE) { message_del(SYSTEMLCD, EMPTY, EMPTY); message_del(TRANSLCD, EMPTY, EMPTY); } finalcmd.command=RESET; finalcmd.station=0; new_state=FINAL_COMMAND; systemStation=0; systemStationb=0; malfunctionActive=FALSE; // turn off priority if it was on statTrans = FALSE; secureTrans = FALSE; autoRtnTrans = FALSE; break; case MALFUNCTION_STATE: // first time into malfunction? if (malfunctionActive==FALSE) { inUse(OFF, ALL_STATIONS); setAlerts(OFF); //print_malfunction( translog ); addTransaction( translog, 0 ); lcd_drawScreen(1,lcd_WITH_BUTTONS); // redraw screen with buttons to allow for alarm menu // report blower errors if (blwrError==TRUE) { message_add(TRANSLCD, MSG_TIMEOUT, MSG_BLOWER, NEXT); } } arrivalEnable(OFF); // disable arrival interrupt if (mainStation == MASTER) alarm(ON); // turn off priority if it was on statTrans = FALSE; secureTrans = FALSE; autoRtnTrans = FALSE; // signal alarm at remote command.devAddr=ALL_DEVICES; command.command=MALFUNCTION; command.station=systemStation; send_command(command); // put up lcd message message_add(SYSTEMLCD, MSG_ALARM, MSG_ALARM+1, NOW); malfunctionActive=TRUE; break; case FINAL_COMMAND: // set the command before entering this state // remains in this state until command received or timeout //if (systemStartup==FALSE) transProgress=999; // blank out progress bar //else transProgress=101; // don't blank progress bar // P2P WORK TO BE DONE HERE finalcmd.devAddr=ALL_DEVICES; if (send_command(finalcmd)) { new_state=IDLE_STATE; if (finalcmd.command==TRANS_COMPLETE) incrementCounter(); // turn off priority if it was on statTrans = FALSE; secureTrans = FALSE; autoRtnTrans = FALSE; transProgress=101; // don't blank progress bar if (systemStartup==FALSE) lcd_drawScreen(1,lcd_WITH_BUTTONS); // Redraw screen with buttons systemStartup=FALSE; // no longer in system startup mode } // check timeout if (MS_TIMER-state_timer >= 1000) { new_state=IDLE_STATE; if (systemStartup==FALSE) lcd_drawScreen(1,lcd_WITH_BUTTONS); // Redraw screen with buttons systemStartup=FALSE; // no longer in system startup mode } break; default: // unknown state, execute cancel code new_state=CANCEL_STATE; } // if state change, reset state timer if (new_state != system_state) { // set blower for new state blower(blowerStateTable[new_state][blwrConfig]); state_timer=MS_TIMER; system_state=new_state; first_time_here=TRUE; // wasn't here yet sendUDPHeartbeat(0); // notify network on state change } else first_time_here=FALSE; // were already here } char checkSecureRemoval(void) { // Look into secure tracking structure for any removed secure transactions char i; // secureAck = 0; // to handshake back that it was handled for (i=1; i<9; i++) { // anything to do? when both sid and start time are non zero if (UID_Not_Zero(secureTransLog[i].sid) && secureTransLog[i].start_tm) { // handle secure removal if scan type =1 // flags contains the delta-t number of seconds 1:10 scale //secureTransLog[i].start_tm += secureTransLog[i].flags*6; secureTransLog[i].flags=i; // flags to contain the station number // log it - will get warning about wrong parameter type, ok to ignore addSecureTransaction(secureTransLog[i]); // clear PIN message message_del(SYSTEMLCD, MSG_PIN, MSG_AT+i); // acknowledge it ... again secureAck |= station2bit(i); // clear it UID_Clear(secureTransLog[i].sid); secureTransLog[i].start_tm = 0; } } } char autoReturnCarrier() { // check if an auto return timer is expired and the return can be started char k, kb; char returnVal; returnVal=0; // are there any at all? if (arrival_alert) { k=1; kb=1; while (k<=LAST_STATION && returnVal==0) { // for each bit check the auto-return timer if ( ((arrival_alert & kb) != 0) && (autoReturnTime[k] != 0)) { // auto return is active, now check the time remaining if ((SEC_TIMER - autoReturnTime[k]) > param.autoReturnTimer*60) { // and make sure the doors are closed, etc. so it can start if ( di_doorClosed && (kb & remote_data[REMOTE_CIC] & remote_data[REMOTE_DOOR]) ) { // ok to go, set this bit in the return value returnVal = kb; } } } // next bit and station kb=1<<k; k++; } } // Check slave auto return separate if ((returnVal==0) && slave_arrival) { // is there an auto-return timer set? if (autoReturnTime[SLAVE] != 0) { // has the time expired if ( (SEC_TIMER - autoReturnTime[SLAVE]) > (param.autoReturnTimer*60)) { // and make sure the doors are closed, etc. so it can start if ( (slave_doorClosed==TRUE) && (slave_cic==FALSE)) { // ok to go, set this bit in the return value returnVal = 1<<(SLAVE-1); } } } } return returnVal; } char checkDoorWhileRunning(char calling_state) { // Check for main or remote doors opening struct iomessage command; char event_string[80]; // line to send to the printer char rtnval; rtnval = calling_state; // return same state by default // check for main station door opening if ((!doorClosed(mainStation)) || (!doorClosed(destMain))) { setAlerts(ON); rtnval=HOLD_TRANSACTION; memory_state=calling_state; strcpy(event_string, "DOOR OPEN IN TRANSACTION (#) "); event_string[26] = 97+calling_state; strcat(event_string, sys_message[MSG_AT+mainStation].msg); print_event(event_string); eventlog.start_tm=SEC_TIMER; eventlog.source_sta=mainStation; eventlog.dest_sta=calling_state; eventlog.status=ESTS_DOOROPEN; eventlog.flags|=EFLAG_MAINDOOR; //st_time_diff = MS_TIMER - st_timer; // hold transfer timeout //message_add(SYSTEMLCD, MSG_SYSALARM, MSG_DOOR_OPEN, NOW); //door_warning = TRUE; } // check for remote station door opening if (~remote_data[REMOTE_DOOR] & systemStationb) { setAlerts(ON); // Turn on remote alert command.devAddr=ALL_DEVICES; command.command=SET_OUTPUTS; command.station=systemStation; command.data[devInUseSolid]=0; command.data[devInUseFlash]=0; command.data[devAlert]=systemStationb; command.data[devAlarm]=0; // P2P WORK TO BE DONE HERE send_command(command); rtnval=HOLD_TRANSACTION; memory_state=calling_state; strcpy(event_string, "DOOR OPEN IN TRANSACTION (#) "); event_string[26] = 97+calling_state; strcat(event_string, sys_message[MSG_AT+systemStation].msg); print_event(event_string); // capture event information eventlog.start_tm=SEC_TIMER; eventlog.source_sta=systemStation; eventlog.dest_sta=calling_state; eventlog.status=ESTS_DOOROPEN; eventlog.flags|=EFLAG_SUBSDOOR; //st_time_diff = MS_TIMER - st_timer; // hold transfer timeout //message_add(SYSTEMLCD, MSG_SYSALARM, MSG_DOOR_OPEN, NOW); //door_warning = TRUE; } return rtnval; } void processMainArrivalAlert(void) { // clear main arrival alert when door opens and no more carrier if (main_arrival) { // check for 10 second arrival alert signal if (main_arrival==1) { if (param.areturn_arrive_alert) do_audibleAlert(ON); // constant on if (param.mainVisualAlert) do_visualAlert(ON); } else if ( (SEC_TIMER - main_arrival) %20 >= 10 ) { if (param.mainAudibleAlert) do_audibleAlert(ON); // pulsed on if (param.mainVisualAlert) do_visualAlert(ON); } else { do_audibleAlert(OFF); do_visualAlert(OFF); } // check to clear main arrival alert if (!di_doorClosed && !di_carrierInChamber) { main_arrival=0; arrival_from=0; message_del(SYSTEMLCD, MSG_ARVALRT, MSG_AT); setAlerts(OFF); latchCarrierArrival=FALSE; // clear latch //lcd_smartPrompt(0); // clear smartPrompt } } } void processStatPriority(void) { // use btnStatFlag and btnSecureFlag to communicate between lcd screen functions and here // btnStatFlag = 1 - turn on stat // btnStatFlag = 2 - turn off stat // btnSecureFlag = 1 - turn on secure // btnSecureFlag = 2 - turn off secure // = else - no change // activate priority (next transaction) if requested if (di_priorityRequest || (btnStatFlag==1)) { statTrans = TRUE; btnStatFlag = 0; stat_expire = SEC_TIMER + STAT_TIMEOUT; do_priorityLight(ON); message_add(SYSTEMLCD, MSG_STAT, MSG_STAT+1, NOW); } // check for secure activation if (btnSecureFlag==1) { secureTrans = TRUE; btnSecureFlag=0; stat_expire = SEC_TIMER + STAT_TIMEOUT; // use stat timeout // Generage random PIN and display on the screen, make sure its not 0000 securePIN[0] = (int)(MS_TIMER % 9880)+110; // range of 0110 to 9989 //sprintf(&sys_message[MSG_PIN].msg[MSG_OFFSET+12], "%04d", securePIN[0]); message_add(TRANSLCD, MSG_STAT, MSG_PIN, NOW); } // check for auto return activation if (btnAReturnFlag==1) { autoRtnTrans = TRUE; stat_expire = SEC_TIMER + STAT_TIMEOUT; // use stat timeout btnAReturnFlag=0; } // deactivate secure after timeout or 2nd button press AND NO CIC if ((secureTrans && (SEC_TIMER > stat_expire) && (system_state == IDLE_STATE) && (!carrierInChamber(mainStation))) || (btnSecureFlag==2)) { secureTrans = FALSE; btnSecureFlag=0; // Remove PIN from the display securePIN[0] = -1; message_del(TRANSLCD, MSG_STAT, MSG_PIN); // deactivate screen button lcd_SetState( BTN_SECURE, 0); } // deactivate Auto Return after timeout or 2nd button press AND NO CIC if ((autoRtnTrans && (SEC_TIMER > stat_expire) && (system_state == IDLE_STATE) && (!carrierInChamber(mainStation))) || (btnAReturnFlag==2)) { autoRtnTrans = FALSE; btnAReturnFlag=0; // deactivate screen button lcd_SetState( BTN_ARETURN, 0); } // deactivate STAT priority after timeout, if not in a transaction AND NO CIC if ((statTrans && (SEC_TIMER > stat_expire) && (system_state == IDLE_STATE) && (!carrierInChamber(mainStation))) || (btnStatFlag==2)) { statTrans = FALSE; btnStatFlag = 0; do_priorityLight(OFF); // deactivate screen button lcd_SetState( BTN_STAT, 0); message_del(SYSTEMLCD, MSG_STAT, MSG_STAT+1); } } const char msgTable[4][2] = {MSG_BLANK, MSG_BLANK, MSG_BLANK, MSG_DROPEN, MSG_CIC, MSG_BLANK, MSG_CIC, MSG_DROPEN}; void update_cic_door_msgs(void) { // Add or remove CIC and Door messages from the TRANSLCD static char lastCIC, lastDoor; char CIC, Door; char theRow; char i; #GLOBAL_INIT { lastCIC=0; lastDoor=0; } // Note that ideal state of CIC and Door digital inputs is opposite each other CIC = di_carrierInChamber ? 1 : 0; // ensure it is only 1 or 0 Door = di_doorClosed ? 0 : 1; // ensure it is only 0 or 1 if ((lastCIC != CIC) || (lastDoor != Door)) { // One or the other changed so update all messages lastCIC = CIC; lastDoor = Door; theRow = lastCIC*2 + lastDoor; // don't actually use case 0,0 if (i>0) message_add(TRANSLCD, msgTable[theRow][0], msgTable[theRow][1], NEXT); // delete the other messages for (i=1; i<4; i++) { if (i != theRow) message_del(TRANSLCD, msgTable[i][0], msgTable[i][1]); } } } void showactivity() { // update active processor signal ledOut(0, (MS_TIMER %250) < 125); // on fixed frequency //ledOut(1, (MS_TIMER %500) > 250); // off fixed frequency toggleLED(2); // toggle each call } void toggleLED(char LEDDev) { static char LEDState[4]; // initialize LED states off #GLOBAL_INIT { LEDState[0]=0; LEDState[1]=0; LEDState[2]=0; LEDState[3]=0; } LEDState[LEDDev] ^= 1; // toggle LED state on/off ledOut(LEDDev, LEDState[LEDDev]); // send LED state } /******************************************************************/ // Blower Processing Routines - supports both standard and APU blowers /******************************************************************/ // Interface definition // char blwrConfig; // to become a parameter from eeprom // blwrConfig 0 = Straight through pipeing // blwrConfig 1 = Head diverter configuration // #define blwrOFF 0 // #define blwrIDLE 1 // #define blwrVAC 2 // #define blwrPRS 3 // void initBlower(void); // void blower(char blowerOperatingValue); // use blwrOFF, blwrIDLE, blwrVAC, blwrPRS // char processBlower(void); // char blowerPosition(void); char blower_mode, blower_limbo, last_shifter_pos, lastDir; unsigned long blower_timer; void initBlower() { // trys to find any shifter position, then goes to idle unsigned long mytimer; blwrConfig = 0; // Not a head diverter configuration // Clear global blower variables last_shifter_pos=0; lastDir=0; blower_limbo=FALSE; remoteBlwrPos=blwrIDLE; blwrError=FALSE; // turn off all outputs do_blower(OFF); do_blowerVac(OFF); do_blowerPrs(OFF); blower_mode=blwrOFF; // remainder of initialization is for APU blowers only if ((param.blowerType == blwrType_APU) && (param.headDiverter == FALSE)) { // if not in any position, try to find any position if (blowerPosition() == 0) { // hunt for any position do_blowerPrs(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); if (blowerPosition()==0) { // still not found...so go the other way do_blowerPrs(OFF); do_blowerVac(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); do_blowerVac(OFF); if (blowerPosition==0) blwrError=TRUE; // Blower timeout } } // after all that, now command to goto idle blower(blwrIDLE); } } void blower(char request) { // operates both standard blowers and APU blowers // sets the direction of the blower shifter // use blwrVAC, blwrPRS, blwrIDLE, or OFF char hv_save; char how; static char lastHow; #GLOBAL_INIT { blwrConfig = 0; // Not a head diverter configuration lastHow = 0; } // Remainder only for APU blowers if (param.blowerType == blwrType_STD) { // No such state as idle in standard blowers so map to OFF if (request==blwrIDLE) request=blwrOFF; how = request; // make sure correct parameter is used. anything but VAC and PRS is OFF if ((how != blwrVAC) && (how != blwrPRS)) how = blwrOFF; // if going from one on-state to the other on-state then turn off first if ((how != blwrOFF) && (lastHow != blwrOFF) && (how != lastHow)) { // can't run in both directions at the same time do_blowerPrs(OFF); do_blowerVac(OFF); msDelay(100); /* wait a little while */ } /* turn on appropriate bit */ if (how == blwrPRS) do_blowerPrs(ON); else if (how == blwrVAC) do_blowerVac(ON); else { do_blowerPrs(OFF); do_blowerVac(OFF); } // Add alternate blower on/off control per Joe request on 10-Jul-07 if (how != blwrOFF) do_blower(ON); else do_blower(OFF); // remember last setting lastHow = how; blower_timer = MS_TIMER; blower_mode = how; } // end of standard blower else if (param.blowerType == blwrType_APU) { // store in local work space blower_mode=request; blower_limbo=FALSE; /* clear previous state */ // hv_save=output_buffer; // turn off shifters do_blowerPrs(OFF); do_blowerVac(OFF); // CW for Pressure to Idle or Any to Vacuum // CCW for Vacuum to Idle or Any to Pressure if (blower_mode == blwrVAC) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blower_mode == blwrPRS) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blower_mode == blwrIDLE) { if (blowerPosition() == blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blowerPosition() == blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blowerPosition() == 0) { // go to idle but don't know which way if (lastDir==blwrVAC) { do_blowerVac(ON); blower_limbo=TRUE; lastDir=blwrVAC; } else if (lastDir==blwrPRS) { do_blowerPrs(ON); blower_limbo=TRUE; lastDir=blwrPRS; } else { // use last position to know which way to go blower_limbo = TRUE; // incomplete operation if (last_shifter_pos==blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (last_shifter_pos==blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else blower_limbo=FALSE; // idle to idle is ok to leave alone } } // else go-idle and already in idle position } else if (blower_mode == OFF) do_blower(OFF); // power off blower_timer = MS_TIMER; } return; } char processBlower() { // call repeatedly to handle process states of the blower // returns non-zero when shifter or blower error char rtnval; rtnval=0; // assume all is good // Turn on secondary output 2 seconds after first output goes on if ((MS_TIMER - blower_timer > 2000) && (blower_mode != OFF)) do_blowerDly(ON); else do_blowerDly(OFF); // Remainder only for APU blowers if there is no head diverter if ((param.blowerType == blwrType_APU) && (param.headDiverter == FALSE)) { if (blower_mode==OFF) return rtnval; // nothing happening, go home. if (blower_mode==ON) return rtnval; // running (ON is generic run mode) ... nothing to do // check for idled blower timeout if ((blower_mode==blwrIDLE) && (last_shifter_pos == blwrIDLE) && (lastDir==0) ) { // turn off idle'd blower after 2 minutes if (MS_TIMER - blower_timer > 120000) { // turn off all blower outputs do_blowerPrs(OFF); do_blowerVac(OFF); do_blower(OFF); blower_mode=OFF; lastDir=0; } return rtnval; } // check for incomplete change of direction and reset shifter outputs. // if was in limbo, and now in a known position, reset shifter if (blowerPosition() && blower_limbo) blower(blower_mode); // if in position .. but only the first time FIX. if (blower_mode == blowerPosition()) { // turn off shifter, turn on blower do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; // if going for idle position, mode is not ON ... just idle if (blower_mode != blwrIDLE) { blower_mode = ON; // generic ON state do_blower(ON); } blower_timer=MS_TIMER; // use also for blower idle time } else if (MS_TIMER - blower_timer > 12000) { // timeout ... shut off all outputs do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; blower_mode=OFF; rtnval=1; // set error code blwrError=TRUE; } } return rtnval; } char blowerPosition() { // returns the current position of the blower shifter // also keeps track of the last valid shifter position char rtnval, inval; rtnval=0; if (di_shifterPosVac) rtnval=blwrVAC; if (di_shifterPosPrs) rtnval=blwrPRS; if (di_shifterPosIdle) rtnval=blwrIDLE; if (rtnval) last_shifter_pos=rtnval; return rtnval; } char blowerReady() { // Checks for APU blowers to be in the idle position char rtnval; rtnval=TRUE; // assume ready if (param.blowerType==blwrType_APU) // STD blowers always ready { if (param.headDiverter==TRUE) // local or remote APU { if (remoteBlwrPos!=blwrIDLE) rtnval=FALSE; } else { if (blowerPosition()!=blwrIDLE) rtnval=FALSE; } if (blwrError==TRUE) rtnval=FALSE; // Blower timeout detected? } return rtnval; } // DIVERTER PROCESSING ROUTINES void setDiverterConfiguration() { // diverter configuration set by localDiverter byte // 0 = no local diverter; 1 = local diverter; // sets up values in the diverter_map station array // Array index is station # 1..7; // Value is diverter address; leg 1 or 2 or 0=n/a if (param.localDiverter == 0) { // All stations n/a diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; } else { // Station 1..4 on diverter leg 1; 5..7 on leg 2 diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 1; diverter_map[3] = 1; diverter_map[4] = 1; diverter_map[5] = 2; diverter_map[6] = 2; diverter_map[7] = 2; diverter_map[8] = 0; // no local diverter for slave } } /******************************************************************/ char divertersReady(char station, char headDiverter, char mainDiverter) { // Indicates if all local and remote diverters are set to // the specified station position. Returns TRUE or FALSE. struct iomessage command, response; char rtnval; rtnval=FALSE; // assign default value command.devAddr=ALL_DEVICES; command.command=DIVERTER_STATUS; command.station=station; command.data[0]=headDiverter; command.data[1]=mainDiverter; // also pass along the secure PIN for the active station command.data[2]=(char)(securePIN[systemStation] >> 8); // high byte command.data[3]=(char)(securePIN[systemStation] & 0xFF); // low byte response.data[0]=0; // P2P WORK TO BE DONE HERE send_n_get(command, &response); //if ( ( (response.data[0] & STATION_SET)==STATION_SET) if ( (response.data[0]==availableDevices) && ( (diverter_attention==FALSE) || (diverter_map[station]==0) ) ) { rtnval=TRUE; } // setup the diverter status to find out which device is not ready diverter_status = response.data[0]; if ((diverter_map[station]==0) || (diverter_attention==FALSE)) diverter_status |= 0x100; return rtnval; } /******************************************************************/ void set_diverter(char station) { /* Controls the setting of diverter positions Return from this routine is immediate. If diverter is not in position, it is turned on and a timer started. You MUST repeatedly call check_diverter() to complete processing of the diverter control position */ /* use mapping from station to diverter position */ if ((station>0) && (station<9)) // Valid station # { diverter_setting = diverter_map[station]; // mapped setting // if position<>ANY (any=0) and not in position if ((diverter_setting>0) && (diverter_setting!=di_diverterPos)) { /* turn on diverter and start timer */ do_diverter(ON); diverter_start_time = MS_TIMER; // + DIVERTER_TIMEOUT; diverter_attention = TRUE; // NOT USED IN MAIN diverter_station=station; } } return; } /******************************************************************/ void check_diverter() { /* Poll type processing of diverter control system */ /* Allows other processes to be acknowleged when setting diverter */ if (diverter_attention) { if ((diverter_setting == di_diverterPos) || (MS_TIMER-diverter_start_time > DIVERTER_TIMEOUT)) { // turn off diverter and clear status do_diverter(OFF); diverter_attention = FALSE; // NOT USED IN MAIN: diverter_station=0; } } } //************************************** // DIGITAL INPUT/OUTPUT FUNCTIONS //************************************** int readDigInput(char channel) { // returns the state of digital input 0-39 // function supports inverted logic by assigning dio_ON and dio_OFF char rtnval; if (channel < 16) { // on-board inputs rtnval = digIn(channel); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digIn(DevRN1100, channel-16, &rtnval, 0) == -1) rtnval=0; } else rtnval = 0; } // deal with logic inversion if (rtnval) rtnval = dio_ON; else rtnval = dio_OFF; return rtnval; } void setDigOutput(int channel, int value) { // sets the state of digital output 0-23 // call with logic value (0=OFF, 1=ON) // function is adapted to support inverted logic by assigning dio_ON and dio_OFF int outval; // check for logic inversion if (value) outval = dio_ON; else outval = dio_OFF; if (channel < 8) { // on-board outputs digOut(channel, outval); } else { // rn1100 outputs if (DevRN1100 != -1) rn_digOut(DevRN1100, channel-8, outval, 0); } } void alarm(char how) { if (how) { // turn on light //do_alarmLight(how); removed to substitute for alternate blower output, request by Joe 10-Jul-07 // if sound flag on, turn noise on, else off. if (alarm_silenced_flag) do_alarmSound(OFF); else do_alarmSound(how); } else { // turn off light and sound do_alarmSound(how); //do_alarmLight(how); } return; } void inUse(char how, char station_b) { // Only sets the global flags // Call Maintenance to actually turn on/off lights if (how == ON) { /* solid on, flash off */ outputvalue[devInUseSolid] |= station_b & STATION_SET; outputvalue[devInUseFlash] &= ~(station_b & STATION_SET); } else if (how == OFF) { /* solid off, flash off */ outputvalue[devInUseSolid] &= ~(station_b & STATION_SET); outputvalue[devInUseFlash] &= ~(station_b & STATION_SET); } else if (how == FLASH) { /* solid off, flash on */ outputvalue[devInUseSolid] &= ~(station_b & STATION_SET); outputvalue[devInUseFlash] |= station_b & STATION_SET; } // Turn off unused stations outputvalue[devInUseSolid] &= STATION_SET; outputvalue[devInUseFlash] &= STATION_SET; return; } // define input functions which take master/slave as a parameter char carrierInChamber(char whichMain) { if (whichMain==MASTER) return di_carrierInChamber; else return slaveData[0] & 0x01; } char carrierArrival(char whichMain) { if (whichMain==MASTER) return di_carrierArrival; else return slaveData[0] & 0x04; } char doorClosed(char whichMain) { if (whichMain==MASTER) return di_doorClosed; else return slaveData[0] & 0x02; } void setAlerts(char how) { // sets both audible and visual alerts do_audibleAlert(how); do_visualAlert(how); } //************************************** // KEYPAD INPUT FUNCTIONS //************************************** char getKey(void) { // Return a key from the keypad char wKey; char gk; static char last; //rn_keyProcess(DevRN1600, 0); // process keypad device //wKey = rn_keyGet(DevRN1600, 0); // reset menu timeout every time a key is pressed if (wKey) menu_timeout=SEC_TIMER + 60; else { // no keypad key so look for request-to-send key gk = bit2station(di_requestToSend); // return the key when the button is released if (gk==0 && last!=0) { wKey=last; last=0; menu_timeout=SEC_TIMER + 60; } else { last=gk; } } return wKey; } char valid_send_request(char station_b) { // make sure conditions are right to send a carrier // put up a brief message if not // checks for local and remote CIC, door, stacking, auto-return // returns zero when all conditions are ready to go char ecode, stanum; stanum = bit2station(station_b); if (stanum > 0) { // make sure local inputs are correct if (di_carrierInChamber && di_doorClosed) { ecode=0; // good local request ... for now // make sure no remote carrier unless stacking is ok and not a pending secure or pendign auto return if (remote_data[REMOTE_CIC] & station_b) { // remote CIC but maybe this is ok if (secureTransLog[stanum].start_tm != 0) { // this is not ok ecode=4; //reset_msg_timer(NEXT); //lcd_printMessage(0, " CAN NOT SEND "); //lcd_printMessage(1, "SECURE NOT REMOVED"); strncpy(sys_message[MSG_CANT_WHY].msg, "SECURE NOT REMOVED", MSG_LEN); } else if (autoReturnTime[stanum] !=0) { // this is not ok ecode=5; //reset_msg_timer(NEXT); //lcd_printMessage(0, " CAN NOT SEND "); //lcd_printMessage(1, "AUTO-RETURN ACTIVE"); strncpy(sys_message[MSG_CANT_WHY].msg, "AUTO-RETURN ACTIVE", MSG_LEN); } else if (param.stacking_ok[1] == FALSE) { // this is not ok ecode=3; //reset_msg_timer(NEXT); //lcd_printMessage(0, " CAN NOT SEND "); //lcd_printMessage(1, "STACKING UNALLOWED"); strncpy(sys_message[MSG_CANT_WHY].msg, "STACKING UNALLOWED", MSG_LEN); } else if (autoRtnTrans) { // this is not ok ecode=6; //reset_msg_timer(NEXT); //lcd_printMessage(0, " CAN NOT SEND "); //lcd_printMessage(1, "AUTO-RTN ON TO CIC"); strncpy(sys_message[MSG_CANT_WHY].msg, "AUTO-RTN ON TO CIC", MSG_LEN); } else if (secureTrans) { // this is not ok ecode=7; //reset_msg_timer(NEXT); //lcd_printMessage(0, " CAN NOT SEND "); //lcd_printMessage(1, " SECURE ON TO CIC "); strncpy(sys_message[MSG_CANT_WHY].msg, " SECURE ON TO CIC ", MSG_LEN); } // else then this is fine to stack } // else no carrier so no problem // check for remote door open if ((remote_data[REMOTE_DOOR] & station_b)==0) { // this is not ok ecode=8; strncpy(sys_message[MSG_CANT_WHY].msg, " REMOTE DOOR OPEN ", MSG_LEN); } // check for remote optic blocked if (remote_data[REMOTE_ARRIVE] & station_b) { // this is not ok ecode=9; strncpy(sys_message[MSG_CANT_WHY].msg, " REMOTE OPTIC ERR ", MSG_LEN); } // if can not send then show the reason why message if (ecode) message_add(TRANSLCD, MSG_CANT_SEND, MSG_CANT_WHY, NOW); else message_del(TRANSLCD, MSG_CANT_SEND, MSG_CANT_WHY); } else { ecode=2; // local door open or no carrier message_del(TRANSLCD, MSG_CANT_SEND, MSG_CANT_WHY); } } else ecode=1; // no request or multiple inputs return ecode; } /*******************************************************/ // transaction request queue functions #define queue_len 9 struct trans_queue_type { char source; char dest; } trans_queue[queue_len]; char queue_last; void queueAdd(char tsource, char tdest) { // adds request to queue USE BIT VALUES char i; char found; // add only if source does not already exist .. otherwise replace found=FALSE; for (i=0; i<queue_len; i++) { if (trans_queue[i].source==tsource) { // replace existing entry trans_queue[i].dest = tdest; found=TRUE; } } if (found==FALSE) { // not found so add after last current entry queue_last = (queue_last+1) % queue_len; trans_queue[queue_last].source=tsource; trans_queue[queue_last].dest=tdest; } } void queueDel(char tsource, char tdest) { // deletes request from queue // call with (0,0) to initialize char i; if (tsource==0 && tdest==0) { for (i=0; i<queue_len; i++) { trans_queue[i].source=0; trans_queue[i].dest=0; } queue_last=0; } else // find specified entry and delete it { for (i=0; i<queue_len; i++) { if (trans_queue[i].source==tsource && trans_queue[i].dest==tdest) { trans_queue[i].source=0; trans_queue[i].dest=0; // decrement last if it is the current entry if (queue_last==i) queue_last = (queue_last+queue_len-1) % queue_len; } } } } void queueNext(char *tsource, char *tdest) { // returns next queue entry char i; char found; // start at last+1 until a non-zero entry or back to last *tsource=0; *tdest=0; // initialize to zero found=FALSE; i=queue_last; do { // increment to next queue entry i=(i+1) % queue_len; if (trans_queue[i].source != 0) { // this must be it *tsource=trans_queue[i].source; *tdest=trans_queue[i].dest; found=TRUE; } } while (found==FALSE && i!=queue_last); } char queueVerify(char cic_data, char door_data) { // step through each queue entry and kill if no carrier or door open // returns bit set of each station in queue (to flash in-use) char i; char rtnval; rtnval=0; for (i=0; i<queue_len; i++) { if (trans_queue[i].source != 0) // if valid queue entry { if ((trans_queue[i].source & cic_data & door_data) == 0) { // kill it ... no more carrier or door is open queueDel(trans_queue[i].source, trans_queue[i].dest); } else { // include these bits in return val rtnval |= trans_queue[i].source | trans_queue[i].dest; } } } return rtnval; } //************************************** // LCD MESSAGE FUNCTIONS //************************************** static unsigned long msgtimer; struct queue { char curentry; char cursize; char line1[QUEUESIZE]; char line2[QUEUESIZE]; } msgqueue[2]; char oneshot[2][2]; // oneshot buffer [lcd][line] char currentmsg[2][2]; // current display message void message_del(char lcd, char msgline1, char msgline2) { char k, l, loc; if ( (lcd != 0) && (lcd != 1) ) return; // invalid lcd# if (msgline1==EMPTY) { // delete all messages, reinitialize queue for (l=0; l<LCDCOUNT; l++) { for (k=0; k<QUEUESIZE; k++) { msgqueue[l].line1[k] = EMPTY; msgqueue[l].line2[k] = EMPTY; } msgqueue[l].curentry = 0; msgqueue[l].cursize = 0; oneshot[l][0]=EMPTY; // clear oneshot buffers oneshot[l][1]=EMPTY; } message_show(NOW); // } else { // remove message from queue k=0; // find k, the queue entry number while ( ((msgline1 != msgqueue[lcd].line1[k]) || ( (msgline2 != msgqueue[lcd].line2[k]) || (msgline2 == EMPTY) )) && (k < QUEUESIZE-1) ) k++; // did we find a matching message? if ( (msgline1 == msgqueue[lcd].line1[k]) && ( (msgline2 == msgqueue[lcd].line2[k]) || (msgline2 == EMPTY) ) ) { // yes so remove the entry loc = k; for (k=loc; k<QUEUESIZE-1; k++) { msgqueue[lcd].line1[k] = msgqueue[lcd].line1[k+1]; msgqueue[lcd].line2[k] = msgqueue[lcd].line2[k+1]; } msgqueue[lcd].cursize--; // decrement current size if (msgqueue[lcd].cursize==0) msgqueue[lcd].curentry=0; msgqueue[lcd].line1[QUEUESIZE-1] = EMPTY; // insert empty entry at end if (msgqueue[lcd].line1[ msgqueue[lcd].curentry ] == EMPTY) { msgqueue[lcd].curentry = 0; message_show(NOW); // show next } if (msgqueue[lcd].curentry == loc) message_show(NOW); // show next } } return; } void message_add(char lcd, char msgline1, char msgline2, char how) { int k; // how = NOW // show message immediately // how = NEXT // show message next // how = ONESHOTA // show message once first of 2 oneshots // how = ONESHOT // show message once right now if ( (lcd != 0) && (lcd != 1) ) return; // invalid lcd# if (how==ONESHOT || how==ONESHOTA) { // show only once oneshot[lcd][0]=msgline1; oneshot[lcd][1]=msgline2; if (how==ONESHOT) message_show(ONESHOT); return; } // insert as next message if not already in queue k=0; if (msgqueue[lcd].cursize==0) { msgqueue[lcd].curentry=0; msgqueue[lcd].line1[0] = msgline1; msgqueue[lcd].line2[0] = msgline2; msgqueue[lcd].cursize++; } else { while ( ( (msgline1 != msgqueue[lcd].line1[k]) || (msgline2 != msgqueue[lcd].line2[k]) ) && (k < QUEUESIZE-1) ) k++; if ( (msgline1 != msgqueue[lcd].line1[k]) || (msgline2 != msgqueue[lcd].line2[k]) ) // must not be in q already { for (k=QUEUESIZE-2; k>msgqueue[lcd].curentry; k--) { msgqueue[lcd].line1[k+1] = msgqueue[lcd].line1[k]; // shift over msgqueue[lcd].line2[k+1] = msgqueue[lcd].line2[k]; // shift over } msgqueue[lcd].line1[ msgqueue[lcd].curentry+1 ] = msgline1; msgqueue[lcd].line2[ msgqueue[lcd].curentry+1 ] = msgline2; msgqueue[lcd].cursize++; // increment current size } else return; // no update if already in queue } // fix queue when size=1 and not current if ( (how == NOW ) || ( msgqueue[lcd].cursize==1 ) ) { // make current now, otherwise update in time message_show(NOW); } return; } void message_show(char how) { char lcd, l1, l2, k; if ( (how==NOW) || (how==ONESHOT) || (MS_TIMER - msgtimer >= SCROLLTIME) ) { if (how != ONESHOT) { // index to next message (both lcds) for (lcd=0; lcd<LCDCOUNT; lcd++) { if (msgqueue[lcd].cursize > 0) { k=msgqueue[lcd].curentry + 1; while ((msgqueue[lcd].line1[k] == EMPTY) && (k != msgqueue[lcd].curentry)) k=(k+1)%QUEUESIZE; if (msgqueue[lcd].line1[k] != EMPTY) msgqueue[lcd].curentry = k; } } } msgtimer = MS_TIMER; // + SCROLLTIME; // display messages for (lcd=0; lcd<LCDCOUNT; lcd++) { if ((how==ONESHOT) && (oneshot[lcd][0] != EMPTY)) { l1=oneshot[lcd][0]; // use oneshot buffer l2=oneshot[lcd][1]; oneshot[lcd][0]=EMPTY; // clear oneshot buffer } else { // load regular message l1=msgqueue[lcd].line1[ msgqueue[lcd].curentry ]; l2=msgqueue[lcd].line2[ msgqueue[lcd].curentry ]; } if (l1==EMPTY) // show default msg if empty queue { setTimeMessages(MSG_DATE_TIME, SEC_TIMER); // default uses time message if (lcd==TRANSLCD) { l1=MSG_TDEFAULT; l2=MSG_TDEFAULT2; } else { l1=MSG_SDEFAULT; l2=MSG_SDEFAULT2; } } // check for timer message refresh before display //refresh_dynamic_message(l1); //refresh_dynamic_message(l2); // refresh PIN message, have to assume line 2 is target station //if (l1==MSG_PIN) refresh_PIN_message(l1, l2); //if (l2==MSG_PIN) refresh_PIN_message(l2, l1); // double check message range before display if ((l1>=0) && (l1<MSGCOUNT)) { //lcd_print(lcd, 0, sys_message[l1].msg); currentmsg[lcd][0] = l1; } if ((l2>=0) && (l2<MSGCOUNT)) { //lcd_print(lcd, 1, sys_message[l2].msg); currentmsg[lcd][1] = l2; } } // send command to remote systems with lcd's to display same msg displayRemoteMsgs(&currentmsg[0][0]); if (echoLcdToTouchscreen) lcd_displayMsgs(&currentmsg[0][0]); // color touch screen for (lcd=0; lcd<LCDCOUNT; lcd++) { // show messages after sending to slave //lcd_print(lcd, 0, sys_message[currentmsg[lcd][0]].msg); //lcd_print(lcd, 1, sys_message[currentmsg[lcd][1]].msg); printf("%s\n%s\n", sys_message[currentmsg[lcd][0]].msg, sys_message[currentmsg[lcd][1]].msg); } } } void refresh_dynamic_message(char msg) { // Update display of dynamic messages // timer messages need to refresh every second char lcd, line; unsigned long timepar; switch (msg) { /* case MSG_EXPOSE_TIME: // count up or count down if (op_mode == OPMODE_MANUAL) timepar = (MS_TIMER - exposure_start_time) / 1000; else timepar = param.exposureTimer - (MS_TIMER - exposure_start_time)/1000; sys_message[MSG_EXPOSE_TIME].msg[9] = 48 + (sample_number / 10); sys_message[MSG_EXPOSE_TIME].msg[10] = 48 + (sample_number % 10); setTimeMessages(MSG_EXPOSE_TIME, timepar); //lcd_print(lcd, line, sys_message[MSG_EXPOSE_TIME].msg); break; */ } } void refresh_PIN_message(char msg1, char msg2) { // Update display of secure PIN messages int station; // already know that msg1 = MSG_PIN // need to determine what station this is for as offset from MSG_AT station = (int)msg2 - (int)MSG_AT; if ((station < 0) || (station > 8)) station=0; // if not MSG_AT then default to station 0 // NOTE space in format after %04d matches with extra space at end of message sprintf(&sys_message[MSG_PIN].msg[MSG_OFFSET+12], "%04d ", securePIN[station]); } void lcd_show_cursor(char lcd, char line, char pos) { // Show or hide the lcd cursor if (lcd >= LCDCOUNT) { //rn_dispCursor(DevRN1600, RNDISP_CUROFF, 0); } else { //rn_dispCursor(DevRN1600, RNDISP_CURON, 0); //rn_dispGoto (DevRN1600, pos, line+lcd*2, 0); } } void reset_msg_timer(char how) { // setup for next message in time or show next message now (soon) if (how==NOW) msgtimer = MS_TIMER + 100 - SCROLLTIME; else if (how=NEXT) msgtimer = MS_TIMER; } void lcd_print(char lcd, char line, char* message) { lputs(line+lcd*2, message); } void lputs(char line, char* msg) { //char c; //rn_dispGoto(DevRN1600, 0, line, 0); //rn_dispPrintf (DevRN1600, 0, msg); //for (c=0; c<MSG_LEN; c++) rn_dispPutc(DevRN1600, msg[c], 0); printf("%s \n", msg); } void lcd_initialize() { } /******************************************************************/ void initializeMessages(void) { // Setup messages for lcd display char j; // load ram messages with contents of rom for (j=0; j<MSGCOUNT; j++) strcpy(sys_message[j].msg, sysmsg[j]); // set station name messages buildStationNames(); } /******************************************************************/ const char * const defaultStaName[] = { "MAIN", "STATION 1", "STATION 2", "STATION 3", "STATION 4", "STATION 5", "STATION 6", "STATION 7", "SLAVE MAIN", "SYSTEM" }; void buildStationNames() { char j, k, start, mybuf[MSG_LEN+1]; // check if names are initialized if (param.names_init != 69) // init flag { // use default names for (j=0; j<SYSTEM_NAME; j++) // SYSTEM_NAME always the last name { strcpy(param.station_name[j].name, defaultStaName[j]); } param.names_init = 69; } // build station name messages for (j=0; j<SYSTEM_NAME; j++) // SYSTEM_NAME always the last name { // clear out destinations strcpy(sys_message[MSG_AT+j].msg, sys_message[MSG_BLANK].msg); strcpy(sys_message[MSG_FROM+j].msg, sys_message[MSG_BLANK].msg); strcpy(sys_message[MSG_TO+j].msg, sys_message[MSG_BLANK].msg); strcpy(mybuf, "AT "); strcat(mybuf, param.station_name[j].name); // center message start = (MSG_LEN - strlen(mybuf)) / 2; // place in destination for (k=0; k<strlen(mybuf); k++) sys_message[MSG_AT+j].msg[k+start]=mybuf[k]; strcpy(mybuf, "FROM "); strcat(mybuf, param.station_name[j].name); // center message start = (MSG_LEN - strlen(mybuf)) / 2; // place in destination for (k=0; k<strlen(mybuf); k++) sys_message[MSG_FROM+j].msg[k+start]=mybuf[k]; strcpy(mybuf, "TO "); strcat(mybuf, param.station_name[j].name); // center message start = (MSG_LEN - strlen(mybuf)) / 2; // place in destination for (k=0; k<strlen(mybuf); k++) sys_message[MSG_TO+j].msg[k+start]=mybuf[k]; } } char functionDefineStations() { // define the active stations } /******************************************************************/ void functionSetNames() { // edit main & remote station names } // time structure used in several of the following routines //struct tm time; void setCountMessage(void) { // store long numeric value transactionCount into message buffer char j, k, mybuf[MSG_LEN+1]; strcpy(sys_message[MSG_TRANS_COUNT].msg, sys_message[MSG_BLANK].msg); ltoa(transactionCount(), mybuf); // stuff mybuf into center of message k=(MSG_LEN-strlen(mybuf))/2; for (j=0; j<strlen(mybuf); j++) sys_message[MSG_TRANS_COUNT].msg[j+k]=mybuf[j]; } void setParValueMessage(char MSG_message, unsigned long par_value, char * par_units) { // store long numeric value into message buffer char j, k, mybuf[MSG_LEN+1]; // blank out existing message strcpy(sys_message[MSG_message].msg, sys_message[MSG_BLANK].msg); // convert value to string and append units text ltoa(par_value, mybuf); strcat(mybuf, " "); strcat(mybuf, par_units); // place mybuf and units text into center of message k=(MSG_LEN-strlen(mybuf))/2; for (j=0; j<strlen(mybuf); j++) sys_message[MSG_message].msg[j+k]=mybuf[j]; } void setTimeMessages(char message, unsigned long timedate) { // fills in the time and date into the sys_message messages // timedate in seconds struct tm time; //char bad; //bad=63; // question mark // convert unsigned long to time structure mktm(&time, timedate); //if ( tm_rd( &time ) ) //{ // error reading date/time //} else if (message == MSG_DATE_TIME) { // fill in the time values /* FOR ORIGINAL TIME MESSAGE sys_message[MSG_TIME].msg[MSG_OFFSET + 7] = 48 + (time.tm_hour / 10); sys_message[MSG_TIME].msg[MSG_OFFSET + 8] = 48 + (time.tm_hour % 10); sys_message[MSG_TIME].msg[MSG_OFFSET + 10] = 48 + (time.tm_min / 10); sys_message[MSG_TIME].msg[MSG_OFFSET + 11] = 48 + (time.tm_min % 10); //sys_message[MSG_TIME].msg[13] = 48 + (time.tm_sec / 10); //sys_message[MSG_TIME].msg[14] = 48 + (time.tm_sec % 10); */ // and second message sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 10] = 48 + (time.tm_hour / 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 11] = 48 + (time.tm_hour % 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 13] = 48 + (time.tm_min / 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 14] = 48 + (time.tm_min % 10); // fill in the date values // sys_message[MSG_DATE].msg[MSG_OFFSET + 7] = 48 + (time.tm_mon / 10); // sys_message[MSG_DATE].msg[MSG_OFFSET + 8] = 48 + (time.tm_mon % 10); // sys_message[MSG_DATE].msg[MSG_OFFSET + 10] = 48 + (time.tm_mday / 10); // sys_message[MSG_DATE].msg[MSG_OFFSET + 11] = 48 + (time.tm_mday % 10); // sys_message[MSG_DATE].msg[MSG_OFFSET + 13] = 48 + ((time.tm_year / 10) % 10); // sys_message[MSG_DATE].msg[MSG_OFFSET + 14] = 48 + (time.tm_year % 10); // and second message sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 1] = 48 + (time.tm_mon / 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 2] = 48 + (time.tm_mon % 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 4] = 48 + (time.tm_mday / 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 5] = 48 + (time.tm_mday % 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 7] = 48 + ((time.tm_year / 10) % 10); sys_message[MSG_DATE_TIME].msg[MSG_OFFSET + 8] = 48 + (time.tm_year % 10); } else if (message == MSG_PAR_VALUE) { // fill in the time values //sys_message[MSG_PAR_VALUE].msg = " HH:MM:SS "; strcpy(sys_message[MSG_PAR_VALUE].msg, sys_message[MSG_BLANK].msg); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 4] = 48 + (time.tm_hour / 10); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 5] = 48 + (time.tm_hour % 10); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 6] = ':'; sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 7] = 48 + (time.tm_min / 10); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 8] = 48 + (time.tm_min % 10); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 9] = ':'; sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 10] = 48 + (time.tm_sec / 10); sys_message[MSG_PAR_VALUE].msg[MSG_OFFSET + 11] = 48 + (time.tm_sec % 10); } } void setFlagMessage(char flag) { // flag message is on or off if (flag) { sys_message[MSG_FLAG_SET].msg[MSG_OFFSET + 12]=78; // ON sys_message[MSG_FLAG_SET].msg[MSG_OFFSET + 13]=32; } else { sys_message[MSG_FLAG_SET].msg[MSG_OFFSET + 12]=70; // OFF sys_message[MSG_FLAG_SET].msg[MSG_OFFSET + 13]=70; } } void show_extended_data() { // display watchdog, powerlow resets and versions on the lcd int i; int ver; char msgbuf[30]; //lcd_print(SYSTEMLCD, 0, " REMOTE RESETS "); //strcpy(msgbuf, "#n WD:___ PL:___"); lcd_DispText("Remote Vers ", 0, 0, MODE_NORMAL); for (i=1; i<8; i++) { if ( (1 << (i-1)) & (int)availableDevices ) // if i is a remote devAddr { ver = extendedData[i][2]; // move to int as DC treats char different - could be a bug??? sprintf(msgbuf, "4.%02d; ", ver); lcd_DispText(msgbuf,0, 0, MODE_NORMAL); //lcdcmd(LINE1); //msgbuf[1]=48+i; // remote # //msgbuf[6]=48+(extendedData[i][0] / 100); //msgbuf[7]=48+((extendedData[i][0] / 10) % 10); //msgbuf[8]=48+(extendedData[i][0] % 10); //msgbuf[13]=48+(extendedData[i][1] / 100); //msgbuf[14]=48+((extendedData[i][1] / 10) %10); //msgbuf[15]=48+(extendedData[i][1] % 10); //lputs(0, msgbuf); } } // msDelay(1200); lcd_DispText("\n", 0, 0, MODE_NORMAL); } unsigned long transaction_count; static unsigned long transCountXaddr; // physical memory address /*******************************************************/ unsigned long transactionCount() { return transaction_count; } /*******************************************************/ nodebug void incrementCounter() { transaction_count++; setCountMessage(); root2xmem( transCountXaddr, &transaction_count, 4); root2xmem( transCountXaddr+4, &statistics, sizeof(statistics)); // also save stats to xmem syncTransCount(); // send to the slave } /*******************************************************/ void loadTransactionCount() { #GLOBAL_INIT { transCountXaddr = 0; } // allocate xmem if not already done if (transCountXaddr == 0) transCountXaddr = xalloc(32); // Read transaction counter xmem2root( &transaction_count, transCountXaddr, 4); xmem2root( &statistics, transCountXaddr+4, sizeof(statistics)); // also read stats if (transaction_count < 0 || transaction_count > 10000000) { resetTransactionCount(0); } setCountMessage(); syncTransCount(); // send to the slave } /******************************************************************/ void resetTransactionCount(unsigned long value) { transaction_count=value; setCountMessage(); root2xmem( transCountXaddr, &transaction_count, 4); syncTransCount(); // send to the slave } void resetStatistics(void) { statistics.trans_in=0; statistics.trans_out=0; statistics.deliv_alarm=0; statistics.divert_alarm=0; statistics.cic_lift_alarm=0; root2xmem( transCountXaddr+4, &statistics, sizeof(statistics)); } /******************************************************************/ // MAKING DESIGN ASSUMPTION --> MNU_xxx value is the same as the index in menu[] // define menu item numbers enum MenuItems { MNU_MARRIVAL_BEEP, MNU_RARRIVAL_BEEP, MNU_ARETURN_BEEP, MNU_VISUAL_ALERT, MNU_ALARM_SOUND, MNU_PURGE, MNU_ALARM_RESET, MNU_SETACTIVEMAIN, MNU_SET_CLOCK, MNU_COMM_STAT, MNU_MSTACKING, MNU_RSTACKING, MNU_RESET_COUNT, MNU_SET_STANAMES, MNU_SET_PHONENUMS, MNU_DIVERTER_CFG, MNU_SETPASSWORD, MNU_CLEARPASSWORDS, MNU_SETTIMEOUT, MNU_HEADDIVERTER, MNU_AUTO_PURGE, MNU_AUTOPUR_TIMER, MNU_SETASSLAVE, MNU_DEF_STATIONS, MNU_ADVANCED_SETUP, MNU_RESET, MNU_ADMIN_FEATURES, MNU_MAINT_FEATURES, MNU_SYSTEM_CONFIG, MNU_VIEW_LOGS, MNU_VIEW_TLOG, // Transaction log MNU_VIEW_SLOG, // Summary log MNU_VIEW_ELOG, // Event log MNU_VIEW_ALOG, // Alarm log MNU_AUTO_RETURN, MNU_DNLD_TLOG, MNU_UPLD_TLOG, MNU_CHECK_SFLASH, MNU_ANALYZE_LOG, MNU_SUBSTA_ADDR, // for remote to select destination (main or sattelite) MNU_BLOWER_TYPE, MNU_PORT_MAPPING, MNU_LCD_CALIBRATE, MNU_SET_SYSNUM, MNU_SHOW_IPADDR, MNU_SECURE_SETUP, MNU_SECURE_ENABLE, MNU_CARDID_ENABLE, MNU_SERVER_ADDRESS, MNU_SYNC_INTERVAL, //MNU_SECURE_R9MAX, //MNU_SECURE2_L3DIGITS, //MNU_SECURE2_R9MIN, //MNU_SECURE2_R9MAX, MNU_SHOW_INPUTS, MNU_TUBE_DRYER, MNU_ENAB_DRYER_OPT, MNU_RESYNC_USERS, MNU_CHECK_SVR_NOW, MNU_LAST }; // Define bitmasks for activation of menu items #define MNU_ADV 0x0E #define MNU_STD 0x01 #define MNU_ALRM 0x10 #define MNU_NONE 0x00 // Define parameter types #define MNU_FLAG 01 #define MNU_VAL 02 #define MNU_TIME 03 #define MNU_CLK 04 #define MNU_OTHR 05 // define parameter menu char NOch; // dummy/temporary character place holder const struct{ char item; // menu item //char usage; // when available to the user char *msg1; // pointer to message char partype; // parameter type (flag, clock, integer value, other) char *parval; // parameter value unsigned long min; // parameter minimum unsigned long max; // parameter maximum (or don't save flag changes [=0]) char units[4]; // parameter units display } menu[] = { MNU_MARRIVAL_BEEP, "MAIN AUDIBLE ALERT",MNU_FLAG, &param.mainAudibleAlert, 0, 1, "", MNU_RARRIVAL_BEEP, "REMOTE AUDIBLE ALRT",MNU_FLAG, &param.remoteAudibleAlert, 0, 1, "", MNU_ARETURN_BEEP, "AUTO RETURN AUDIBLE",MNU_FLAG, &param.areturn_arrive_alert, 0, 1, "", MNU_VISUAL_ALERT, "MAIN VISUAL ALERT", MNU_FLAG, &param.mainVisualAlert, 0, 1, "", MNU_ALARM_SOUND, "SILENCE ALARM", MNU_FLAG, &alarm_silenced_flag, 0, 0, "", MNU_PURGE, "MANUAL PURGE", MNU_OTHR, &NOch, 0, 0, "", MNU_ALARM_RESET, "RESET ALARM", MNU_OTHR, &NOch, 0, 0, "", MNU_SETACTIVEMAIN, "SET ACTIVE MAIN", MNU_OTHR, &activeMainHere, 0, 0, "", MNU_SET_CLOCK, "SET CLOCK", MNU_CLK, &NOch, 0, 0, "", MNU_COMM_STAT, "SHOW COMMUNICATIONS",MNU_OTHR, &NOch, 0, 0, "", MNU_MSTACKING, "STACK AT MAIN", MNU_FLAG, &param.stacking_ok[0], 0, 1, "", MNU_RSTACKING, "STACK AT REMOTES", MNU_FLAG, &param.stacking_ok[1], 0, 1, "", MNU_RESET_COUNT, "SET TRANS COUNT", MNU_OTHR, &NOch, 0, 0, "", MNU_SET_STANAMES, "SET STATION NAMES", MNU_OTHR, &NOch, 0, 0, "", MNU_SET_PHONENUMS, "SET PHONE NUMBERS", MNU_OTHR, &NOch, 0, 0, "", MNU_DIVERTER_CFG, "USE LOCAL DIVERTER", MNU_FLAG, &param.localDiverter, 0, 1, "", MNU_SETPASSWORD, "SET PASSWORD", MNU_OTHR, &NOch, 0, 0, "", MNU_CLEARPASSWORDS, "CLEAR PASSWORDS", MNU_OTHR, &NOch, 0, 0, "", MNU_SETTIMEOUT, "DELIVERY TIMEOUT", MNU_VAL, (char *)&param.deliveryTimeout, 10, 240, "SEC", MNU_HEADDIVERTER, "USE HEAD DIVERTER", MNU_FLAG, &param.headDiverter, 0, 1, "", MNU_AUTO_PURGE, "AUTOMATIC PURGE", MNU_OTHR, &NOch, 0, 0, "", MNU_AUTOPUR_TIMER, "AUTO PURGE TIMER", MNU_VAL, (char *)&param.autoPurgeTimer, 10, 200, "SEC", MNU_SETASSLAVE, "SET AS SLAVE DEVICE",MNU_FLAG, &param.slaveController, 0, 1, "", MNU_DEF_STATIONS, "SET ACTIVE STATIONS",MNU_OTHR, &NOch, 0, 0, "", MNU_ADVANCED_SETUP, "Only in old menu", MNU_FLAG, &diagnostic_mode, 0, 0, "", MNU_RESET, "RESTART SYSTEM", MNU_OTHR, &NOch, 0, 0, "", MNU_ADMIN_FEATURES, "ADMIN FEATURES", MNU_OTHR, &NOch, 0, 0, "", MNU_MAINT_FEATURES, "MAINT FEATURES", MNU_OTHR, &NOch, 0, 0, "", MNU_SYSTEM_CONFIG, "SYSTEM CONFIG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_LOGS, "VIEW LOGS", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_TLOG, "VIEW TRANSACTIONS", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_SLOG, "VIEW SUMMARY LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_ELOG, "VIEW EVENT LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_VIEW_ALOG, "VIEW RECENT ALARMS", MNU_OTHR, &NOch, 0, 0, "", MNU_AUTO_RETURN, "AUTO RETURN TIMER", MNU_VAL, (char *)&param.autoReturnTimer, 0, 60, "MIN", MNU_DNLD_TLOG, "DOWNLOAD TRANS LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_UPLD_TLOG, "UPLOAD TRANS LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_CHECK_SFLASH, "CHECK SERIAL FLASH", MNU_OTHR, &NOch, 0, 0, "", MNU_ANALYZE_LOG, "ANALYZE EVENT LOG", MNU_OTHR, &NOch, 0, 0, "", MNU_SUBSTA_ADDR, "SUB-STA ADDRESSING", MNU_FLAG, &param.subStaAddressing, 0, 1, "", MNU_BLOWER_TYPE, "SET BLOWER TYPE", MNU_OTHR, &param.blowerType, 0, 0, "", MNU_PORT_MAPPING, "SET PORT MAPPING", MNU_OTHR, &NOch, 0, 0, "", MNU_LCD_CALIBRATE, "CALIBRATE SCREEN", MNU_OTHR, &NOch, 0, 0, "", MNU_SET_SYSNUM, "SET SYSTEM NUMBER", MNU_VAL, &param.systemNum, 1, 20, "", MNU_SHOW_IPADDR, "SHOW IP ADDRESS", MNU_OTHR, &NOch, 0, 0, "", MNU_SECURE_SETUP, "SETUP SECURE TRANS", MNU_OTHR, &NOch, 0, 0, "", MNU_SECURE_ENABLE, "ENABLE SECURE TRANS",MNU_FLAG, &param.secureEnabled, 0, 1, "", MNU_CARDID_ENABLE, "ENABLE CARD CHECK", MNU_FLAG, &param.cardCheckEnabled, 0, 1, "", MNU_SERVER_ADDRESS, "SERVER ADDRESS", MNU_OTHR, &NOch, 0, 0, "", MNU_SYNC_INTERVAL, "SYNC INTERVAL", MNU_VAL, &param.syncInterval, 0, 255, "MIN", // MNU_SECURE_R9MAX, "CARD1 RIGHT 9 MAX", MNU_VAL, (char *)&param.cardR9Max, 200000000, 618000000, "ID", // MNU_SECURE2_L3DIGITS,"CARD2 LEFT 3 DIGITS",MNU_VAL, &param.card2L3Digits, 155, 155, "ID", // MNU_SECURE2_R9MIN, "CARD2 RIGHT 9 MIN", MNU_VAL, (char *)&param.card2R9Min, 000000000, 999999999, "ID", // MNU_SECURE2_R9MAX, "CARD2 RIGHT 9 MAX", MNU_VAL, (char *)&param.card2R9Max, 000000000, 999999999, "ID", MNU_SHOW_INPUTS, "SHOW INPUTS", MNU_OTHR, &NOch, 0, 0, "", MNU_TUBE_DRYER, "RUN TUBE DRYER", MNU_OTHR, &NOch, 0, 0, "", MNU_ENAB_DRYER_OPT, "ENABLE TUBE DRYER", MNU_FLAG, &param.enableTubeDryOpt, 0, 1, "", MNU_RESYNC_USERS, "SYNCHRONIZE USERS", MNU_OTHR, &NOch, 0, 0, "", MNU_CHECK_SVR_NOW, "CHECK SERVER NOW", MNU_OTHR, &NOch, 0, 0, "", MNU_LAST, "END", MNU_NONE, &NOch, 0, 0, "" }; char menuOrder[25]; void setupMenuOrder(char menuLevel) { char i; i=0; // content of menu depends on if passwords are enabled or not switch (menuLevel) { case 0: // ALARM menuOrder[i++]=MNU_ALARM_SOUND; menuOrder[i++]=MNU_PURGE; menuOrder[i++]=MNU_ALARM_RESET; break; case 1: // Basic User if ((slaveAvailable || param.slaveController) && (param.subStaAddressing==FALSE)) menuOrder[i++]=MNU_SETACTIVEMAIN; menuOrder[i++]=MNU_AUTO_PURGE; menuOrder[i++]=MNU_PURGE; menuOrder[i++]=MNU_VIEW_LOGS; if (param.slaveController == 0) { // these menu items not allowed at slave menuOrder[i++]=MNU_ADMIN_FEATURES; menuOrder[i++]=MNU_MAINT_FEATURES; } menuOrder[i++]=MNU_SYSTEM_CONFIG; break; case 2: // Administrator if (param.enableTubeDryOpt) menuOrder[i++]=MNU_TUBE_DRYER; menuOrder[i++]=MNU_MARRIVAL_BEEP; menuOrder[i++]=MNU_VISUAL_ALERT; menuOrder[i++]=MNU_RARRIVAL_BEEP; menuOrder[i++]=MNU_ARETURN_BEEP; menuOrder[i++]=MNU_MSTACKING; menuOrder[i++]=MNU_RSTACKING; menuOrder[i++]=MNU_AUTOPUR_TIMER; menuOrder[i++]=MNU_AUTO_RETURN; menuOrder[i++]=MNU_DNLD_TLOG; menuOrder[i++]=MNU_UPLD_TLOG; menuOrder[i++]=MNU_SET_CLOCK; menuOrder[i++]=MNU_RESET_COUNT; menuOrder[i++]=MNU_SET_STANAMES; menuOrder[i++]=MNU_SET_PHONENUMS; menuOrder[i++]=MNU_SETPASSWORD; break; case 3: // Maintenance menuOrder[i++]=MNU_SETTIMEOUT; menuOrder[i++]=MNU_AUTO_PURGE; menuOrder[i++]=MNU_PURGE; menuOrder[i++]=MNU_CHECK_SVR_NOW; menuOrder[i++]=MNU_SETPASSWORD; //menuOrder[i++]=MNU_DIV_TIMEOUT; //menuOrder[i++]=MNU_LIFT_TIMEOUT; break; case 4: // System configuration (Colombo only) menuOrder[i++]=MNU_ENAB_DRYER_OPT; menuOrder[i++]=MNU_DIVERTER_CFG; menuOrder[i++]=MNU_HEADDIVERTER; menuOrder[i++]=MNU_BLOWER_TYPE; //menuOrder[i++]=MNU_REMOTEDIVERTER; menuOrder[i++]=MNU_DEF_STATIONS; menuOrder[i++]=MNU_SET_SYSNUM; menuOrder[i++]=MNU_SETASSLAVE; menuOrder[i++]=MNU_SUBSTA_ADDR; menuOrder[i++]=MNU_SECURE_SETUP; menuOrder[i++]=MNU_PORT_MAPPING; menuOrder[i++]=MNU_SHOW_IPADDR; menuOrder[i++]=MNU_COMM_STAT; menuOrder[i++]=MNU_SETPASSWORD; menuOrder[i++]=MNU_CLEARPASSWORDS; menuOrder[i++]=MNU_CHECK_SFLASH; menuOrder[i++]=MNU_ANALYZE_LOG; menuOrder[i++]=MNU_LCD_CALIBRATE; menuOrder[i++]=MNU_SHOW_INPUTS; menuOrder[i++]=MNU_RESET; break; case 5: // view logs menuOrder[i++]=MNU_VIEW_SLOG; // transaction summary menuOrder[i++]=MNU_VIEW_TLOG; // transaction log //menuOrder[i++]=MNU_VIEW_ELOG; // event log menuOrder[i++]=MNU_VIEW_ALOG; // alarm log break; case 6: // secure card setup menuOrder[i++]=MNU_SECURE_ENABLE; menuOrder[i++]=MNU_CARDID_ENABLE; menuOrder[i++]=MNU_SERVER_ADDRESS; menuOrder[i++]=MNU_SYNC_INTERVAL; menuOrder[i++]=MNU_RESYNC_USERS; //menuOrder[i++]=MNU_SECURE_R9MAX; //menuOrder[i++]=MNU_SECURE2_L3DIGITS; //menuOrder[i++]=MNU_SECURE2_R9MIN; //menuOrder[i++]=MNU_SECURE2_R9MAX; break; } menuOrder[i]=MNU_LAST; } #define PAGE_SIZE 5 const char * const title[7] = { "ALARM MENU", "MENU", "ADMIN MENU", "MAINTENANCE MENU", "CONFIGURATION MENU", "LOGS MENU","SECURE TRANS MENU" }; char lcd_ShowMenu(char menuLevel, char page) { // returns if a next page is available char i, j; char rtnval; int row, count, button; char ttl; rtnval=TRUE; setupMenuOrder(menuLevel); ttl = (menuLevel<7) ? menuLevel : 0; // which title to show lcd_drawScreen(2,title[ttl]); // show the screen & title // make sure we can handle the page size if (page >= 1) { i = page * PAGE_SIZE; // count backwards and reduce i if needed for (j=i; j>0; j--) if (menuOrder[j]==MNU_LAST) i=j-1; } else i=0; count=0; lcd_Font("16B"); while ((menuOrder[i] != MNU_LAST) && (count < PAGE_SIZE)) { row = 47 + count*30; // put up text //lcd_DispText(sys_message[menu[menuOrder[i]].msg1].msg, row, 50, MODE_TRANS); // put up button lcd_ButtonDef( BTN_MNU_FIRST+menuOrder[i], // menu items at 21+ BTN_MOM, // momentary operation BTN_TLXY, 40, row, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 315, BTN_TEXT, menu[menuOrder[i]].msg1, BTN_TXTOFFSET, 10, 6, BTN_BMP, BMP_long_button, BMP_long_button_dn, BTN_END ); i++; count++; } // show page # at the bottom j=0; while (menuOrder[j] != MNU_LAST) j++; count = ((j-1) / PAGE_SIZE) + 1; lcd_showPage(page+1, count); // is there another page to show? //if ( (menuOrder[i] == MNU_LAST) || (menuOrder[i+1] == MNU_LAST) ) rtnval=FALSE; if ( (menuOrder[i] == MNU_LAST) ) rtnval=FALSE; return rtnval; } char lcd_ProcessMenuItem(char menu_idx, char *menu_level) { // can modify menu_level using advanced configuration menu item // returns true if a flash parameter changed unsigned long clock_in_seconds; char work; char maxDigits; unsigned long temp_ulong; static char parChanged; parChanged=FALSE; // assume not switch (menu[menu_idx].partype) { case MNU_VAL: //lcd_drawScreen(4);sys_message[menu[menuOrder[i]].msg1].msg if (menu[menu_idx].max > 999) { // unsigned long data type maxDigits = 9; // 9 digits max temp_ulong = *(unsigned long*)menu[menu_idx].parval; // type is ulong } else { // character data type maxDigits = 3; // only 3 digits max temp_ulong = *menu[menu_idx].parval; // type is character } if (lcd_GetNumberEntry(menu[menu_idx].msg1, &temp_ulong, menu[menu_idx].min, menu[menu_idx].max, menu[menu_idx].units, maxDigits, 0)) { if (menu[menu_idx].max > 999) // cast unsigned long *(unsigned long*)menu[menu_idx].parval = temp_ulong; else // cast character *menu[menu_idx].parval = (char)temp_ulong; parChanged=TRUE; } break; case MNU_FLAG: parChanged=lcd_SelectChoice(menu[menu_idx].parval, menu[menu_idx].msg1, "YES", "NO"); // Some flags don't require parameters to be saved (when max=0); if (menu[menu_idx].max == 0) parChanged=0; // Don't save parameter change to flash if (menu[menu_idx].item == MNU_ALARM_SOUND) alarm(ON); // update alarm if needed break; case MNU_TIME: //ptr_ulong = (unsigned long *)menu[menu_idx].parval; //par_changed |= functionSetTime(menu[menu_idx].item, menu_idx, ptr_ulong); break; case MNU_CLK: lcd_setClock(); //clock_in_seconds = SEC_TIMER; syncDateAndTime(); // send to slave break; case MNU_OTHR: switch (menu[menu_idx].item) { case MNU_SERVER_ADDRESS: parChanged = lcd_editServerName(); break; case MNU_CHECK_SVR_NOW: pingTimer = SEC_TIMER - 1; // force check now *menu_level=99; // exit menu break; case MNU_RESYNC_USERS: work=FALSE; lcd_SelectChoice(&work, menu[menu_idx].msg1, "YES", "NO"); if (work) { // yes please resync UID_ResyncAll(); } *menu_level=99; // exit menu break; case MNU_ADMIN_FEATURES: // get pin for next menu level if (lcd_enableAdvancedFeatures(2, menu[menu_idx].msg1)) *menu_level=2; break; case MNU_MAINT_FEATURES: // get pin for next menu level if (lcd_enableAdvancedFeatures(3, menu[menu_idx].msg1)) *menu_level=3; break; case MNU_SYSTEM_CONFIG: // get pin for next menu level if (lcd_enableAdvancedFeatures(4, menu[menu_idx].msg1)) *menu_level=4; break; case MNU_VIEW_LOGS: *menu_level=5; // Logs menu items break; case MNU_SECURE_SETUP: *menu_level=6; // Secure card setup items break; case MNU_BLOWER_TYPE: if (*menu[menu_idx].parval==blwrType_STD) work=TRUE; else work=FALSE; parChanged=lcd_SelectChoice(&work, menu[menu_idx].msg1, "STD", "APU"); if (parChanged) *menu[menu_idx].parval = work ? blwrType_STD : blwrType_APU; break; case MNU_ALARM_RESET: // alarm reset work=FALSE; lcd_SelectChoice(&work, menu[menu_idx].msg1, "YES", "NO"); if (work) { // yes please reset, added here to make sure alarm goes off at slave system_state=CANCEL_STATE; alarm(OFF); } *menu_level=99; // exit menu break; case MNU_SETACTIVEMAIN: lcd_SelectChoice(menu[menu_idx].parval, menu[menu_idx].msg1, param.station_name[0].name, param.station_name[SLAVE].name); setActiveMain(*menu[menu_idx].parval); break; case MNU_PURGE: // purge system purgeSystem(PURGE_MANUAL); // 0 = manual; 1 = auto break; case MNU_AUTO_PURGE: // purge system purgeSystem(PURGE_AUTOMATIC); // 0 = manual; 1 = auto break; case MNU_TUBE_DRYER: // purge system purgeSystem(PURGE_DRYING); // 2 = tube drying break; case MNU_RESET_COUNT: maxDigits=6; temp_ulong = transactionCount(); if (lcd_GetNumberEntry(menu[menu_idx].msg1, &temp_ulong, 0, 999999, menu[menu_idx].units, maxDigits, 0)) resetTransactionCount(temp_ulong); break; case MNU_SET_STANAMES: // set station names parChanged=lcd_editStationNames(); if (parChanged) setActiveMainMsg(); // reset rcv @ message if needed break; case MNU_SET_PHONENUMS: // set phone numbers parChanged=lcd_editPhoneNums(); break; case MNU_PORT_MAPPING: // define the remote port/station mapping parChanged=lcd_editPortMapping(menu[menu_idx].msg1); break; case MNU_DEF_STATIONS: // define active stations parChanged=lcd_defineActiveStations(); break; case MNU_SETPASSWORD: // set new password // get the PIN for the given menu level if (*menu_level==2) parChanged |= lcd_getPin(param.adminPassword, "SET ADMIN PASSWORD"); else if (*menu_level==3) parChanged |= lcd_getPin(param.maintPassword, "SET MAINT PASSWORD"); else if (*menu_level==4) parChanged |= lcd_getPin(param.cfgPassword, "SET CONFIG PASSWORD"); break; case MNU_CLEARPASSWORDS: // reset passwords param.adminPassword[0]=0; param.maintPassword[0]=0; // param.cfgPassword[0]=0; // SHOULD NOT BE NECESSARY parChanged=TRUE; break; case MNU_COMM_STAT: show_comm_test(1); // wait for button press break; case MNU_VIEW_SLOG: lcd_showTransSummary(); break; case MNU_VIEW_TLOG: lcd_showTransactions(0); break; case MNU_VIEW_ALOG: lcd_showTransactions(1); break; case MNU_DNLD_TLOG: // how many days of the log should be downloaded? temp_ulong=0; if (lcd_GetNumberEntry("DOWNLOAD LOG, Last", &temp_ulong, 0, 9999, "Days", 4, 1)) { // Download last x days of the log if (temp_ulong == 0) temp_ulong = 9999; // essentially the whole log downloadTransLog((int)temp_ulong); } break; case MNU_UPLD_TLOG: uploadTransLog(); break; case MNU_CHECK_SFLASH: checkSerialFlash(); break; case MNU_ANALYZE_LOG: analyzeEventLog(); break; case MNU_LCD_CALIBRATE: lcd_Calibrate(); while ( lcd_Origin(0,0) != lcd_SUCCESS ) msDelay(1000); // wait for done calibrate break; case MNU_SHOW_IPADDR: show_ip_address(); break; case MNU_SHOW_INPUTS: lcd_show_inputs(); break; case MNU_RESET: // go into long loop to allow watchdog reset clock_in_seconds = SEC_TIMER; lcd_drawScreen(3, menu[menu_idx].msg1); lcd_Font("24"); lcd_DispText("SYSTEM RESTARTING", 50, 85, MODE_NORMAL); #asm ipset 3 ; disable interrupts so that the periodic ISR doesn't hit the watchdog. ld a,0x53 ; set the WD timeout period to 250 ms ioi ld (WDTCR),a #endasm while (SEC_TIMER - clock_in_seconds < 5); lcd_DispText("UNABLE TO RESET", 50, 115, MODE_NORMAL); msDelay(1000); break; } } return parChanged; } /******************************************************************/ void setActiveMain(char setToMaster) { if (setToMaster) param.activeMain = MASTER; else param.activeMain = SLAVE; if (param.slaveController) { // set flag to send new status if (param.activeMain==MASTER) slaveReturnStatus |= 0x04; else slaveReturnStatus |= 0x02; } setActiveMainMsg(); } void setActiveMainMsg() { // setup active main message shown on lcd char i; char mybuf[20]; char start; // Only show Rcv@ if slave detected and sub station addressing is off if ((slaveAvailable || param.slaveController) && (param.subStaAddressing==FALSE)) { //strcpy(sys_message[MSG_SDEFAULT2].msg, " RCV @ "); strcpy(mybuf, "RCV @ "); if (param.activeMain == MASTER) strncat(mybuf, param.station_name[0].name,10); else strncat(mybuf, param.station_name[8].name,10); // center message start = (MSG_LEN - strlen(mybuf)) / 2; // place in destination // leading spaces for (i=0; i<start; i++) sys_message[MSG_SDEFAULT2].msg[i]=32; // message for (i=0; i<strlen(mybuf); i++) sys_message[MSG_SDEFAULT2].msg[i+start]=mybuf[i]; // trailing spaces for (i=start+strlen(mybuf); i<MSG_LEN; i++) sys_message[MSG_SDEFAULT2].msg[i]=32; // end of string sys_message[MSG_SDEFAULT2].msg[MSG_LEN]=0; } else { // go back to system startup default strcpy(sys_message[MSG_SDEFAULT2].msg, sysmsg[MSG_SDEFAULT2]); } } /******************************************************************/ // set clock functions char functionSetTime(char what_timer, char index, unsigned long *time_val) { // what_timer is the base menu item } char functionSetParValue(char menu_item, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units) { // allow changing an unsigned long parameter value } /******************************************************************/ // define purge system states #define PURGE_ARE_YOU_SURE 0x20 #define PURGE_GET_DIRECTION 0x21 #define PURGE_GET_STATION 0x22 #define PURGE_SET_DIVERTER 0x23 #define PURGE_WAIT_DIVERTER 0x24 #define PURGE_RUN 0x25 #define PURGE_GET_HEADDIVERTER 0X26 #define PURGE_RUN_DONE 0x27 #define PURGE_RUN_AUTO 0x28 #define PURGE_RUN_DRYING 0x29 #define PURGE_EXIT 0x30 void purgeSystem(char purge_mode) { // Input parameter purge_mode is manual (0) or automatic (1) or tube drying (2) // Definitions for calling are PURGE_MANUAL, PURGE_AUTOMATIC, PURGE_DRYING struct iomessage command, response; char purge_state, new_state, k, station_msg; char mymessage[17]; char i; // loop counter char remote_data_p[4]; char first_time_here; char align_headdiverter; char blower_purge_state; // used to tell headdiverter blower what to do char first_purge_state; // initial state of the purge mode char auto_station; char auto_blower; char MSG_direction; // to indicate if auto purge is TO or FROM station char title[15]; int button; // from color lcd int col; unsigned long ms_autoPurgeTimer; ms_autoPurgeTimer = param.autoPurgeTimer * 1000ul; // convert seconds to milliseconds echoLcdToTouchscreen=FALSE; // Touchscreen has own messages, don't echo from lcd eventlog.start_tm=SEC_TIMER; // if auto purge, build up for control loop auto_station = 1; // set first auto purge station state_timer=MS_TIMER; if (purge_mode==PURGE_AUTOMATIC) { // eventlog.status=ESTS_AUTOPURGE; //first_purge_state=PURGE_SET_DIVERTER; first_purge_state=PURGE_ARE_YOU_SURE; // operation depends on headdiverter config if (param.headDiverter==TRUE) { auto_blower=blwrPRS; // always use pressure MSG_direction=MSG_TO; align_headdiverter=1; // align main systemStation=0; // no remote station systemStationb=0; system_direction=DIR_SEND; } else { auto_blower=blwrVAC; // always use vacuum MSG_direction=MSG_FROM; align_headdiverter=0; // no headdiverter systemStationb=firstBit(STATION_SET); systemStation=bit2station(systemStationb); system_direction=DIR_RETURN; } strcpy(title, "AUTO PURGE"); } else if (purge_mode==PURGE_DRYING) { eventlog.status=ESTS_MANPURGE; // set entry state based on if headdiverter is used if (param.headDiverter==TRUE) first_purge_state=PURGE_GET_HEADDIVERTER; else first_purge_state=PURGE_GET_STATION; MSG_direction=MSG_FROM; system_direction = DIR_SEND; // undefined align_headdiverter = 2; // undefined (align remote) strcpy(title, "RUN TUBE DRYER"); // 14 characters max } else // must be PURGE_MANUAL { eventlog.status=ESTS_MANPURGE; // set entry state based on if headdiverter is used if (param.headDiverter==TRUE) first_purge_state=PURGE_GET_HEADDIVERTER; else first_purge_state=PURGE_GET_STATION; system_direction = DIR_SEND; // undefined align_headdiverter = 2; // undefined (align remote) strcpy(title, "PURGE"); } purge_state = first_purge_state; new_state = purge_state; blower_purge_state = IDLE_STATE; // remote blower idle first_time_here = TRUE; // use to show state message once per state change station_msg = 1; // anything //eventlog.source_sta eventlog.dest_sta=0; // initial dest eventlog.flags=0; // initial dest(s) inUse(FLASH, STATION_SET); // send command to tell remotes command.devAddr=ALL_DEVICES; command.command=SET_OUTPUTS; command.station=systemStation; command.data[devInUseSolid]=0; command.data[devInUseFlash]=0; command.data[devAlert]=0; command.data[devAlarm]=1; // 1=purge send_command(command); // display initial messages //if (purge_mode) message_add(TRANSLCD, MSG_FUNCTION, MSG_AUTO_PURGE, ONESHOTA); //else message_add(TRANSLCD, MSG_FUNCTION, MSG_PURGE, ONESHOTA); //message_add(SYSTEMLCD, MSG_BLANK, MSG_BLANK, ONESHOT); // Setup color lcd display and buttons lcd_drawScreen(5, title); lcd_Font("24"); while ((purge_state != PURGE_EXIT) && !secTimeout(menu_timeout) ) { hitwd(); // hit the watchdog timer showactivity(); check_diverter(); processBlower(); button = lcd_GetTouch(10); // Exit anytime FUNC is triggered // except in PURGE_RUN then go back to first_purge_state (through PURGE_RUN_DONE) // if (functionButton(FUNC_BUTT, FUNC_TRIG)) if (button == BTN_EXIT) { //if (headDiverter==TRUE && purge_state==PURGE_GET_DIRECTION) if (purge_state==PURGE_RUN) new_state=PURGE_RUN_DONE; else new_state=PURGE_EXIT; } // Exit anytime anything is pressed in auto purge or tube dry if (purge_mode==PURGE_AUTOMATIC || purge_mode==PURGE_DRYING) // check for cancel of auto purge { if ( di_requestToSend || (button == BTN_CANCEL) || (button == BTN_EXIT) ) { new_state=PURGE_EXIT; purge_state=PURGE_EXIT; // Force in right away } } // enter local loop to process purge switch (purge_state) { case PURGE_ARE_YOU_SURE: if (first_time_here==TRUE) { // show Start button lcd_Font("16B"); lcd_ButtonDef( 1, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Start", BTN_TXTOFFSET, 9, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // show message prompt lcd_DispText("PRESS START BUTTON TO BEGIN", 50, 50, MODE_NORMAL); lcd_Font("24"); } if (button==1) new_state=PURGE_SET_DIVERTER; break; case PURGE_GET_HEADDIVERTER: // get headdiverter alignment if (first_time_here==TRUE) { strcpy(mymessage, "(+) TO "); for (k=0; k<strlen(param.station_name[0].name); k++) { mymessage[k+8]=param.station_name[0].name[k]; } //lcd_print(SYSTEMLCD, 0, mymessage); //lcd_print(SYSTEMLCD, 1, "(-) TO REMOTE "); lcd_drawScreen(5, title); lcd_DispText("SETUP DIVERTER", 50, 50, MODE_NORMAL); lcd_DispText(ltrim(sys_message[MSG_TO].msg), 140, 90, MODE_NORMAL); lcd_ButtonDef( 1, BTN_MOM, // momentary operation BTN_TLXY, 100, 85, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 315, // set left and right margins BTN_SEP, 35, 35, // set up for button sep BTN_TEXT, "", BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); lcd_DispText("TO SUB STATION", 140, 125, MODE_NORMAL); lcd_ButtonDef( 2, BTN_TLXY, 100, 120, // starting x,y for buttons BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); if ((slaveAvailable) || (param.slaveController)) { lcd_DispText(ltrim(sys_message[MSG_TO+SLAVE].msg), 140, 160, MODE_NORMAL); lcd_ButtonDef( 3, BTN_TLXY, 100, 155, // starting x,y for buttons BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); } } // TO MAIN if (button == 1) { new_state=PURGE_SET_DIVERTER; align_headdiverter=1; // align main systemStation=0; // no remote station systemStationb=0; } // TO REMOTE if (button == 2) { new_state=PURGE_GET_STATION; align_headdiverter=2; // align remote } // TO SLAVE if (button == 3) { new_state=PURGE_SET_DIVERTER; align_headdiverter=3; // align slave systemStation=0; // no remote station systemStationb=0; } break; case PURGE_GET_STATION: // get station selection if (first_time_here==TRUE) { //lcd_print(SYSTEMLCD, 0, sys_message[MSG_SEL_STATION].msg); //lcd_print(SYSTEMLCD, 1, " TO PURGE "); lcd_drawScreen(5, title); lcd_DispText("SELECT STATION TO PURGE", 20, 50, MODE_NORMAL); // draw station buttons col=40; for (i=0; i<LAST_STATION; i++) { if ((1<<i) & STATION_SET) { mymessage[0]=49+i; mymessage[1]=0; lcd_ButtonDef( i, // station# - 1 BTN_MOM, // momentary operation BTN_TLXY, col, 90, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, mymessage, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); col+=40; } } } if (di_requestToSend & STATION_SET) { systemStation=firstBit(di_requestToSend & STATION_SET); systemStationb=station2bit(systemStation); new_state=PURGE_SET_DIVERTER; } if ((button >= 0) && (button < LAST_STATION)) { systemStation = firstBit((1<<button) & STATION_SET); systemStationb=station2bit(systemStation); new_state=PURGE_SET_DIVERTER; } break; case PURGE_SET_DIVERTER: // set diverter and continue if (first_time_here==TRUE) { //message_add(TRANSLCD, MSG_FUNCTION, MSG_PURGE, ONESHOTA); //message_add(SYSTEMLCD, MSG_SETTING, MSG_TO+systemStation, ONESHOT); //lcd_print(SYSTEMLCD, 0, sys_message[MSG_SETTING].msg); //lcd_print(SYSTEMLCD, 1, sys_message[MSG_TO+systemStation].msg); lcd_drawScreen(5, title); lcd_DispText(ltrim(sys_message[MSG_SETTING].msg), 50, 50, MODE_NORMAL); if (align_headdiverter==1) // align main lcd_DispText(ltrim(sys_message[MSG_TO].msg), 50, 80, MODE_NORMAL); else if (align_headdiverter==3) // align slave lcd_DispText(ltrim(sys_message[MSG_TO+SLAVE].msg), 50, 80, MODE_NORMAL); else lcd_DispText(ltrim(sys_message[MSG_TO+systemStation].msg), 50, 80, MODE_NORMAL); state_timer=MS_TIMER; } // Stay in this state until diverter command received set_diverter(systemStation); command.devAddr=ALL_DEVICES; command.command=SET_DIVERTER; command.station=systemStation; command.data[0]=align_headdiverter; command.data[1]=0; // mainStation command.data[2]=param.subStaAddressing; command.data[3]=param.blowerType; // P2P WORK TO BE DONE HERE if (send_command(command)) new_state=PURGE_WAIT_DIVERTER; break; case PURGE_WAIT_DIVERTER: // no additional messages to show here if (MS_TIMER-state_timer >= DIVERTER_TIMEOUT) { // timeout //lcd_print(SYSTEMLCD, 1, sys_message[MSG_TIMEOUT].msg); lcd_DispText(sys_message[MSG_TIMEOUT].msg, 30, 180, MODE_NORMAL); sprintf(mymessage, "STATUS = %x", diverter_status); lcd_DispText(mymessage, 0, 0, MODE_NORMAL); // just wait for exit key //new_state=PURGE_EXIT; } // Stay in this state until diverter in position msDelay(10); if (divertersReady(systemStation, align_headdiverter, 0)) { station_msg = MSG_TO + systemStation; if (purge_mode==PURGE_AUTOMATIC) new_state=PURGE_RUN_AUTO; else if (purge_mode==PURGE_DRYING) new_state=PURGE_RUN_DRYING; else new_state=PURGE_RUN; } break; case PURGE_RUN: // capture the station being purged in the event log if (eventlog.dest_sta==0) eventlog.dest_sta=systemStation; // first destination recorded eventlog.flags |= systemStationb; // capture any destination selected if (first_time_here==TRUE) { //message_add(TRANSLCD, MSG_FUNCTION, MSG_PURGE, ONESHOTA); //message_add(SYSTEMLCD, station_msg, MSG_BLANK, ONESHOT); // lcd_print(SYSTEMLCD, 0, " F1=PRS F2=VAC "); //lcd_print(SYSTEMLCD, 0, "(+)=PRS (-)=VAC "); //lcd_print(SYSTEMLCD, 1, sys_message[MSG_BLANK].msg); lcd_drawScreen(5, title); lcd_DispText("PRESS BUTTONS TO OPERATE BLOWER", 32, 50, MODE_NORMAL); if (align_headdiverter==1) // align main lcd_DispText(ltrim(sys_message[MSG_TO].msg), 62, 75, MODE_NORMAL); else if (align_headdiverter==3) // align slave lcd_DispText(ltrim(sys_message[MSG_TO+SLAVE].msg), 62, 75, MODE_NORMAL); else lcd_DispText(ltrim(sys_message[MSG_TO+systemStation].msg), 62, 75, MODE_NORMAL); lcd_DispText("PRESSURE", 140, 110, MODE_NORMAL); lcd_ButtonDef( 3, BTN_LAT, // momentary operation BTN_TLXY, 100, 103, // starting x,y for buttons BTN_TYPE, BUTTON_LAT_0, BTN_MARGINS, 5, 315, // set left and right margins BTN_SEP, 35, 35, // set up for button sep BTN_TEXT, "","", BTN_BMP, BMP_button_off, BMP_button_on, BTN_END ); lcd_DispText("VACUUM", 140, 147, MODE_NORMAL); lcd_ButtonDef( 4, BTN_TLXY, 100, 140, // starting x,y for buttons BTN_BMP, BMP_button_off, BMP_button_on, BTN_END ); //lcd_DispBitmap(BMP_LEDOFF, } // Pressure // if (functionButton(FUNC_F1, FUNC_CURR)) if (button%256==3) { if ((blower_purge_state != WAIT_FOR_REM_ARRIVE) || (button==259)) { blower_purge_state = WAIT_FOR_REM_ARRIVE; // always pressure blower(blwrPRS); //lcd_print(SYSTEMLCD, 1, " PRESSURE "); //lcd_DispText("PRESSURE", 120, 155, MODE_NORMAL); lcd_SetState( 4, 0 ); // make sure vacuum button is off system_direction=DIR_SEND; } // NEW to toggle on each key press else { blower_purge_state=IDLE_STATE; blower(blwrIDLE); //lcd_print(SYSTEMLCD, 1, sys_message[MSG_BLANK].msg); //lcd_DispText(" ", 120, 155, MODE_NORMAL); } menu_timeout = SEC_TIMER + 60 * param.manPurgeTimeout; // 5 min timeout while purging } // Vacuum // else if (functionButton(FUNC_F2, FUNC_CURR)) else if (button%256==4) { if ((blower_purge_state != WAIT_FOR_REM_DEPART) || (button==260)) { blower_purge_state = WAIT_FOR_REM_DEPART; // always vacuum blower(blwrVAC); //lcd_print(SYSTEMLCD, 1, " VACUUM "); //lcd_DispText("VACUUM ", 120, 155, MODE_NORMAL); lcd_SetState( 3, 0 ); // make sure pressure button is off system_direction=DIR_RETURN; } // NEW to toggle on each key press else { blower_purge_state=IDLE_STATE; blower(blwrIDLE); //lcd_print(SYSTEMLCD, 1, sys_message[MSG_BLANK].msg); //lcd_DispText(" ", 120, 155, MODE_NORMAL); } menu_timeout = SEC_TIMER + 60 * param.manPurgeTimeout; // 5 min timeout while purging } // show message if arrival at headdiverter if ((remote_data_p[REMOTE_ARRIVE] & HEADDIVERTERSTATION) && (system_direction==DIR_RETURN)) { //lcd_print(SYSTEMLCD, 1, "CARRIER @ BLOWER"); lcd_DispText("CARRIER @ BLOWER", 120, 180, MODE_NORMAL); } break; case PURGE_RUN_AUTO: // wait for auto purge duration then go to the next station if (first_time_here==TRUE) { blower(auto_blower); if (auto_blower == blwrPRS) blower_purge_state = WAIT_FOR_REM_ARRIVE; else blower_purge_state = WAIT_FOR_REM_DEPART; //lcd_print(SYSTEMLCD, 0, " PURGING "); //lcd_print(SYSTEMLCD, 1, sys_message[station_msg].msg); lcd_clearMiddle(); lcd_DispText("PURGING ", 20, 50, MODE_NORMAL); //lcd_DispText(ltrim(sys_message[MSG_TO+systemStation].msg), 0, 0, MODE_NORMAL); if (align_headdiverter==3) // align slave lcd_DispText(ltrim(sys_message[MSG_direction+SLAVE].msg), 0, 0, MODE_NORMAL); else lcd_DispText(ltrim(sys_message[MSG_direction+systemStation].msg), 0, 0, MODE_NORMAL); } menu_timeout = SEC_TIMER + 60; // Don't timeout while purging if (MS_TIMER-state_timer > ms_autoPurgeTimer) { // turn off blower blower(blwrIDLE); // Always turn off the blower when leaving ... just in case. blower_purge_state=IDLE_STATE; // go to the next station if ((align_headdiverter==1) && (slaveAvailable || param.slaveController)) { align_headdiverter=3; // align slave } else { systemStation++; align_headdiverter=2; // align remote // make sure its an active station while ( ((station2bit(systemStation) & STATION_SET)==0) && (systemStation < 8) ) systemStation++; } // set the next state if (systemStation >= 8) new_state=PURGE_EXIT; else { new_state = PURGE_SET_DIVERTER; systemStationb = station2bit(systemStation); } } break; case PURGE_RUN_DRYING: // wait indefinitely until a key is pressed // wait for auto purge duration then go to the next station if (first_time_here==TRUE) { blower(blwrVAC); blower_purge_state = WAIT_FOR_REM_DEPART; system_direction=DIR_RETURN; lcd_clearMiddle(); lcd_DispText("DRYING ", 20, 50, MODE_NORMAL); if (align_headdiverter==3) // align slave lcd_DispText(ltrim(sys_message[MSG_direction+SLAVE].msg), 0, 0, MODE_NORMAL); else lcd_DispText(ltrim(sys_message[MSG_direction+systemStation].msg), 0, 0, MODE_NORMAL); lcd_DispText("Press Exit To Stop Drying", 20, 80, MODE_NORMAL); } menu_timeout = SEC_TIMER + 60; // Don't timeout while purging break; case PURGE_RUN_DONE: // used to force one time through loop for remote command of blower blower_purge_state=IDLE_STATE; blower(blwrIDLE); // go to next state after one extra time through ... to set blowers properly if (first_time_here!=TRUE) new_state=first_purge_state; break; case PURGE_EXIT: // leaving purge here blower(blwrIDLE); // Always turn off the blower when leaving ... just in case. blower_purge_state=IDLE_STATE; break; default: new_state=PURGE_EXIT; break; } // end switch // check for purge state change if (purge_state != new_state) { first_time_here=TRUE; // wasn't here yet purge_state=new_state; // this is where to be state_timer=MS_TIMER; } else first_time_here=FALSE; // were already here // Check remote inputs only if processing PURGE_WAIT_DIVERTER or PURGE_RUN // or PURGE_RUN_DONE or PURGE_EXIT if ( (purge_state==PURGE_WAIT_DIVERTER) || (purge_state==PURGE_RUN) || (purge_state==PURGE_RUN_AUTO) || (purge_state==PURGE_RUN_DRYING) || (purge_state==PURGE_RUN_DONE) || (purge_state==PURGE_EXIT) ) { // Add check for remote inputs in V2.34 for Up-Receive control // and now for headdiverter too command.devAddr=ALL_DEVICES; command.command=RETURN_INPUTS; command.station=0; command.data[0]=0; command.data[1]=blower_purge_state; // send blower state // command.data[2]=system_direction; // send diverter direction command.data[2]=outputvalue[devInUseSolid]; // was system_direction; command.data[3]=outputvalue[devInUseFlash]; command.data[4]=STATION_SET; msDelay(10); // P2P WORK TO BE DONE HERE if (send_n_get(command, &response)) { if (response.command==INPUTS_ARE) { // store remote response in local var for (k=0; k<4; k++) remote_data_p[k]=response.data[k]; // force unused doors closed (on) and other unused inputs off remote_data_p[REMOTE_DOOR] |= ~STATION_SET; remote_data_p[REMOTE_CIC] &= STATION_SET; remote_data_p[REMOTE_RTS] &= STATION_SET; } // end if } // end if } // end if } // end while inUse(OFF, STATION_SET); echoLcdToTouchscreen=TRUE; // Reenable echo of lcd to Touchscreen eventlog.duration=(int)(SEC_TIMER-eventlog.start_tm); addTransaction( eventlog, 0 ); // transaction resumed, log the event // send command to tell remotes command.devAddr=ALL_DEVICES; command.command=SET_OUTPUTS; command.station=systemStation; command.data[devInUseSolid]=0; command.data[devInUseFlash]=0; command.data[devAlert]=0; command.data[devAlarm]=0; // 1=purge send_command(command); } int readParameterSettings(void) { // Read the parameter block param int rtn_code; rtn_code = readUserBlock(&param, 0, sizeof(param)); if (rtn_code || (param.sysid != 63)) { // fault or parameters not initialized // set default parameters param.sysid=63; param.names_init=0; param.stacking_ok[0]=FALSE; param.stacking_ok[1]=FALSE; param.remoteAudibleAlert=TRUE; param.localDiverter=FALSE; // local diverter configuration param.activeStations=1; // active station set param.autoPurgeTimer=10; // auto purge timer in seconds param.deliveryTimeout=60; // delivery timeout in seconds param.headDiverter=FALSE; param.pw_enabled=FALSE; param.slaveController=MASTER; // master (0) or slave (SLAVE) param.systemNum=1; } param.activeMain = MASTER; // always default to master return rtn_code; } int writeParameterSettings(void) { // Write the parameter block param int rtn_code; rtn_code = writeUserBlock(0, &param, sizeof(param)); return rtn_code; } int syncParametersToRemote(void) { // returns 0 if no error, non-zero otherwise int status, i; struct iomessage command; // First update card parameters command.command = SET_CARD_PARAMS; command.station = 0; command.devAddr = ALL_DEVICES; // Individual card checking command.data[0]=6; // Left 3 digits command.data[1]=param.cardCheckEnabled; send_command(command); msDelay(10); // Left 3 digits // command.data[0]=0; // Left 3 digits // command.data[1]=param.cardL3Digits; // send_command(command); // msDelay(10); // Right 9 minimum // command.data[0]=1; // Right 9 min // *(unsigned long *)&command.data[1] = param.cardR9Min; // send_command(command); // msDelay(10); // Right 9 maximum // command.data[0]=2; // Right 9 max // *(unsigned long *)&command.data[1] = param.cardR9Max; // send_command(command); // msDelay(10); //// SECOND CARD RANGE // Left 3 digits // command.data[0]=3; // Left 3 digits // command.data[1]=param.card2L3Digits; // send_command(command); // msDelay(10); // Right 9 minimum // command.data[0]=4; // Right 9 min // *(unsigned long *)&command.data[1] = param.card2R9Min; // send_command(command); // msDelay(10); // Right 9 maximum // command.data[0]=5; // Right 9 max // *(unsigned long *)&command.data[1] = param.card2R9Max; // send_command(command); // msDelay(10); // send command to remote to update and save other parameters command.command=SET_PARAMETERS; command.station=0; status=0; // assume none good for (i=FIRST_DEVADDR; i<=LAST_DEVADDR; i++) { if ( (1 << (i-1)) & availableDevices ) // if i is a remote devAddr { command.devAddr=i; command.data[0]=param.portMapping[i]; command.data[1]=param.blowerType; if (send_command(command)==1) status |= (1 << (i-1)); } } return (status == availableDevices) ? 0 : 1; } #ifdef USE_TCPIP int sendUDPcommand(struct UDPmessageType UDPmessage) { // Send the supplied command over UDP // Appends some info to the standard message // .device // .timestamp auto int length, retval; char * UDPbuffer; // to index into UDPmessage byte by byte // fill the packet with additional data UDPmessage.device = param.systemNum; // system id UDPmessage.devType = 4; // NEW main station 1; // main station UDPmessage.timestamp = MS_TIMER; length = sizeof(UDPmessage); // how many bytes to send UDPbuffer = (char *) &UDPmessage; /* send the packet */ retval = udp_send(&sock, UDPbuffer, length); if (retval < 0) { printf("Error sending datagram! Closing and reopening socket...\n"); sock_close(&sock); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); } } } int sendUDPHeartbeat(char sample) { // Sends an INPUTS_ARE message to the host struct UDPmessageType HBmessage; unsigned long timer_val; char * cptr; // pointer to reference into timer value int idx; timer_val=SEC_TIMER; cptr = (char *) &timer_val; idx=0; HBmessage.command = INPUTS_ARE; HBmessage.station = param.systemNum; // provide the real station number HBmessage.data[idx++] = *cptr++; // (char) SEC_TIMER; // Seconds timer HBmessage.data[idx++] = *cptr++; //(char) SEC_TIMER; // Seconds timer HBmessage.data[idx++] = *cptr++; //(char) SEC_TIMER; // Seconds timer HBmessage.data[idx++] = *cptr++; //(char) SEC_TIMER; // Seconds timer HBmessage.data[idx++] = 2; // packet type = heartbeat HBmessage.data[idx++] = system_state; HBmessage.data[idx++] = systemStation; HBmessage.data[idx++] = mainStation; HBmessage.data[idx++] = system_direction; HBmessage.data[idx++] = main2main_trans; HBmessage.data[idx++] = destMain; HBmessage.data[idx++] = remote_data[REMOTE_CIC]; HBmessage.data[idx++] = remote_data[REMOTE_DOOR]; HBmessage.data[idx++] = remote_data[REMOTE_ARRIVE]; HBmessage.data[idx++] = remote_data[REMOTE_RTS]; HBmessage.data[idx++] = remote_data[REMOTE_RTS2]; HBmessage.data[idx++] = 0; // local inputs HBmessage.data[idx++] = 0; // slave inputs HBmessage.data[idx++] = 0; // HBmessage.data[idx++] = 0; // // max is 20 data elements sendUDPcommand(HBmessage); // ignore return value, will send again periodically } void sendUDPtransaction(struct trans_log_type translog, char xtra ) { struct UDPmessageType TLmessage; char * TLbuffer; // to index into translog byte by byte //unsigned long timer_val; //char * cptr; // pointer to reference into timer value int idx; //timer_val=SEC_TIMER; //cptr = (char *) &timer_val; //idx=0; // blank out the buffer for (idx = 0; idx < NUMUDPDATA; idx++) TLmessage.data[idx] = 0; // setup message to announce transaction complete TLmessage.station = param.systemNum; // provide the real station number if possible if (translog.status <= LAST_TRANS_EVENT) TLmessage.command = TRANS_COMPLETE; else if (translog.status == ESTS_SECURE_REMOVAL) { TLmessage.command = ESECURE_REMOVAL; TLmessage.station = xtra; // TLmessage.data[sizeof(translog)] = param.cardL3Digits-CARDHBOFFSET; // add on 5th byte of 38 bit card id } else if (translog.status == ESTS_CARD_SCAN) { TLmessage.command = ECARD_SCAN; TLmessage.station = xtra; } else // otherwise must be some kind of event TLmessage.command = SYSTEM_EVENT; // stuff the transaction log data straight into UDP buffer TLbuffer = (char *) &translog; for (idx = 0; idx < sizeof(translog); idx++) TLmessage.data[idx] = TLbuffer[idx]; sendUDPcommand(TLmessage); // ignore return value, will send again periodically } void sendParametersToLogger(void) { // send the full parameter set over TCP/IP UDP struct UDPmessageType PBmessage; char * PBbuffer; // to index into translog byte by byte int idx; // blank out the buffer for (idx = 0; idx < NUMUDPDATA; idx++) PBmessage.data[idx] = 0; // setup message to announce transaction complete PBmessage.station = param.systemNum; // provide the real station number if possible PBmessage.command = SET_PARAMETERS; // stuff the transaction log data straight into UDP buffer PBbuffer = (char *) &param; // for (idx = 0; idx < sizeof(param); idx++) for (idx = 0; idx < NUMUDPDATA; idx++) // only send as much as fits in buffer. PBmessage.data[idx] = PBbuffer[idx]; sendUDPcommand(PBmessage); // ignore return value, will send again periodically } #endif void maintenance(void) { // handle all regularly scheduled calls hitwd(); // hit the watchdog timer showactivity(); //rn_keyProcess(DevRN1600, 0); // process keypad device // process command communications #ifdef USE_TCPIP tcp_tick(NULL); #endif // handle carrier in chamber light do_CICLight(di_carrierInChamber); // process flashing inUse lights if ((MS_TIMER %500) < 300) digBankOut(0, ~(outputvalue[devInUseFlash] | outputvalue[devInUseSolid])); else digBankOut(0, ~outputvalue[devInUseSolid]); // process blower processBlower(); // process arrival alert processMainArrivalAlert(); // process remote arrival alerts } void exercise_outputs() { /* Exercise all lighted outputs */ alarm(OFF); setAlerts(ON); inUse(FLASH, ALL_STATIONS); hitwd(); // "hit" the watchdog timer msDelay(1000); setAlerts(OFF); hitwd(); // "hit" the watchdog timer msDelay(1000); hitwd(); inUse(ON, ALL_STATIONS); maintenance(); msDelay(200); inUse(OFF, ALL_STATIONS); maintenance(); msDelay(200); inUse(ON, ALL_STATIONS); maintenance(); msDelay(200); inUse(OFF, ALL_STATIONS); maintenance(); hitwd(); // "hit" the watchdog timer } /******************************************************************/ char station2bit(char station) { /* Converts the station number assignment to an equivalent bit value. ie. station 3 -> 0100 (=4) .. same as 2^(sta-1) NOTE: Returns 0 if station is not 1..8 */ if (station) return 1 << (station-1); else return 0; } /******************************************************************/ char bit2station(char station_b) { /* Converts a bit assignment to the bit number value ie. 0100 -> station 3. NOTE: Returns 0 if more than 1 station bit is active */ char stanum, i; stanum = 0; for (i=0; i<8; i++) { if (1<<i == station_b) stanum=i+1; } return stanum; } /******************************************************************/ char firstBit(char bitdata) { // Return # of first bit that is on (1-8) char i; i=0; while (i<8 && ((1<<i & bitdata)==0)) i++; if (i<8) return i+1; else return 0; } /******************************************************************/ /* Communications drivers */ #define CMD_LENGTH 12 #define RCV_TIMEOUT 70 #define ACK_TIMEOUT 30 //#define BUF_COUNT 1 //#define BUF_SIZE 10 #define BAUD_RATE 19200 int badcmd; #define CSTATS 10 unsigned long commstat[CSTATS]; char comError, wasComError; const char * const commlbl[CSTATS] = { "Messages Sent ","Messages Recvd ","Msgs Not Recvd ","Msgs Answered ", "# BAD CHECKSUM ","# INCOMPLETE INP","# NO STX/ETX ","# UNKNOWN ACK ", "# NAK ","# NIL " }; // message buffer for general work use struct iomessage workmsg; void print_comstats(void) { static unsigned long laststats[CSTATS]; // using item 0, 1, 3 // calc difference printf("\n sent=%ld acked=%ld rcvd=%ld", commstat[0]-laststats[0], commstat[1]-laststats[1], commstat[3]-laststats[3]); laststats[0]=commstat[0]; laststats[1]=commstat[1]; laststats[3]=commstat[3]; } void disable485whenDone(void) { while (serDwrUsed()); // wait for all bytes to be transmitted while (RdPortI(SDSR) & 0x0C); // wait for last byte to complete serDrdFlush(); // flush the read buffer ser485Rx(); // disable transmitter } char init_communication() { char stat, i; // Initialize packet driver // Coyote uses port D for RS485 // use default buffer sizes (31 bytes, tx & rx) serDopen(BAUD_RATE); ser485Rx(); serDrdFlush(); // clear receive buffer serDwrFlush(); // clear transmit buffer badcmd=0; workmsg.devAddr=ALL_DEVICES; workmsg.command=RESET; workmsg.station=0; stat = send_command( workmsg ); // return code to determine comm status // clear comm status counters for (i=0; i<CSTATS; i++) commstat[i]=0; wasComError=0; // reset com error state change flag return stat; } unsigned long t1, t2, t3, t4; // debug char send_n_get(struct iomessage message, struct iomessage *response) { // Transmits message to 1 or all devices and combines responses for return // Verify success by response.devAddr -- equals those that answered BIT-WISE (message.devAddr=3 returns 0x04) // Uses global data structure extendedData[] // Break out response for Secure ID char i, j, firstDevAddr, lastDevAddr; char good,retry,anygood; // P2P WORK TO BE DONE HERE ???? response->devAddr=0; response->command=0; // message.command; response->station=0; for (i=0; i<NUMDATA; i++) response->data[i]=0; // process send/return for each controller necessary if (message.devAddr == ALL_DEVICES) { firstDevAddr=FIRST_DEVADDR; lastDevAddr=LAST_DEVADDR; } else { firstDevAddr=message.devAddr; lastDevAddr=message.devAddr; } comError=0; // reset only once each pass through this routine // so that 1 bad device & 1 good device still flags error for (i=firstDevAddr; i<=lastDevAddr; i++) { if ( (1 << (i-1)) & availableDevices ) // if i is a remote devAddr { // set device id message.devAddr=i; if (i != firstDevAddr) msDelay(2); // wait for data lines to clear retry=3; good=FALSE; while (!good && retry) { if (send_command(message)) { // sent command ok, now get response workmsg.command=0; // clear for input of response get_response(&workmsg); if (workmsg.command==message.command) { // OR all the input responses together // for (j=0; j<4; j++) response->data[j] |= workmsg.data[j]; // Catch blower error from head diverter - NOT A GOOD WAY TO DO IT BUT EASY FOR NOW, FIX LATER if ((workmsg.devAddr==HEADDIV_DEVADDR) && (workmsg.command==RETURN_INPUTS)) { // catch blower error from head diverter if (workmsg.data[4]==0xFF) { // blower timeout blwrError=TRUE; } else { // just return blower position remoteBlwrPos = workmsg.data[4]; } workmsg.data[4]=0; } if (workmsg.devAddr==SLAVE_DEVADDR && workmsg.command==RETURN_INPUTS) { // store slave return_input data in global array for (j=0; j<NUMDATA; j++) slaveData[j] = workmsg.data[j]; } else // standard response { for (j=0; j<NUMDATA; j++) response->data[j] |= workmsg.data[j]; } response->devAddr |= workmsg.devAddr; // only works for 1 device at a time (1 << workmsg.devAddr-1); // return responders as bit-wise response->station |= workmsg.station; response->command = workmsg.command; good=TRUE; anygood=TRUE; // if extended data command then store data in alternate location if (workmsg.command==RETURN_EXTENDED) for (j=0; j<4; j++) extendedData[i][j]=workmsg.data[j]; } // could get an alternate message instead of a direct answer to the requested message else if (workmsg.command==SECURE_REMOVAL) // can be std scan as well { // store secure badge id and delta-time //if (secureTransLog[workmsg.station].start_tm) { // not yet logged //secureTransLog[workmsg.station].sid = *(unsigned long *) &workmsg.data[0]; UID_Copy(secureTransLog[workmsg.station].sid, workmsg.data); // update start_tm to be NOW secureTransLog[workmsg.station].start_tm = SEC_TIMER; secureTransLog[workmsg.station].scanType = workmsg.data[5]; //secureTransLog[workmsg.station].flags = workmsg.data[4]; // save scaled delta-t for now } // acknowledge secure removal secureAck |= station2bit(workmsg.station); // BUT DON'T SET GOOD TO BE TRUE SO AS TO FORCE A RETRY ON RETURN_INPUTS } else retry--; } else retry--; } if (!good) comError |= 1<<(i-1); // set flag on failed communications } } return anygood; } char get_response(struct iomessage *message) { char i, status; char rcvbuf[CMD_LENGTH]; int rcvcount; char cksum; unsigned long tstart; message->command=0; /* assume no response for now */ // P2P WORK TO BE DONE HERE ????? /* enable the receiver to get cmdlen characters */ ser485Rx(); // should have been done already // rcvcount = CMD_LENGTH; t3=MS_TIMER; // debug //ser_rec_z1(rcvbuf, &rcvcount); // align frame to <STX> while ((serDrdUsed() > 0) && (serDpeek() != STX)) serDgetc(); //printf("gr tossing %d\n",serDgetc()); rcvcount = 0; tstart = MS_TIMER; while (rcvcount==0 && (MS_TIMER - tstart < RCV_TIMEOUT)) rcvcount = serDread(rcvbuf, CMD_LENGTH, RCV_TIMEOUT); t4=MS_TIMER; // debug if (rcvcount != CMD_LENGTH) { /* not all characters received */ // ser_kill_z1(); /* disable and return failure */ ++commstat[5]; // increment status counter #ifdef PRINT_ON printf("\n INCOMPLETE INPUT: (%d) ",rcvcount); for (i=0; i<rcvcount; i++) printf(" %d", rcvbuf[i]); #endif status=FALSE; } else { /* got the right number of characters */ if ( (rcvbuf[0] != STX) || (rcvbuf[CMD_LENGTH-2] != ETX)) { ++commstat[6]; // increment status counter #ifdef PRINT_ON printf("\n BAD INPUT: No STX %d and/or ETX %d", rcvbuf[0],rcvbuf[CMD_LENGTH-2]); #endif status=FALSE; } else { /* check the checksum */ cksum=0; for (i=0; i<CMD_LENGTH-1; i++) cksum += rcvbuf[i]; if (cksum != rcvbuf[CMD_LENGTH-1]) { /* bad checksum */ ++commstat[4]; // increment status counter #ifdef PRINT_ON printf("\n CHECKSUM ERROR: Calculated %d not equal to xmitted %d",cksum, rcvbuf[CMD_LENGTH-1]); #endif status=FALSE; } else { /* command is good */ ++commstat[3]; // increment status counter - # returned message->devAddr = rcvbuf[1]; message->command = rcvbuf[2]; message->station = rcvbuf[3]; for (i=0; i<NUMDATA; i++) message->data[i]=rcvbuf[i+4]; status=TRUE; } } } //printf(" :: %ld %ld %ld \n", t2-t1, t3-t2, t4-t3); // debug return status; } /******************************************************************/ char txcounter; char send_command(struct iomessage message) { /* Transmits a message/command to the remote system(s). Command string defined as: <STX> <devAddr> <Command> <Station> <Data0..3> <ETX> <CHKSUM> */ // Set <devAddr> = ALL_DEVICES to transmit command to all devices char i,good,retry; char cmdstr[CMD_LENGTH]; char cmdlen; char rcvbuf[CMD_LENGTH]; unsigned long timeout, cmdsent; char mybuf[100]; char tmpbuf[10]; int bufchrs; //unsigned long t1, t2; mybuf[0]=0; good=0; /* return value -- assume nogood*/ retry=3; ++commstat[0]; // increment status counter -- total sent hitwd(); // hit watchdog incase comm loop //msDelay(5); while (!good && retry) { // enable transmitter a bit sooner ser485Tx(); /* assemble the full command string */ cmdlen = CMD_LENGTH; cmdstr[0] = STX; cmdstr[1] = message.devAddr; // one or all devices cmdstr[2] = message.command; cmdstr[3] = message.station; for (i=0; i<NUMDATA; i++) cmdstr[i+4]=message.data[i]; cmdstr[cmdlen-2] = ETX; cmdstr[cmdlen-1] = 0; for (i=0; i<cmdlen-1; i++) cmdstr[cmdlen-1] += cmdstr[i]; /* checksum */ // enable transmitter and send //ser485Tx(); cmdlen = serDwrite(cmdstr, CMD_LENGTH); disable485whenDone(); //t1 = MS_TIMER; // get ack if sending to one device if (message.devAddr != ALL_DEVICES) { // try to throw out first character in case of immediate junk // cmdlen = serDread(rcvbuf, 1, 0); /* should get an ACK or NAK within a short timeout */ rcvbuf[0]=0; cmdlen=0; // one character answer timeout = MS_TIMER; //serDrdFlush(); // try to flush the read buffer again while ((rcvbuf[0] != ACK) && (rcvbuf[0] != NAK) && (MS_TIMER - timeout < ACK_TIMEOUT)) cmdlen = serDread(rcvbuf, 1, 0); //t2 = MS_TIMER; //printf("\n%ld\n", t2-t1); // pre check for ACK, NAK and if not try getting another character //if ((cmdlen) && (rcvbuf[0] != ACK) && (rcvbuf[0] != NAK)) // { cmdlen = 0; // while (cmdlen==0 && (MS_TIMER - timeout < ACK_TIMEOUT)) // cmdlen = serDread(rcvbuf, 1, 0); // } // printf("it took %ld ms to get %d response %d\n", MS_TIMER-timeout, cmdlen, rcvbuf[0]); // if (rcvbuf[0] != ACK) {msDelay(1); printf("peeking at %d\n", serDpeek());} if (rcvbuf[0] == ACK) // received and acknowleged { good = 1; // TRUE } else if (rcvbuf[0] == NAK) // Not received properly { ++commstat[8]; // increment status counter //if (PRINT_ON) printf("NAK "); #ifdef PRINT_ON strcat(mybuf,"NAK "); #endif } else if (rcvbuf[0]) // Unknown response { ++commstat[7]; // increment status counter //if (PRINT_ON) printf("DK "); #ifdef PRINT_ON strcat(mybuf,"DK "); itoa((int)rcvbuf[0], tmpbuf); strcat(mybuf,tmpbuf); #endif } else // No response { /* Re-initialize serial port 1 */ //ser_init_z1(4, 19200/1200); //serDclose(); //serDopen(BAUD_RATE); ++commstat[9]; // increment status //if (PRINT_ON) printf("NIL "); #ifdef PRINT_ON strcat(mybuf,"NIL "); #endif } --retry; } else good = 1; } // Update communication statistics and flags if (good) { ++commstat[1]; } // don't reset comError flag here else { ++commstat[2]; } #ifdef PRINT_ON if (strlen(mybuf) > 0) printf("%ld %s\n",SEC_TIMER, mybuf); #endif return good; } /********************************************************/ // slave com functions /********************************************************/ void slaveEnableCommands() { // open serial port D serDopen(BAUD_RATE); ser485Rx(); // enable the receiver serDrdFlush(); // flush the read buffer } char slaveComActive() { if (SEC_TIMER - lastComTime > 2) return FALSE; else return TRUE; } /********************************************************/ void slaveSendResponse(struct iomessage message) { /* Transmits a message/command to the main system. Command string defined as: <STX> <lplc> <Command> <Station> <Data0..4> <ETX> <CHKSUM> */ char i; char cmdstr[CMD_LENGTH]; char cmdlen; char rcvbuf[CMD_LENGTH]; char rcvlen; unsigned long timeout, cmdsent; cmdlen=CMD_LENGTH; // enable transmitter ser485Tx(); /* formulate the full command string */ cmdstr[0] = STX; cmdstr[1] = SLAVE_DEVADDR; cmdstr[2] = message.command; cmdstr[3] = message.station; for (i=0; i<NUMDATA; i++) cmdstr[i+4]=message.data[i]; cmdstr[cmdlen-2] = ETX; cmdstr[cmdlen-1] = 0; for (i=0; i<cmdlen-1; i++) cmdstr[cmdlen-1] += cmdstr[i]; /* checksum */ // send cmdlen = serDwrite(cmdstr, CMD_LENGTH); if (cmdlen != CMD_LENGTH) printf("Send command failed, only sent %d chars \n", cmdlen); disable485whenDone(); } /********************************************************/ char slaveGetCommand(struct iomessage *message) { /* Repeatedly call this function to process incoming commands efficiently. */ char charsinbuf, msg_address; char rtnval, chksum, i; #define rbuflen 30 #define sbuflen 5 #define SLAVE_RCV_TIMEOUT 1 static char rbuf[rbuflen], sbuf[sbuflen]; static char bufstart; rtnval=FALSE; /* assume none for now */ // align frame to <STX> while ((serDrdUsed() > 0) && (serDpeek() != STX)) serDgetc(); //printf("%ld tossing %d\n",MS_TIMER, serDgetc()); // if at least 1 command in buffer then get them if (serDrdUsed() >= CMD_LENGTH) charsinbuf = serDread(rbuf, CMD_LENGTH, SLAVE_RCV_TIMEOUT); bufstart = 0; if (charsinbuf==CMD_LENGTH) /* all characters received */ { /* verify STX, ETX, checksum then respond */ if ((rbuf[bufstart] == STX) && (rbuf[bufstart+CMD_LENGTH-2] == ETX)) { /* check checksum */ chksum=0; for (i=0; i<CMD_LENGTH-1; i++) chksum+=rbuf[bufstart+i]; if (chksum != rbuf[bufstart+CMD_LENGTH-1]) { sbuf[0]=NAK; rtnval=FALSE; } else { /* looks good, send ACK */ sbuf[0]=ACK; rtnval=TRUE; } lastComTime = SEC_TIMER; msg_address = rbuf[bufstart+1]; // send response if message is addressed to me only if (msg_address==SLAVE_DEVADDR) { // enable transmitter and send ser485Tx(); serDwrite(sbuf, 1); disable485whenDone(); } // If this message for me OR everyone then process it. if ((msg_address==SLAVE_DEVADDR) || (msg_address==ALL_DEVICES)) { // message for me (and possibly others) /* return the command for processing */ message->devAddr=msg_address; message->command=rbuf[bufstart+2]; message->station=rbuf[bufstart+3]; for (i=0; i<NUMDATA; i++) message->data[i]=rbuf[i+bufstart+4]; } else rtnval=FALSE; // command not for me! //serDrdFlush(); // flush the read buffer } } return rtnval; } void show_comm_status() { static unsigned long updateclock; char eventMsg[40]; #GLOBAL_INIT { updateclock = 0; } // now=SEC_TIMER; if (SEC_TIMER > updateclock) { updateclock=SEC_TIMER+2; // put up or remove communications status message if (comError) { sys_message[MSG_NOCOMM+1].msg[MSG_OFFSET+14]=48+firstBit(comError); // show device # message_add(SYSTEMLCD, MSG_NOCOMM, MSG_NOCOMM+1, NEXT); } else message_del(SYSTEMLCD, MSG_NOCOMM, MSG_NOCOMM+1); } // else if (updateclock-2 > SEC_TIMER) updateclock=SEC_TIMER; // means updateclock is grossly out of whack // log to printer on failure and restore if ((comError!=0) && (wasComError==0)) { // error occured now strcpy(eventMsg, "LOST REMOTE COMMUNICATIONS @ DEV #"); eventMsg[33]=48+firstBit(comError); print_event(eventMsg); wasComError=comError; } else if ((wasComError!=0) && (comError==0)) { // error cleared now print_event("REMOTE COMMUNICATIONS RESTORED"); wasComError=comError; } } void show_comm_test(char wait) { // Show communication statistics on the LCD display char i, msgbuf[16];//, shortlbl[3]; char y; if (wait) { lcd_drawScreen(5, "COMMUNICATIONS"); lcd_Font("16B"); } else { // show first label only lcd_DispText(commlbl[0], 0, 0, MODE_NORMAL); } //strcpy(shortlbl, "#:"); // use single character label for nowait screen y=60; // loop through each statistic for (i=0; i<CSTATS; i++) { if (commstat[i]) // only show if non-zero { //lputs(0, commlbl[i]); // write the descriptive label ltoa(commstat[i],msgbuf); //lputs(1," "); //lputs(1, msgbuf); // write the statistic value if (wait) { lcd_DispText(commlbl[i], 20, y, MODE_NORMAL); lcd_DispText(msgbuf, 160, y, MODE_NORMAL); y=y+20; } else // show on plain screen { //shortlbl[0]=65+i; // replace first character with ABC label //lcd_DispText(shortlbl, 0, 0, MODE_NORMAL); //lcd_DispText(":", 0, 0, MODE_NORMAL); lcd_DispText(" ", 0, 0, MODE_NORMAL); lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); } //msDelay(1500); } } if (wait) // wait for any button press or timeout { menu_timeout = SEC_TIMER + 60; while( (lcd_GetTouch(100) == -1) && !secTimeout(menu_timeout) ) maintenance(); } else lcd_DispText("\n", 0, 0, MODE_NORMAL); msDelay(1500); } void show_ip_address(void) { // Show ip address on the LCD display unsigned long ipAddr, netMask, router; char HWA[6]; char s_ipAddr[20]; char s_outBuf[40]; lcd_drawScreen(5, "IP CONFIGURATION"); lcd_Font("16B"); // get ip info ifconfig(IF_ETH0, IFG_IPADDR, &ipAddr, IFG_NETMASK, &netMask, IFG_ROUTER_DEFAULT, &router, IFG_HWA, HWA, IFS_END); // Convert to dotted string and display with a label inet_ntoa(s_ipAddr, ipAddr); sprintf(s_outBuf, "%-15.15s", s_ipAddr); lcd_DispText("IP ADDR", 40, 80, MODE_NORMAL); lcd_DispText(s_outBuf, 120, 80, MODE_NORMAL); inet_ntoa(s_ipAddr, netMask); sprintf(s_outBuf, "%-15.15s", s_ipAddr); lcd_DispText("NETMASK", 40, 100, MODE_NORMAL); lcd_DispText(s_outBuf, 120, 100, MODE_NORMAL); inet_ntoa(s_ipAddr, router); sprintf(s_outBuf, "%-15.15s", s_ipAddr); lcd_DispText("ROUTER", 40, 120, MODE_NORMAL); lcd_DispText(s_outBuf, 120, 120, MODE_NORMAL); sprintf(s_outBuf, "%02X-%02X-%02X-%02X-%02X-%02X", (int)HWA[0], (int)HWA[1], (int)HWA[2], (int)HWA[3], (int)HWA[4], (int)HWA[5]); lcd_DispText("MAC ADDR", 40, 140, MODE_NORMAL); lcd_DispText(s_outBuf, 120, 140, MODE_NORMAL); menu_timeout = SEC_TIMER + 60; while( (lcd_GetTouch(100) == -1) && !secTimeout(menu_timeout) ) maintenance(); } /******************************************************************/ void checkRemoteConfiguration(void) { // determine which remotes are connected to the bus struct iomessage testcmd, testrsp; char i, workset, mymsg[20], mybuf[10]; int j; // P2P WORK TO BE DONE HERE slaveAvailable = FALSE; // ASSUME NOT FIRST_DEVADDR=0; // number LAST_DEVADDR=0; // number workset=0; //ALL_DEVADDRS=((1 << MAX_DEVADDRS) - 1 ) | 0x80; // bits ... including high bit availableDevices = 0xFF; // address all possible devices //lcd_print(SYSTEMLCD, 0, " CHECKING REMOTE"); //lcd_print(SYSTEMLCD, 1, " CONFIGURATION "); lcd_DispText("Detecting Remote Devices\n",0, 0, MODE_NORMAL); // hold for a few seconds //msDelay(100); strcpy(mymsg, " "); STATION_SET = 0; // startoff with none for (j=1; j<=MAX_DEVADDRS; j++) { mybuf[0]=48+j; mybuf[1]=32; mybuf[2]=0; lcd_DispText(mybuf, 0, 0, MODE_NORMAL); hitwd(); testcmd.station=0; testcmd.devAddr=j; testcmd.data[0]=0; // main ok to receive testcmd.data[1]=IDLE_STATE; // system state testcmd.data[2]=0; // slave inUse ON testcmd.data[3]=0; // slave inUse Flash testcmd.data[4]=STATION_SET; // who's available testcmd.command=RETURN_INPUTS; msDelay(100); // seems to improve communications i = send_n_get( testcmd, &testrsp ); // are you alive if (testrsp.devAddr==testcmd.devAddr) { // this one is alive STATION_SET |= testrsp.station; // who do you own if (FIRST_DEVADDR==0) FIRST_DEVADDR=j; LAST_DEVADDR=j; // if (testrsp.station & SLAVE_b) slaveAvailable=TRUE; if (testrsp.devAddr == SLAVE_DEVADDR) slaveAvailable=TRUE; workset |= (1 << (j-1)); // include this bit itoa(j, mybuf); strcat(mymsg, " #"); strcat(mymsg, mybuf); } } STATION_SET &= param.activeStations; // allow only those programmed in diag menu availableDevices = workset; // | 0x80; // also set high bit, meaning ALL if (strlen(mymsg) <= 3) strcpy(mymsg, "- NONE -"); // pad the message buffer //for (j=strlen(mymsg); j<16; j++) strcat(mymsg, " "); // show the results of the query //lcd_print(SYSTEMLCD, 0, "RESPONSE OK FROM"); //lcd_print(SYSTEMLCD, 1, mymsg); lcd_DispText("\nResponse Received From ",0, 0, MODE_NORMAL); lcd_DispText(mymsg,0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); // reset communications statistics init_communication(); // hold for a few seconds //msDelay(2000); } nodebug void reset_statistics() { // reset system statistics statistics.trans_in=0; statistics.trans_out=0; statistics.deliv_alarm=0; statistics.divert_alarm=0; statistics.cic_lift_alarm=0; } void time2string(unsigned long time, char *buf, int format) { // Converts the time value into a string as specified by format // time time value to be converted // buf destination string ... make sure you allocate enough room // format how the time should be converted // 1 = HH:MM:SS 2 = HH:MM // 3 = MM/DD/YY 4 = MM/DD/YY HH:MM:SS struct tm mytime; char * myptr; // convert long time to structure mktm( &mytime, time); myptr=buf; // convert date if (format==3 || format==4) { // fill in the date values *myptr++ = 48 + (mytime.tm_mon / 10); *myptr++ = 48 + (mytime.tm_mon % 10); *myptr++ = '/'; *myptr++ = 48 + (mytime.tm_mday / 10); *myptr++ = 48 + (mytime.tm_mday % 10); *myptr++ = '/'; *myptr++ = 48 + ((mytime.tm_year / 10) % 10); *myptr++ = 48 + (mytime.tm_year % 10); } // convert time if (format==1 || format==2 || format==4) { if (format==4) *myptr++ = 32; // space seperator // fill in the time values *myptr++ = 48 + (mytime.tm_hour / 10); *myptr++ = 48 + (mytime.tm_hour % 10); *myptr++ = ':'; *myptr++ = 48 + (mytime.tm_min / 10); *myptr++ = 48 + (mytime.tm_min % 10); if (format==1 || format==4) // format seconds { *myptr++ = ':'; *myptr++ = 48 + (mytime.tm_sec / 10); *myptr++ = 48 + (mytime.tm_sec % 10); } } *myptr = 0; // null terminator } /******************************************************/ // Printout functions /******************************************************/ void print_event(char *event) { char myline[80]; // line to send to the printer char * instr; // work pointer into myline instr=myline; time2string(SEC_TIMER, instr, 4); // event time strcat(myline, " "); strcat(myline, event); /// reset_printer(); // reset/retry printer each time /// print_line(myline); printf("\n"); printf(myline); } /* void print_malfunction(struct trans_log_type log) { char myline[80]; // line to send to the printer char * instr; // work pointer into myline strcpy(myline, "ALARM "); instr=myline+strlen(myline); time2string(log.duration, instr, 4); // malfunction time strcat(myline," "); instr=myline+strlen(myline); switch (log.status & 0x0F) { case STS_DIVERTER_TOUT: strcat(myline, "DIVERTER TIMEOUT"); break; case STS_DEPART_TOUT: strcat(myline, "DEPARTURE TIMEOUT"); break; case STS_ARRIVE_TOUT: strcat(myline, "DELIVERY OVERDUE"); break; case STS_BLOWER_TOUT: strcat(myline, "BLOWER TIMEOUT"); break; case STS_TRANS_CANCEL: strcat(myline, "CANCEL DISPATCH"); break; //case 5: strcat(myline, "COMMUNICATIONS LOST"); break; } /// reset_printer(); // reset/retry printer each time /// print_line(myline); // print_transaction( log ); // now print normal log } void print_transaction(struct trans_log_type log) { char myline[80]; // line to send to the printer char * instr; // work pointer into myline long transtime; // how long transaction took // format the message line time2string(log.start_tm, myline, 4); // start time strcat(myline," "); instr=myline+strlen(myline); sprintf(instr, "%-12s", param.station_name[log.source_sta].name); strcat(myline, "-->> "); instr=myline+strlen(myline); time2string(log.duration, instr, 1); transtime=log.duration-log.start_tm; instr=myline+strlen(myline); sprintf(instr, " %-12s %4ld sec", param.station_name[log.dest_sta].name, transtime); /// reset_printer(); // reset/retry printer each time /// print_line(myline); } */ /******************************************************/ /*const char prLine[] = "-----------------------------------------------------------------"; void print_summary(struct stats_type stats, char how) { // stats : system summary statistics // how : automatic report (0) or on-demand report (1) char myline[80]; // line to send to the printer char * instr; // work pointer into myline long subtot; // total of transactions or alarms /* reset_printer(); // reset/retry printer each time print_line(prLine); print_line(station_name[SYSTEM_NAME].name); // print system name if (how==0) { strcpy(myline, " Daily "); } else { strcpy(myline, " On-Demand "); } strcat(myline, "Transaction Summary Printed "); instr = myline + strlen(myline); time2string(clock(), instr, 4); print_line(myline); print_line(prLine); print_line(" Transactions:"); sprintf(myline, " Incoming: %ld", stats.trans_in); print_line(myline); sprintf(myline, " Outgoing: %ld", stats.trans_out); print_line(myline); sprintf(myline, " Daily Total: %ld", stats.trans_in + stats.trans_out); print_line(myline); sprintf(myline, " Grand Total: %ld", transactionCount()); print_line(myline); print_line(" "); print_line(" Alarms:"); sprintf(myline, " Incomplete Delivery: %d", stats.deliv_alarm); print_line(myline); sprintf(myline, " Diverter Timeout: %d", stats.divert_alarm); print_line(myline); sprintf(myline, " Other Timeouts: %d", stats.cic_lift_alarm); print_line(myline); subtot=stats.deliv_alarm+stats.divert_alarm+stats.cic_lift_alarm; sprintf(myline, " Total: %ld", subtot); print_line(myline); print_line(prLine); }*/ /* void check_auto_report(struct stats_type stats) { if (SEC_TIMER >= nextAutoPrint) { // time to print automatic summary report print_summary(stats, 0); // increment to next day (86400 seconds per day) while (nextAutoPrint <= SEC_TIMER) { reset_auto_print(); } // reset statistics reset_statistics(); } } void reset_auto_print() { // set auto print statistics for midnight tomorrow nextAutoPrint = (((SEC_TIMER+1) / 86400) +1) * 86400; } */ //************************************* // functions for master/slave operation //************************************* void syncDateAndTime() { // for master to send the date/time to the slave struct iomessage command; struct tm time; tm_rd(&time); // get the time from the RTC command.devAddr=ALL_DEVICES; command.command=SET_DATE_TIME; command.station=0; command.data[0] = time.tm_year; command.data[1] = time.tm_mon; command.data[2] = time.tm_mday; command.data[3] = time.tm_hour; command.data[4] = time.tm_min; send_command(command); } void syncTransCount() { // for master to send traction count to slave struct iomessage command; char *p; p=(char*)&transaction_count; command.devAddr=ALL_DEVICES; command.command=SET_TRANS_COUNT; command.station=0; command.data[0] = *p++; command.data[1] = *p++; command.data[2] = *p++; command.data[3] = *p; command.data[4] = 0; msDelay(10); // just sent a command so wait a bit send_command(command); } void displayRemoteMsgs(char * message_num) { // for master to send lcd messages to slave struct iomessage command; char i; command.devAddr = ALL_DEVICES; command.command = DISPLAY_MESSAGE; for (i=0; i<4; i++) command.data[i]=message_num[i]; send_command(command); } void deliverComControl(char *sys_state) { // let slave use the comm for a while struct iomessage mymsg; char waiting; param.slaveController=SLAVE; // TEMP ID // tell slave ok mymsg.command=TAKE_COMMAND; mymsg.devAddr=SLAVE_DEVADDR; mymsg.data[0]=*sys_state; mymsg.data[1]=availableDevices; mymsg.data[2]=remote_data[REMOTE_CIC]; send_command(mymsg); // display lcd message lcd_printMessage(2, " SLAVE IN USE "); lcd_printMessage(3, " PLEASE WAIT... "); // setup diverter at master for slave to purge set_diverter(SLAVE); // wait for response waiting=TRUE; slaveEnableCommands(); lastComTime=SEC_TIMER; while (waiting) { check_diverter(); maintenance(); if (slaveGetCommand(&mymsg)) { if ( (mymsg.command==TAKE_COMMAND) || (mymsg.command==RESET) ) { waiting=FALSE; *sys_state=mymsg.data[0]; } lastComTime=SEC_TIMER; } if (SEC_TIMER - lastComTime > 60) waiting=FALSE; // timeout if no com for 60 seconds } param.slaveController=MASTER; // RESET Address } void slaveSyncTransCount(char *p) { // for slave to sync transaction count from master char *myp; myp=(char*)&transaction_count; *myp++ = *p++; *myp++ = *p++; *myp++ = *p++; *myp++ = *p++; setCountMessage(); root2xmem( transCountXaddr, &transaction_count, 4); } void slaveFinishTransaction() { setAlerts(OFF); //, station2bit(systemStation)); // set arrival alert if the transaction is to here if ( ((system_direction == DIR_RETURN) && (mainStation==SLAVE)) || ((mainStation==MASTER) && (main2main_trans==DIR_SEND)) ) { //inUse(FLASH, station2bit(message.station)); // until no cic slave_arrival = SEC_TIMER; // to flash inuse rts_latch=0; // don't allow any out-bounds right now } mainStation=0; systemStation=0; system_direction=0; arrivalEnable(OFF); // force an increment of the transaction counter even though a sync message should come soon // for some reason the sync is not getting through transaction_count++; setCountMessage(); } int slaveButton; void slaveProcessIO() { // for slave to handle local I/O processing struct iomessage message; char k; // temporary work value char menu_item; char key; int button; static char lastDirectory; // for showing stations on the lcd #GLOBAL_INIT { lastDirectory = 0; } // check for and process communications if (slaveGetCommand(&message)) slaveProcessCommand(message); slaveProcessState(); // operate on system_state // process local i/o check_diverter(); //processCycleTime(); //key = getKey(); // processKeyInput(); // handle button press button = lcd_GetTouch(1); if (button != -1) { slaveButton = button; // save this button press if (!slaveComActive()) lcd_processTouchScreen(slaveButton); else slaveReturnStatus |= 0x08; // let master decide if I can do this } if (slave_arrival) { // check for 10 second arrival alert signal if (system_state != HOLD_TRANSACTION) // except when holding { if ( (SEC_TIMER - slave_arrival) %20 >= 10 ) setAlerts(ON); else setAlerts(OFF); } // check to clear main arrival alert when door opens or another transaction starts if ( (!di_doorClosed && !di_carrierInChamber) || ((mainStation==SLAVE) && (system_direction==DIR_SEND)) ) { slave_arrival=0; arrival_from=0; setAlerts(OFF); } } lcd_showCIC(0); // show CIC // latch transaction requests ... only if there is a carrier or carrierReturn k=di_requestToSend; // | station2bit(lcd_sendTo()); if (di_carrierInChamber || di_returnCarrier) { rts_latch |= (k & STATION_SET); } else if (system_state==IDLE_STATE) { rts_latch=0; // check for directory display if (k != lastDirectory) { //systemStationb=k; systemStation=bit2station(k); //systemStationb); if (systemStation) { //lcd_print(TRANSLCD, 0, sys_message[MSG_REMOTESTA].msg); //lcd_print(TRANSLCD, 1, sys_message[MSG_AT+systemStation].msg); currentmsg[TRANSLCD][0]=MSG_REMOTESTA; currentmsg[TRANSLCD][1]=MSG_AT+systemStation; lcd_displayMsgs(&currentmsg[0][0]); } lastDirectory = k; systemStation=0; // reset this after directory display } } } void slaveProcessCommand(struct iomessage message) { char wcmd, wdata, source, dest; char ok, i, j; static char haveButtons; struct iomessage response; struct tm time; #GLOBAL_INIT { haveButtons=TRUE; } response.command=0; response.station=message.station; // set initial default response.devAddr=SLAVE_DEVADDR; /* determine what type of command */ switch(message.command) { case CANCEL_PENDING: rts_latch = 0; // clear latch for all stations break; case SET_STATION_NAME: if (message.station==69) { // construct messages and save parameters to flash buildStationNames(); writeParameterSettings(); } else { // save chunk of name i=message.data[0]; for (j=0; j<4; j++) param.station_name[message.station].name[i+j] = message.data[j+1]; } break; case SET_PHONE_NUMS: if (message.station==69) { // save parameters to flash writeParameterSettings(); } else { // save chunk of name i=message.data[0]; for (j=0; j<4; j++) param.phoneNum[message.station][i+j] = message.data[j+1]; } break; case SET_TRANS_COUNT: slaveSyncTransCount(&message.data[0]); break; case SET_PARAMETERS: // no parameters to deal with ... for now break; case SET_DATE_TIME: tm_rd(&time); // read all time data time.tm_year=message.data[0]; time.tm_mon=message.data[1]; time.tm_mday=message.data[2]; time.tm_hour=message.data[3]; time.tm_min=message.data[4]; tm_wr(&time); // write new time data SEC_TIMER = mktime(&time); // resync SEC_TIMER break; case DISPLAY_MESSAGE: // display messages on lcd if installed // first update variable messages setCountMessage(); setTimeMessages(MSG_DATE_TIME, SEC_TIMER); // fixup messages in function_mode at master if (message.data[0] == MSG_FUNCTION) { message.data[2]=MSG_WAIT; message.data[3]=MSG_BLANK; } lcd_displayMsgs(&message.data[0]); break; case ARE_YOU_READY: // ready to begin transaction // need to check for both source and destination stations response.command=ARE_YOU_READY; systemStation=message.station; systemStationb=station2bit(systemStation); system_direction=message.data[0]; mainStation=message.data[1]; main2main_trans=message.data[2]; // clear latch for these stations rts_latch &= ~systemStationb; response.data[0]=SLAVE_b; // assume ready for now // check destination station ... is it me? // 1) main to slave if ((mainStation==MASTER) && (main2main_trans==DIR_SEND)) { // door must be closed, set arrival enable if (di_doorClosed) { arrivalEnable(ON); } else { // door open so not ready response.data[0]=0; // not ready setAlerts(ON); } } // 2) remote to slave else if ((mainStation==SLAVE) && (system_direction==DIR_RETURN)) { // door must be closed, set arrival enable if (di_doorClosed) { arrivalEnable(ON); } else { // door open so not ready response.data[0]=0; // not ready setAlerts(ON); } } // 3) slave to any else if ((mainStation==SLAVE) && (system_direction==DIR_SEND)) { // door must be closed, carrier in chamber if (di_doorClosed && di_carrierInChamber) { // do nothing, ready to go } else { // door open or no carrier so not ready response.data[0]=0; // not ready setAlerts(ON); } } // 4) don't care, always ready else { // do nothing } slaveSendResponse(response); lcd_drawScreen(1,lcd_NO_BUTTONS); // take away buttons haveButtons=FALSE; break; case SET_DIVERTER: mainStation=message.data[1]; param.subStaAddressing=message.data[2]; param.blowerType=message.data[3]; // set_diverter(mainStation); NEVER A SLAVE LOCAL DIVERTER break; case DIVERTER_STATUS: /* return logic of correct position */ response.command=DIVERTER_STATUS; mainStation=message.data[1]; response.data[0]=SLAVE_b; // NEVER A SLAVE LOCAL DIVERTER, ALWAYS OK TO GO slaveSendResponse(response); break; case RETURN_INPUTS: /* return general status */ system_state=message.data[1]; // set system_state response.command=INPUTS_ARE; response.station=SLAVE_b; // return this to enlighten main response.data[0] = di_carrierInChamber ? 0x01 : 0; if (di_doorClosed) response.data[0] |= 0x02; if (latchCarrierArrival) response.data[0] |= 0x04; if (di_priorityRequest || (btnStatFlag==1)) response.data[0] |= 0x08; if (btnStatFlag==2) response.data[0] |= 0x10; btnStatFlag=0; // reset the flag //response.data[0] |= di_diverterPos << 4; // why was I sending diverter pos? response.data[1] = rts_latch | station2bit(lcd_sendTo()); if (slave_arrival) slaveReturnStatus |=0x10; // slave arrival flag if (di_returnCarrier || lcd_returnCarrier()) slaveReturnStatus |= 0x40; // return carrier_return request if (lcd_autoReturn() || autoRtnTrans) slaveReturnStatus |= 0x80; // auto return requested response.data[2]=slaveReturnStatus; slaveReturnStatus=0; // I expect immediate response // return the response immediately response.devAddr=SLAVE_DEVADDR; slaveSendResponse(response); response.command=0; // set my lights based on main station inUse(ON, message.data[2]); inUse(FLASH, message.data[3]); inUse(OFF, ~(message.data[2]|message.data[3])); STATION_SET=message.data[4]; // change active main if needed if ( (message.station != param.activeMain) && (message.station == MASTER || message.station == SLAVE)) { param.activeMain=message.station; setActiveMainMsg(); } activeMainHere = (param.activeMain == MASTER); // FOR SETUP MENU - NOT-OPPOSITE OF MASTER LOGIC break; case RETURN_EXTENDED: response.command=RETURN_EXTENDED; response.station=SLAVE_b; // return this to enlighten main response.data[0]=0; // Add version number here later response.data[1]=0; response.data[2]=0; response.data[3]=0; slaveSendResponse(response); break; case SET_OUTPUTS: break; case CLEAR_OUTPUTS: break; case TRANS_COMPLETE: slaveFinishTransaction(); lcd_drawScreen(1,lcd_WITH_BUTTONS); haveButtons=TRUE; break; case TAKE_COMMAND: // setup for handling communications, determine first, last, and available devices availableDevices=message.data[1] & 0x7F; // exclude slave (me) FIRST_DEVADDR=0; LAST_DEVADDR=0; for (i=0; i<7; i++) { if (availableDevices & (1<<i)) { if (FIRST_DEVADDR==0) FIRST_DEVADDR=i+1; LAST_DEVADDR=i+1; } } // take CIC data too remote_data[REMOTE_CIC] = message.data[2]; // process the button previously presses lcd_processTouchScreen(slaveButton); slaveButton=-1; //if (system_state==MALFUNCTION_STATE) lcd_enterSetupMode(0); //else lcd_enterSetupMode(1); //lcd_drawScreen(1, "MENU"); // redraw main screen // return command when done message.command=TAKE_COMMAND; message.devAddr=SLAVE_DEVADDR; // send to main, temporary lplc# message.data[0]=system_state; send_command(message); lastComTime=SEC_TIMER; break; case MALFUNCTION: // turn on alarm output only setAlerts(OFF); if (mainStation==SLAVE) alarm(ON); // alarm(ON) appears in process state too rts_latch=0; for (i=0; i<NUMDATA; i++) response.data[i]=0; // clear remote i/o arrivalEnable(OFF); // disable arrival interrupt if (haveButtons==FALSE) { // no buttons yet so redraw screen to allow responding to an alarm lcd_drawScreen(1,lcd_WITH_BUTTONS); haveButtons=TRUE; } break; case RESET: // Turn off all outputs // SEEMS LIKE SOMETIMES MAY NOT COME HERE WHEN SLAVE ISSUED AN ALARM RESET // WHICH PASSES CANCEL_STATE BACK TO MAIN, LEADING TO A RESET COMMAND IN FINAL_COMMAND lcd_drawScreen(1,lcd_WITH_BUTTONS); inUse(OFF, ALL_STATIONS); // clear local i/o setAlerts(OFF); alarm(OFF); // rts_latch=0; mainStation=0; systemStation=0; system_direction=0; for (i=0; i<NUMDATA; i++) response.data[i]=0; // clear remote i/o arrivalEnable(OFF); // disable arrival interrupt slave_arrival=0; arrival_from=0; break; } // Reset serial port (but why?) // slaveEnableCommands(); return; } void slaveProcessState() { static char washolding; // Process system states switch (system_state) { case IDLE_STATE: if (systemStation) slaveFinishTransaction(); // force finish because this should not be washolding=FALSE; break; case PREPARE_SEND: // does job for send and return // turn off priority if it was on statTrans = FALSE; setAlerts(OFF); do_priorityLight(OFF); arrivalEnable(OFF); //inUse(FLASH, sub_stationb); //blower(OFF); // for slave to master headdiverter break; case WAIT_FOR_DIVERTERS: // does job for send and return // while waiting, if different request to send, cancel. if (di_requestToSend && (mainStation==SLAVE) && (systemStationb != di_requestToSend) && (system_direction==DIR_SEND)) slaveReturnStatus |= 0x01; // cancel transaction break; case BEGIN_SEND: // make sure all stations ready (by command) //inUse(ON, sub_stationb); break; case WAIT_FOR_MAIN_DEPART: // if (mainStation==SLAVE) blower(blowerSend); setAlerts(OFF); break; case WAIT_FOR_REM_DEPART: if ( (mainStation==SLAVE) || ((mainStation==MASTER) && (main2main_trans==DIR_SEND))) { // blower(blowerReturn); arrivalEnable(ON); // enable arrival interrupt } setAlerts(OFF); break; case WAIT_FOR_HEADDIVERTER: break; case SHIFT_HEADDIVERTER: if ( (mainStation==SLAVE) || ((mainStation==MASTER) && (main2main_trans==DIR_SEND))) { // blower(blowerReturn); arrivalEnable(ON); // enable arrival interrupt } setAlerts(OFF); break; case WAIT_FOR_MAIN_ARRIVE: if (washolding && ( (mainStation==SLAVE) || ( (mainStation==MASTER) && (main2main_trans==DIR_SEND)))) { // blower(blowerReturn); arrivalEnable(ON); // enable arrival interrupt washolding=FALSE; } setAlerts(OFF); break; case WAIT_FOR_REM_ARRIVE: if (washolding && ( (mainStation==SLAVE) || ((mainStation==MASTER) && (main2main_trans==DIR_SEND)))) { // blower(blowerSend); washolding=FALSE; } setAlerts(OFF); break; case HOLD_TRANSACTION: // blower(OFF); if (mainStation==SLAVE) { setAlerts(ON); // FORCED); washolding=TRUE; } break; case CANCEL_STATE: inUse(OFF, systemStationb); // blower(OFF); arrivalEnable(OFF); washolding=FALSE; break; case MALFUNCTION_STATE: // blower(OFF); arrivalEnable(OFF); if (mainStation==SLAVE) alarm(ON); // added 10/23/97, alarm(ON) appears in process command too break; default: // unknown state, do nothing } // end switch (system_state) } nodebug void msDelay(unsigned int delay) { auto unsigned long start_time; start_time = MS_TIMER; //if (delay < 500) while( (MS_TIMER - start_time) <= delay ); //else while( (MS_TIMER - start_time) <= delay ) hitwd(); } nodebug char secTimeout(unsigned long ttime) { return (ttime > SEC_TIMER) ? FALSE : TRUE; } char Timeout(unsigned long start_time, unsigned long duration) { return ((MS_TIMER - start_time) < duration) ? FALSE : TRUE; } void lcd_helpScreen(char view) { // view not applicable - reserved for future use int button; // Logo splash screen lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Font("13"); lcd_DispText(FIRMWARE_VERSION, 230, 5, MODE_NORMAL); lcd_DispText(param.station_name[SYSTEM_NAME].name, 10, 5, MODE_NORMAL); lcd_DispText("\nTo send a carrier:", 0, 0, MODE_NORMAL); lcd_DispText("\nInsert carrier into tube and close the door", 0, 0, MODE_NORMAL); lcd_DispText("\nPress the send button for the destination", 0, 0, MODE_NORMAL); lcd_DispText("\nOR", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Send To Directory button", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the send button for the destination", 0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the STAT button for priority dispatch", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Secure button to enable secure handling", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Auto Return button to enable automatic return", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Return Carrier button to return a carrier", 0, 0, MODE_NORMAL); lcd_DispText("\nTouch the Menu button to access system features", 0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); lcd_DispText("\nHelp Phone Numbers", 0, 0, MODE_NORMAL); lcd_DispText("\nSystem Administrator: ", 0, 0, MODE_NORMAL); lcd_DispText(param.phoneNum[ADMIN_PHONE], 0, 0, MODE_NORMAL); lcd_DispText("\nMaintenance: ", 0, 0, MODE_NORMAL); lcd_DispText(param.phoneNum[MAINT_PHONE], 0, 0, MODE_NORMAL); lcd_DispText("\nColombo Sales & Engineering: 800-547-2820 ", 0, 0, MODE_NORMAL); lcd_Font("16B"); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TXTOFFSET, 10, 9, BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TEXT, "Done", BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // wait for a button press menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); } void lcd_splashScreen(char view) { // view 0 for initial startup splash (no wait) // view 1 for help->about splash (wait for button) int loop_count, i; char sbuf[15]; if (view==0) { for ( loop_count = 0; loop_count < 20; loop_count++) { if ( (i = lcd_Connect()) == lcd_SUCCESS ) break; hitwd(); // "hit" the watchdog timer } //if ( i!= lcd_SUCCESS ) exit (1); // exit if no comm with unit lcd_BeepVolume ( 100 ); // default of 200 is TOO loud lcd_Typematic ( 500, 330 ); // delay .5 secs, repeat 3/sec } // Logo splash screen lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); //lcd_screenSaver(LCD_BRIGHT); lcd_DispBitmap( BMP_COLOMBO_LOGO, 79, 30 ); lcd_Font("16"); lcd_DispText("Colombo Sales & Engineering", 70, 180, MODE_NORMAL); lcd_DispText("800-547-2820", 115, 200, MODE_NORMAL); if (view) { //lcd_DispText("Software version ", 70, 225, MODE_NORMAL); lcd_Font("13"); lcd_DispText(FIRMWARE_VERSION, 108, 221, MODE_NORMAL); // show phone numbers for admin, maint, and colombo msDelay(4000); // wait 4 seconds } else { // Please wait message msDelay(1000); lcd_ClearScreen (); lcd_Font("16B"); lcd_DispText("Colombo Sales & Engineering\n", 0, 0, MODE_NORMAL); lcd_DispText("Pneumatic Tube System\n", 0, 0, MODE_NORMAL); //lcd_DispText("Software version ", 0, 0, MODE_NORMAL); lcd_DispText(FIRMWARE_VERSION, 0, 0, MODE_NORMAL); lcd_DispText(" ", 0, 0, MODE_NORMAL); lcd_DispText(__DATE__, 0, 0, MODE_NORMAL); lcd_Font("16"); lcd_DispText("\nby MS Technology Solutions, LLC", 0, 0, MODE_NORMAL); lcd_DispText("\nAvailable extended memory ",0,0,MODE_NORMAL); sprintf(sbuf, "%ld\n", xavail((long *)0)); lcd_DispText(sbuf,0,0,MODE_NORMAL); } lcd_Font("16"); } void lcd_drawScreen(char whichScreen, char *title) { // whichScreen: // 1: main screen with text boxes, unless title[0]=0 / "" // 2: menu header and bottom buttons // 3: menu header only // 4: menu header, keypad, OK, cancel // 5: header with exit button // 6: header keyboard, next, exit // 7: header clock up/downs, exit // 8: transaction log: pgup, pgdn, done // 9: header, keypad, next, exit // 10: header keyboard, OK, cancel int x, dx; lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); lcd_PenWidth(1); lcd_Font("24"); lcd_resetMsgBackColor(); // draw title if needed if (whichScreen >=2) { lcd_BFcolorsB( lcd_BLUE, lcd_WHITE ); // inside color lcd_Rectangle(5, 5, 315, 40, 1); // inside paint lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); // border color lcd_Rectangle(5, 5, 315, 40, 0); // border paint lcd_Font("24B"); lcd_DispText(title, lcd_Center(title, 1), 14, MODE_TRANS); } // now handle screen specific stuff switch (whichScreen) { case 1: if (title[0] != 0) // Buttons? (any) or not ("") { // Draw a box for top row of bottom buttons lcd_BFcolorsB( lcd_LBLUE, lcd_LBLUE ); // inside color lcd_Rectangle(5, 139, 315, 197, 1); // inside paint 158 -> 140 lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(5, 139, 315, 197, 0); // border paint lcd_Font("13B"); lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); // border color lcd_DispText("---- Transaction Options ----", 15, 143, MODE_TRANS); // Draw a box for Return from lcd_BFcolorsB( lcd_LBLUE, lcd_LBLUE ); // inside color lcd_Rectangle(215, 197, 315, 237, 1); // inside paint lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(215, 197, 315, 237, 0); // border paint // Draw a box for menu/help lcd_BFcolorsB( lcd_LGREEN, lcd_LGREEN ); // inside color lcd_Rectangle(5, 197, 142, 237, 1); // inside paint lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(5, 197, 215, 237, 0); // border paint lcd_Rectangle(5, 197, 142, 237, 0); // border paint // Draw bottom buttons lcd_BFcolorsD( lcd_BLACK, lcd_VLTGRAY_D ); lcd_Font("16B"); lcd_ButtonDef( BTN_MENU, BTN_MOM, // momentary operation BTN_TLXY, 13, 202, //5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Menu", BTN_TXTOFFSET, 10, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_HELP, //BTN_TLXY, 257, 205, BTN_TLXY, 80, 202, //70, 205, BTN_TXTOFFSET, 12, 9, BTN_TEXT, "Help", BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); //lcd_Font("13"); //lcd_Font("13B"); lcd_ButtonDef( BTN_DIRECTORY, //BTN_TLXY, 114, 198, BTN_TLXY, 220, 153, //135, 198, //BTN_TEXT, " Station\nDirectory", BTN_TEXT, "Send to /\nDirectory", BTN_TXTOFFSET, 15, 4, //9, //14, 4, //BTN_BMP, BMP_92x40_button, BMP_92x40_button_dn, BTN_BMP, BMP_92x40_button, BMP_92x40_button_dn, BTN_END ); //lcd_Font("16B"); lcd_Font("13B"); lcd_ButtonDef( BTN_CRETURN, //BTN_TLXY, 257, 160, BTN_TLXY, 220, 202, //70, 160, BTN_TXTOFFSET, 15, 3, BTN_TEXT, "Return a\n Carrier", BTN_BMP, BMP_92x32_button, BMP_92x32_button_dn, BTN_END ); // lcd_Font("16B"); // lcd_Font("13B"); lcd_ButtonDef( BTN_ARETURN, BTN_LAT, //BTN_TLXY, 114, 160, BTN_TLXY, 147, 161, BTN_TYPE, autoRtnTrans ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_TXTOFFSET, 7, 3, 7, 3, BTN_TEXT, " Auto\nReturn", " Auto\nReturn", BTN_BMP, BMP_med_button, BMP_med_grn_button_dn, // BMP_92x32_button, BMP_92x32_button_dn, BTN_END ); lcd_Font("16B"); lcd_ButtonDef( BTN_STAT, BTN_LAT, BTN_TLXY, 13, 161, BTN_TYPE, statTrans ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_TEXT, "STAT", "STAT", BTN_TXTOFFSET, 12, 9, 12, 9, BTN_BMP, BMP_med_button, BMP_med_grn_button_dn, BTN_END ); // show secure button only if the feature is enabled if (param.secureEnabled) lcd_ButtonDef( BTN_SECURE, BTN_LAT, BTN_TLXY, 80, 161, BTN_TYPE, secureTrans ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_TEXT, "Secure", "Secure", BTN_TXTOFFSET, 7, 9, 7, 9, BTN_BMP, BMP_med_button, BMP_med_grn_button_dn, BTN_END ); else lcd_ButtonDef( BTN_FUTURE, BTN_MOM, BTN_TLXY, 80, 161, BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Future", BTN_TXTOFFSET, 7, 9, BTN_BMP, BMP_med_button, BMP_med_button, BTN_END ); // Show CIC light on the screen if we are also showing buttons lcd_showCIC(1); } // Draw LCD Message boxes //lcd_BFcolorsB( lcd_LGREY, lcd_LGREY); // inside color //lcd_Rectangle(5, 5, 315, 71, 1); // inside paint //lcd_Rectangle(5, 71, 315, 137, 1); // inside paint lcd_BFcolorsB( lcd_BLUE, lcd_LGREY); // border color lcd_Rectangle(5, 5, 315, 72, 0); // border paint lcd_Rectangle(5, 72, 315, 139, 0); // border paint // since this screen was just cleared, for a refresh of the lcd messages reset_msg_timer(NOW); break; case 2: // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_PREV, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "PgUp", BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_NEXT, BTN_TEXT, "PgDn", BTN_END ); /* lcd_ButtonDef( 1, BTN_TEXT, "", BTN_END ); lcd_ButtonDef( BTN_SAVE, BTN_TEXT, "", BTN_END ); */ lcd_ButtonDef( BTN_CANCEL, //BTN_TXTOFFSET, 5, 9, BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TEXT, "Done", BTN_END ); break; case 3: break; case 4: lcd_ShowKeypad(0); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_OK, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "OK", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 14, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 5, 9, BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TEXT, "Cancel", BTN_END ); break; case 5: // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_EXIT, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 6: // keyboard entry lcd_drawKeyboard(); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_NEXT, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Next", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 7: // clock with up/downs // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_SAVE, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // print date/time message lcd_Font("16x32i"); lcd_DispText(sys_message[MSG_DATE_TIME].msg, 30, 60, MODE_NORMAL); // Draw up/dn buttons lcd_ButtonDef( 0, // month + BTN_MOM, // momentary operation BTN_TLXY, 46, 100, // starting x,y for buttons BTN_MARGINS, 46, 264, // set left and right margins BTN_TYPE, BUTTON_RELEASE, BTN_SEP, 48, 40, // set up for button sep BTN_TEXT, "+", BTN_TXTOFFSET, 8, 1, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); // month lcd_ButtonDef( 2, BTN_MOM, BTN_TEXT, "+", BTN_END ); // day lcd_ButtonDef( 4, BTN_MOM, BTN_TEXT, "+", BTN_END ); // year lcd_ButtonDef( 6, BTN_MOM, BTN_TEXT, "+", BTN_END ); // hour lcd_ButtonDef( 8, BTN_MOM, BTN_TEXT, "+", BTN_END ); // min lcd_ButtonDef( 1, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 3, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 5, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 7, BTN_MOM, BTN_TEXT, "-", BTN_END ); lcd_ButtonDef( 9, BTN_MOM, BTN_TEXT, "-", BTN_END ); break; case 8: // PgUp, PgDn, Done // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_PREV, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "PgUp", BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_NEXT, BTN_TEXT, "PgDn", BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TEXT, "Exit", BTN_END ); break; case 9: lcd_ShowKeypad(1); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_NEXT, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Next", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 8, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 5, 330, // set left and right margins BTN_SEP, 63, 43, // set up for button sep BTN_TEXT, "Exit", BTN_TXTOFFSET, 15, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); break; case 10: // keyboard entry lcd_drawKeyboard(); // Draw bottom buttons lcd_Font("16B"); lcd_ButtonDef( BTN_OK, BTN_MOM, // momentary operation BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "OK", BTN_MARGINS, 5, 330, // set left and right margins BTN_TXTOFFSET, 14, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 5, 9, BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TEXT, "Cancel", BTN_END ); break; } } int lastBkColor; void lcd_resetMsgBackColor(void) { lastBkColor = -1; } void lcd_displayMsgs(char * msgNum) { // show traditional lcd messages on the color touch screen // static int lastBkColor; int newColor; char myBuf[MSG_LEN+1]; // for date time display #GLOBAL_INIT { lastBkColor = -1; } // DISABLE TOUCH BUTTONS lcd_Font("16x32i"); // TRANS LCD // check for showing alarm message in red switch (msgNum[0]) // set inside color // { case MSG_ALARM: lcd_BFcolorsB(lcd_WHITE, lcd_RED); break; // case MSG_CIC: lcd_BFcolorsB(lcd_BLACK, lcd_GREEN); break; // case MSG_DROPEN: lcd_BFcolorsB(lcd_BLACK, lcd_YELLOW); break; // default: lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); break; { case MSG_ALARM: newColor = lcd_RED; break; case MSG_CANT_SEND: newColor = lcd_RED; break; case MSG_CIC: newColor = lcd_GREEN; break; case MSG_DROPEN: newColor = lcd_YELLOW; break; default: newColor = lcd_WHITE; break; } if (newColor != lastBkColor) { // fill the box lcd_BFcolorsB(newColor, newColor); lcd_Rectangle(6, 6, 314, 71, 1); // inside paint lastBkColor = newColor; } if (msgNum[0]==MSG_PIN) refresh_PIN_message(msgNum[0], msgNum[1]); if (msgNum[1]==MSG_PIN) refresh_PIN_message(msgNum[1], msgNum[0]); //lcd_DispText(sys_message[msgNum[0]].msg, 30, 12, MODE_NORMAL); //lcd_DispText(sys_message[msgNum[1]].msg, 30, 42, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, newColor); lcd_DispText(sys_message[msgNum[0]].msg, 16, 8, MODE_NORMAL); lcd_DispText(sys_message[msgNum[1]].msg, 16, 38, MODE_NORMAL); // SYSTEM LCD // check for showing alarm message in red if (msgNum[2] == MSG_ALARM) lcd_BFcolorsB(lcd_WHITE, lcd_RED); else lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); // inside color //lcd_DispText(sys_message[msgNum[2]].msg, 30, 90, MODE_NORMAL); //lcd_DispText(sys_message[msgNum[3]].msg, 30, 120, MODE_NORMAL); if (msgNum[2]==MSG_PIN) refresh_PIN_message(msgNum[2], msgNum[3]); if (msgNum[3]==MSG_PIN) refresh_PIN_message(msgNum[3], msgNum[2]); lcd_DispText(sys_message[msgNum[2]].msg, 16, 75, MODE_NORMAL); lcd_DispText(sys_message[msgNum[3]].msg, 16, 105, MODE_NORMAL); // display clock and trans counter //lcd_Font("10"); //lcd_BFcolorsB(lcd_BLACK, lcd_LGREEN); // steal date/time from sys_message /* IF THE DATE/TIME AT THE BOTTOM COME BACK, NEED TO SURPRESS DURING A TRANSACTION strcpy(myBuf, &sys_message[MSG_DATE_TIME].msg[2]); myBuf[8]=0; myBuf[14]=0; lcd_DispText(myBuf, 158, 201, MODE_NORMAL); lcd_DispText(&myBuf[9], 165, 213, MODE_NORMAL); ltoa(transactionCount(), myBuf); lcd_DispText(myBuf, 190-strlen(myBuf)*10, 225, MODE_NORMAL); */ // ENABLE TOUCH BUTTONS } void lcd_printMessage(char line, char * msg) { // show traditional lcd messages on the color touch screen //char pw; // pen width //pw=3; int y; y=0; lcd_Font("16x32i"); switch (line) { case 0: y=8; break; case 1: y=38; break; case 2: y=75; break; case 3: y=105; break; } if (y>0) { lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); // inside color lcd_DispText(msg, 16, y, MODE_NORMAL); } } void lcd_processTouchScreen(int button) { // buttons from the main display // optionally process button passed as parameter // if button = -2 then check for a new button press //int button; if (button==-2) button = lcd_GetTouch(1); // reset screen saver if a button is pressed //if (button != -1) lcd_screenSaver(LCD_BRIGHT); switch (button) { case BTN_MENU: if (system_state==MALFUNCTION_STATE) lcd_enterSetupMode(0); // checking for IDLE is redundant since buttons are removed during a transaction else if (system_state==IDLE_STATE) lcd_enterSetupMode(1); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen break; case BTN_DIRECTORY: lcd_showDirectory(0); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen break; case BTN_HELP: lcd_helpScreen(0); // help->about lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen break; case BTN_STAT+256: // Stat on btnStatFlag=1; break; case BTN_STAT: // Stat off btnStatFlag=2; // Use =2 to trigger clearing of stat (timer, lcd message, ) break; case BTN_CRETURN: // aka Return From... lcd_showDirectory(1); lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen break; case BTN_ARETURN+256: // Auto return on btnAReturnFlag=1; break; case BTN_ARETURN: // Auto return off //lcd_showDirectory(2); //lcd_drawScreen(1, lcd_WITH_BUTTONS); // redraw main screen btnAReturnFlag=2; break; case BTN_SECURE+256: // Secure on btnSecureFlag=1; break; case BTN_SECURE: // Secure off btnSecureFlag=2; break; } } char lcd_stationButton; // for holding send-to requests char lcd_returnCarrierButton; // for holding returnCarrier requests char lcd_autoReturnButton; // for holding auto-return requests void lcd_showDirectory(char mode) { // show list of all active stations // mode 0 = standard directory // 1 = carrier-return directory // 2 = auto-return directory char i; int button; int xpos, ypos, dy; char buf[4]; char pin_msg[5]; buf[0]=0; buf[1]=0; // for station number text if (mode==0) lcd_drawScreen(5, "STATION DIRECTORY"); else if (mode==1) lcd_drawScreen(5, "RETURN CARRIER FROM"); else lcd_drawScreen(5, "SEND + AUTO RETURN"); lcd_Font("16B"); xpos=10; // initial x,y button position ypos=50; dy=39; for (i=0; i<LAST_STATION; i++) { if ((1<<i) & STATION_SET) { buf[0]='1'+i; // show a button with the station number lcd_ButtonDef( i+1, BTN_MOM, // momentary operation BTN_TLXY, xpos, ypos, // starting x,y for buttons BTN_MARGINS, 5, 200, // set left and right margins BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, buf, BTN_TXTOFFSET, 12, 9, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); if (remote_data[REMOTE_CIC] & (1<<i)) lcd_BFcolorsB(lcd_BLACK, lcd_GREEN); else lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.station_name[i+1].name, xpos+40, ypos, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.phoneNum[i+1], xpos+40, ypos+18, MODE_NORMAL); // show secure pin if one is active if (securePIN[i+1]>=0) { sprintf(pin_msg, "%04d", securePIN[i+1]); lcd_BFcolorsB(lcd_RED, lcd_WHITE); lcd_DispText(pin_msg, xpos+110, ypos+18, MODE_NORMAL); } // TO DO if (xpos==10) xpos=165; else { xpos=10; ypos+=dy; } } } // What about slave station if (slaveAvailable) { // show a button with the station number buf[0]='0'+SLAVE; lcd_ButtonDef( SLAVE, BTN_MOM, // momentary operation BTN_TLXY, xpos, ypos, // starting x,y for buttons BTN_TEXT, buf, BTN_END ); if (slave_cic) lcd_BFcolorsB(lcd_BLACK, lcd_GREEN); else lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.station_name[i+1].name, xpos+40, ypos, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.phoneNum[i+1], xpos+40, ypos+18, MODE_NORMAL); } // What about main station at the slave else if (param.slaveController) { // show a button with the station number buf[0]=param.station_name[0].name[0]; // take first character of name //='0'; lcd_ButtonDef( SLAVE, BTN_MOM, // momentary operation BTN_TLXY, xpos, ypos, // starting x,y for buttons BTN_TEXT, buf, BTN_END ); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.station_name[0].name, xpos+40, ypos, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(param.phoneNum[0], xpos+40, ypos+18, MODE_NORMAL); } // show legend at bottom for CIC lcd_BFcolorsB(lcd_BLACK, lcd_GREEN); lcd_DispText("Green", 5, 220, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); lcd_DispText(" = Carrier In Chamber", 0, 0, MODE_NORMAL); // Display active (next) secure pin if activated //if ((mode != 1) && (securePIN[0] >= 0)) lcd_DispText(&sys_message[MSG_PIN].msg[MSG_OFFSET+3], 5, 205, MODE_NORMAL); if ((mode != 1) && (securePIN[0] >= 0)) { refresh_PIN_message(MSG_PIN, MSG_AT); // MSG_AT leads to PIN 0 (next trans) lcd_BFcolorsB(lcd_RED, lcd_WHITE); lcd_DispText(sys_message[MSG_PIN].msg, 5, 205, MODE_NORMAL); } // Wait for a button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); // treat button as a send-to request or return-from request if ((button >= 0) && (button <= SLAVE)) lcd_stationButton = button; // set the function flags as needed lcd_returnCarrierButton = FALSE; lcd_autoReturnButton = FALSE; if (button != BTN_EXIT) { // set the appropriate flags if (mode==1) lcd_returnCarrierButton=TRUE; // is this a return carrier request? if (mode==2) lcd_autoReturnButton=TRUE; // is this an auto return request? } } char lcd_autoReturn(void) { // returns the lcd_autoReturnButton char rtnVal; #GLOBAL_INIT { lcd_autoReturnButton=0; } rtnVal = lcd_autoReturnButton; lcd_autoReturnButton=0; // reset whenever it is accesses return rtnVal; } char lcd_returnCarrier(void) { // returns the lcd_returnCarrierButton char rtnVal; #GLOBAL_INIT { lcd_returnCarrierButton=0; } rtnVal = lcd_returnCarrierButton; lcd_returnCarrierButton=0; // reset whenever it is accesses return rtnVal; } char lcd_sendTo(void) { // returns the lcd_stationButton char rtnVal; #GLOBAL_INIT { lcd_stationButton=0; } rtnVal = lcd_stationButton; lcd_stationButton=0; // reset whenever it is accesses return rtnVal; } int lcd_Center(char * string, char font) { int temp; if (font==1) temp = 160 - (int)(strlen(string) * 7); // "24" else if (font==2) temp = 160 - (int)(strlen(string) * 4); // "16" if (temp < 5) temp = 5; return temp; } void lcd_enterSetupMode(char operatorLevel) { int button; char mych; char keepLooping; char menu_idx; char page; char anotherPage; char showPage; char newLevel; char changed; keepLooping=TRUE; page=0; changed=FALSE; // None yet // clear the button input buffer lcd_GetTouch(1); anotherPage = lcd_ShowMenu(operatorLevel, page); // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands // inKey = getKey(); showPage=FALSE; button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= BTN_MNU_FIRST) && (button <= BTN_MNU_FIRST+MNU_LAST)) { menu_idx = button-BTN_MNU_FIRST; newLevel = operatorLevel; changed |= lcd_ProcessMenuItem(menu_idx, &newLevel); // Did we advance to a new menu if (newLevel != operatorLevel) { operatorLevel = newLevel; page=0; } // continue to show menu? if (operatorLevel==99) keepLooping=FALSE; // update display of menu items? if (!secTimeout(menu_timeout)) showPage=TRUE; } else if (button == BTN_PREV) { if (page>0) { page--; showPage=TRUE;} } else if (button == BTN_NEXT) { if (anotherPage) { page++; showPage=TRUE;} } //else if (button == BTN_SAVE) else if (button == BTN_CANCEL) // DONE { if (changed) { // save changes if needed lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_ClearScreen (); lcd_Origin( 0, 0 ); lcd_Font("24"); lcd_DispText("SAVING CHANGES ...", 10, 50, MODE_NORMAL); if (writeParameterSettings() == 0) lcd_DispText("\nCHANGES SAVED", 0, 0, MODE_NORMAL); else lcd_DispText("\nERROR SAVING CHANGES", 0, 0, MODE_REV); // Tell remotes to update/save parameters if (syncParametersToRemote()) lcd_DispText("\nREMOTES NOT SYNC'D", 0, 0, MODE_REV); msDelay(800); sendParametersToLogger(); // send parameters to data logger } keepLooping = FALSE; } //else if (button == BTN_CANCEL) keepLooping = FALSE; // show the same or next menu page if needed if (showPage && keepLooping) anotherPage = lcd_ShowMenu(operatorLevel, page); } } } void lcd_ShowTransactionProgress(char source, char dest, char direction, int progress, unsigned long transTimer) { // call this routine to update the display with transaction progress // source, dest are system station numbers 0-8 // direction is DIR_SEND (left to right) or DIR_RETURN (right to left) // progress is % of progress into transaction // transStartTime is time into transaction so far in seconds // CONSIDER TO SHOW TRANSACTION TIMER static char lastSource; static char lastDest; static char lastDirection; static char lastProgress; // as percentage 0-100 //static char last_CIC; static unsigned long lastTransTimer; static int x1, x2, y1, y2; int xmid; static char pw; // pen width #GLOBAL_INIT { // initialize local variables lastSource=0; lastDest=0; lastDirection=0; lastProgress=0; lastTransTimer=0; x1=6; x2=314; y1=176; y2=199; pw=1; } // show source station name if (source != lastSource) { lastSource=source; } // show destination station name if (dest != lastDest) { lastDest=dest; } // show state progress if ((progress != lastProgress)) // || (di_carrierInChamber != last_CIC)) { // draw a box using background // draw a boarder box lcd_PenWidth(pw); // last_CIC=di_carrierInChamber; // always remember last if (progress <= 100) { // any other progress just blank it out lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); // border color lcd_Rectangle(12, 163, 150, 203, 1); // blank out CIC lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); // border color lcd_Rectangle(x1-pw, y1-pw, x2+pw, y2+pw, 0); // fill box with specific progress and remainder lcd_Font("18BC"); if (direction == DIR_SEND) { // progress left to right xmid = x1 + (int)((x2-x1) * (long)progress/100); lcd_Rectangle(x1, y1, xmid, y2, 1); // fill left side progress lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); // unfill color lcd_Rectangle(xmid, y1, x2, y2, 1); // fill right side remaining lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_DispText("-->>", 150, y1+pw, MODE_TRANS); // show direction arrow } else { // progress right to left xmid = x2 - (int)((x2-x1) * (long)progress/100); lcd_Rectangle(xmid, y1, x2, y2, 1); // fill right side progress lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); // unfill color lcd_Rectangle(x1, y1, xmid, y2, 1); // fill left side remaining lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_DispText("<<--", 150, y1+pw, MODE_TRANS); // show direction arrow } // show the station names; NOTE: source is really main station and dest is remote station lcd_DispText(param.station_name[source].name, 10, y1+pw, MODE_TRANS); xmid = 305 - 11*strlen(param.station_name[dest].name); lcd_DispText(param.station_name[dest].name, xmid, y1+pw, MODE_TRANS); } else if (progress == 999) { // blank out when progress = 999 lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); // border color lcd_Rectangle(x1-pw, y1-pw, x2+pw, y2+pw, 1); } else { // otherwise handle CIC lcd_showCIC(0); } lastProgress=progress; } else { if (progress >= 100) lcd_showCIC(0); // only if no progress bar showing } // show transaction timer if (transTimer != lastTransTimer) { lastTransTimer=transTimer; } } void lcd_showCIC(char forceit) { // show CIC on screen return; } void lcd_ShowKeypad(char opts) { // display 0..9 in a keypad arrangement on the screen // opts = 0 = no '-' button // 1 = use '-' button char i; char btn[2]; i=1; // first digit 1 btn[0]=49; btn[1]=0; // draw first button lcd_Font("16B"); lcd_ButtonDef( '0'+i, BTN_MOM, // momentary operation BTN_TLXY, 200, 55, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_MARGINS, 200, 300, // set left and right margins BTN_SEP, 35, 35, // set up for button sep BTN_TEXT, btn, BTN_TXTOFFSET, 11, 9, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); // draw 2-9 for (i=2; i<10; i++) { btn[0]++; lcd_ButtonDef( '0'+i, BTN_TEXT, btn, BTN_END ); } // draw last buttons if (opts==1) // use '-' button { i='-'; btn[0]='-'; lcd_ButtonDef( i, BTN_TEXT, btn, BTN_END ); } // draw '0' i=0; btn[0]=48; lcd_ButtonDef( '0'+i, BTN_TEXT, btn, BTN_END ); // draw 'Del' lcd_ButtonDef( BTN_DEL, BTN_TXTOFFSET, 5, 9, BTN_TEXT, "Del", BTN_END ); } int lcd_SelectChoice(char *choice, char *label, char *optZero, char *optOne) { // Show label and two choices and allow selection // choice is modified as TRUE (optZero) or FALSE (optOne) based on selection // function returns 0 if cancel or 1 if a choice is made int button; lcd_drawScreen(3, "MENU"); lcd_Font("24"); lcd_DispText(label, lcd_Center(label, 1), 50, MODE_NORMAL); lcd_DispText(optZero, 150, 85, MODE_NORMAL); lcd_DispText(optOne, 150, 115, MODE_NORMAL); // show optZero choice lcd_ButtonDef( BTN_YES_ON, BTN_LAT, // latching operation BTN_TLXY, 110, 80, // starting x,y for buttons BTN_TYPE, (*choice) ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show optOne choice lcd_ButtonDef( BTN_NO_OFF, BTN_TLXY, 110, 110, // starting x,y for buttons BTN_TYPE, (*choice) ? BUTTON_LAT_0 : BUTTON_LAT_1, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show Cancel button lcd_Font("16B"); lcd_ButtonDef( BTN_CANCEL, BTN_MOM, // momentary operation BTN_TLXY, 257, 205, // starting x,y for buttons BTN_TYPE, BUTTON_RELEASE, BTN_TEXT, "Cancel", BTN_TXTOFFSET, 5, 9, BTN_BMP, BMP_med_button, BMP_med_button_dn, BTN_END ); // wait for button press & release menu_timeout = SEC_TIMER + 60; while( ((button = lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); // handle selection if (button == 256+BTN_NO_OFF) { // update screen *choice=FALSE; } else if (button == 256+BTN_YES_ON) { // update screen *choice=TRUE; } if ((button == BTN_CANCEL) || (button == -1)) return 0; // cancel or timeout else { // update scren to show choice lcd_ButtonDef( BTN_YES_ON, BTN_LAT, // latching operation BTN_TLXY, 110, 80, // starting x,y for buttons BTN_TYPE, *choice ? BUTTON_LAT_1 : BUTTON_LAT_0, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); // show optZero choice lcd_ButtonDef( BTN_NO_OFF, BTN_TLXY, 110, 110, // starting x,y for buttons BTN_TYPE, *choice ? BUTTON_LAT_0 : BUTTON_LAT_1, BTN_BMP, BMP_check_box, BMP_check_box_click, BTN_END ); msDelay(500); // wait so you can see the choice return 1; // got a choice } } char lcd_GetNumberEntry(char *description, unsigned long * par_value, unsigned long par_min, unsigned long par_max, char * par_units, char max_digits, char nc_as_ok) { // Allows numeric keypad entry using the touch screen // return value is 0 = *no change or cancel or timeout // 1 = valid number entered and updated to par_value // * no change returns 1 if nc_as_ok is true int button; char keepLooping; unsigned long inval; char number[11]; // for display of numeric text char numDigits; char rtnval; char i; inval=0; keepLooping=TRUE; numDigits=0; rtnval=0; // assume no good // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; // draw screen with keypad lcd_drawScreen(4, "ENTER VALUE"); // print title and place to print the number lcd_Font("18BC"); lcd_DispText(description, 15, 50, MODE_NORMAL); lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_DispText(par_units, 132, 88, MODE_NORMAL); // show actual, min and max lcd_Font("16B"); lcd_DispText("Min = ", 50, 120, MODE_NORMAL); lcd_DispText(ltoa((long)par_min, number), 0, 0, MODE_NORMAL); lcd_DispText("Current = ", 27, 140, MODE_NORMAL); lcd_DispText(ltoa((long)*par_value, number), 0, 0, MODE_NORMAL); lcd_DispText("Max = ", 47, 160, MODE_NORMAL); lcd_DispText(ltoa((long)par_max, number), 0, 0, MODE_NORMAL); // Setup for first character to display number[0]=0; number[1]=0; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= '0') && (button <= '9') && (numDigits < max_digits)) { // add the digit to the string number[numDigits]=button; numDigits++; number[numDigits]=0; // trailing null lcd_DispText(number, 50, 87, MODE_TRANS); // show the number } else if ((button == BTN_DEL) && (numDigits > 0)) { numDigits--; number[numDigits]=0; // trailing null // reprint the screen lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_DispText(number, 50, 87, MODE_TRANS); // show the number } else if (button == BTN_CANCEL) { keepLooping=FALSE; } else if (button == BTN_OK) { // was anything entered? if (numDigits==0) { // no entry if (nc_as_ok) { // return nc as ok rtnval=1; } else { lcd_DispText("NO CHANGE MADE", 50, 180, MODE_REV); msDelay(750); } keepLooping=FALSE; } else { inval = (unsigned long)atol(number); if ((inval >= par_min) && (inval <= par_max)) { keepLooping=FALSE; *par_value = inval; rtnval=1; } else { lcd_DispText("OUTSIDE RANGE", 50, 180, MODE_REV); msDelay(750); numDigits=0; number[0]=0; number[1]=0; lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_DispText(number, 50, 87, MODE_TRANS); // show the number } } } } } return rtnval; } void lcd_setClock() { int button; char keepLooping; struct tm time; unsigned long timedate; timedate=SEC_TIMER; mktm(&time, timedate); setTimeMessages(MSG_DATE_TIME, timedate); lcd_drawScreen(7, "SET DATE & TIME"); keepLooping=TRUE; menu_timeout = SEC_TIMER + 60; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_SAVE: // Done keepLooping=FALSE; break; case 0: // +month if (time.tm_mon<12) time.tm_mon++; break; case 1: // -month if (time.tm_mon>1) time.tm_mon--; break; case 2: // +day if (time.tm_mday<31) time.tm_mday++; break; case 3: // -day if (time.tm_mday>1) time.tm_mday--; break; case 4: // +year if (time.tm_year<140) time.tm_year++; break; case 5: // -year if (time.tm_year>100) time.tm_year--; break; case 6: // +hour if (time.tm_hour<23) time.tm_hour++; break; case 7: // -hour if (time.tm_hour>0) time.tm_hour--; break; case 8: // +minute if (time.tm_min<59) time.tm_min++; break; case 9: // -minute if (time.tm_min>0) time.tm_min--; break; } // update and print date/time message lcd_Font("16x32i"); timedate = mktime(&time); setTimeMessages(MSG_DATE_TIME, timedate); lcd_DispText(sys_message[MSG_DATE_TIME].msg, 30, 60, MODE_NORMAL); } } // put time back into timer and real-time-clock //write_rtc(timedate); if (!secTimeout(menu_timeout)) { // update only if not exiting due to timeout tm_wr(&time); SEC_TIMER = timedate; menu_timeout = SEC_TIMER + 60; } } char lcd_defineActiveStations() { // define the active stations // returns TRUE if activestations were changed char rtsIn; char done; char j, col, msgbuf[17]; char original; char inKey; char inputStations; int button; lcd_drawScreen(5, "DEFINE ACTIVE STATIONS"); lcd_DispText("PRESS ACTIVE SEND BUTTONS", 60, 50, MODE_NORMAL); lcd_Font("12x24"); strcpy(msgbuf, sys_message[MSG_BLANK].msg); // buffer to show stations original = STATION_SET; // save for later STATION_SET = 0xFF; // to allow requestToSend to return any pushbutton inputStations = 0; // reset if (param.headDiverter==TRUE) inputStations |= 0x80; done=FALSE; // Loop until done or timeout while ((done==FALSE) && !secTimeout(menu_timeout)) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); // If BTN_SAVE, save changes if (button == BTN_EXIT) // Exit button { STATION_SET = inputStations; done=TRUE; } // If station button, include bit and show on display rtsIn = firstBit(di_requestToSend); // P2P WORK TO BE DONE HERE if (rtsIn) { inputStations |= station2bit(rtsIn); col = (rtsIn * 2) -1; msgbuf[col] = 48 + rtsIn; //lcd_print(SYSTEMLCD, 1, msgbuf); lcd_DispText(msgbuf, 55, 80, MODE_NORMAL); menu_timeout = SEC_TIMER + 60; // reset menu timeout } } if (STATION_SET==0) STATION_SET = original; // don't allow zero stations param.activeStations = STATION_SET; if (STATION_SET == original) return FALSE; else return TRUE; } char lcd_editServerName() { // Returns TRUE if name changed char j, changed, col, msgbuf[25]; char keepLooping; int button; char inKey; changed=0; lcd_drawScreen(10, "EDIT SERVER NAME"); lcd_Font("12x24"); strncpy(msgbuf, "_", sizeof(param.serverID)); // fill with "_" lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name lcd_DispText(param.serverID, 20, 50, MODE_NORMAL); // show existing name lcd_Font("12x24"); col=0; keepLooping=TRUE; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_OK: // next message keepLooping=FALSE; break; case BTN_CANCEL: // finish changed=FALSE; keepLooping=FALSE; break; case 8: // backspace if (col>0) { if (col<11) msgbuf[col]='_'; col--; msgbuf[col]='_'; lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name } break; default: // ascii key if (col<sizeof(param.serverID)) { msgbuf[col]=button; col++; //msgbuf[col]='_'; lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name changed=TRUE; } break; } } } if (changed) { // store back into parameter space // replace _ with space // trim spaces j=sizeof(param.serverID); while (j>0) { // replace _ with null if (msgbuf[j]=='_') msgbuf[j]=0; // trim spaces if (msgbuf[j]>32) // first non-space { msgbuf[j+1]=0; j=0; } else --j; } // put name back into main storage if (msgbuf[0]!='_') strcpy(param.serverID, msgbuf); // check server connection?? } return changed; } nodebug char lcd_editStationNames() { // Returns TRUE if names changed char pos, j, changed, row, col, msgbuf[17]; char keepLooping; int button; char inKey; struct iomessage message; // in order to transmit to slave row=0; changed=0; lcd_drawScreen(6, "EDIT STATION NAMES"); lcd_Font("12x24"); while ((row <= SYSTEM_NAME) && !secTimeout(menu_timeout)) // row < number of names (0..SYSTEM_NAME) { // display this station name //strcpy(msgbuf, param.station_name[row].name); //strncat(msgbuf, " ", 16-strlen(msgbuf)); strcpy(msgbuf, "___________"); // fill with underscores //msgbuf[15]=0x30+row; // display number lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name lcd_DispText(param.station_name[row].name, 20, 50, MODE_NORMAL); // show existing name lcd_Font("16B"); lcd_DispText("(", 180, 55, MODE_NORMAL); // show the default name lcd_DispText(defaultStaName[row], 0, 0, MODE_NORMAL); // show the default name lcd_DispText(") ", 0, 0, MODE_NORMAL); // blank out leftovers lcd_Font("12x24"); col=0; keepLooping=TRUE; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_NEXT: // next message // row++; loop will increment row keepLooping=FALSE; break; case BTN_CANCEL: // finish keepLooping=FALSE; // row=99; break; case 8: // backspace if (col>0) { if (col<11) msgbuf[col]='_'; col--; msgbuf[col]='_'; lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name } break; default: // ascii key if (col<11) { msgbuf[col]=button; col++; //msgbuf[col]='_'; lcd_DispText(msgbuf, 20, 50, MODE_NORMAL); // show the name changed=TRUE; } break; } } } // replace _ with space // trim spaces j=10; while (j>0) { // replace _ with null if (msgbuf[j]=='_') msgbuf[j]=0; // trim spaces if (msgbuf[j]>32) // first non-space { msgbuf[j+1]=0; j=0; } else --j; } // put name back into main storage if (msgbuf[0]!='_') strcpy(param.station_name[row].name, msgbuf); // send name to remote station controller message.devAddr=ALL_DEVICES; message.command=SET_STATION_NAME; message.station=row; for (j=0; j<3; j++) { pos=j*4; message.data[0] = pos; message.data[1] = param.station_name[row].name[pos]; message.data[2] = param.station_name[row].name[pos+1]; message.data[3] = param.station_name[row].name[pos+2]; message.data[4] = param.station_name[row].name[pos+3]; // send this chunk msDelay(10); send_command(message); } if (button==BTN_CANCEL) row=99; else row++; // next item } if (changed) { // tell slave to finalize update message.devAddr=ALL_DEVICES; message.command=SET_STATION_NAME; message.station=69; // save to eeprom msDelay(10); send_command(message); } // rebuild station name messages buildStationNames(); return changed; } nodebug char lcd_editPhoneNums() { // Returns TRUE if phone numbers changed char pos, j, changed, row, col, msgbuf[10]; char keepLooping; char label[20]; int button; struct iomessage message; // in order to transmit to slave row=0; changed=0; lcd_drawScreen(9, "SET PHONE NUMBERS"); lcd_Font("12x24"); while ((row <= 10) && !secTimeout(menu_timeout)) // row < number of names (0..SYSTEM_NAME) { // display this station phone number and details strcpy(msgbuf, " "); // fill with spaces lcd_Font("18BC"); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); sprintf(label, "Phone # %d ", row); lcd_DispText(label, 50, 50, MODE_NORMAL); lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_Font("8x16"); // white out previous station name and number lcd_BFcolorsB(lcd_WHITE, lcd_WHITE); lcd_Rectangle(50, 115, 130, 155, 1); // show editable number, station name and existing number lcd_BFcolorsB(lcd_BLACK, lcd_LGREY); lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); lcd_DispText("\n\n", 0, 0, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); // show station name or admin or maint if (row<=8) lcd_DispText(param.station_name[row].name, 0, 0, MODE_NORMAL); // show the station name else if (row == ADMIN_PHONE) lcd_DispText("Administrator", 0, 0, MODE_NORMAL); else lcd_DispText("Maintenance ", 0, 0, MODE_NORMAL); lcd_DispText("\n", 0, 0, MODE_NORMAL); lcd_DispText(param.phoneNum[row], 0, 0, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_LGREY); //lcd_Font("12x24"); col=0; keepLooping=TRUE; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_NEXT: // next message keepLooping=FALSE; break; case BTN_CANCEL: // finish keepLooping=FALSE; break; case BTN_DEL: // backspace if (col>0) { if (col<8) msgbuf[col]=' '; col--; msgbuf[col]=' '; lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); // show the name } break; default: // ascii key //if ((button >= 0) && (button <= 9)) button += '0'; if (col<8) { msgbuf[col]=button; col++; lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); // show the name changed=TRUE; } break; } } } // trim spaces j=8; while (j>0) { // replace _ with null if (msgbuf[j]=='_') msgbuf[j]=0; // doesn't apply anymore but leave incase it comes back // trim spaces if (msgbuf[j]>32) // first non-space { msgbuf[j+1]=0; j=0; } else --j; } // put name back into main storage if (msgbuf[0]!='_') strcpy(param.phoneNum[row], msgbuf); // send name to remote station controller message.devAddr=ALL_DEVICES; message.command=SET_PHONE_NUMS; message.station=row; for (j=0; j<2; j++) { pos=j*4; message.data[0] = pos; message.data[1] = param.phoneNum[row][pos]; message.data[2] = param.phoneNum[row][pos+1]; message.data[3] = param.phoneNum[row][pos+2]; message.data[4] = param.phoneNum[row][pos+3]; // send this chunk msDelay(10); send_command(message); } if (button==BTN_CANCEL) row=99; // all done else row++; // next item } if (changed) { // tell slave to finalize update message.devAddr=ALL_DEVICES; message.command=SET_PHONE_NUMS; message.station=69; // save to eeprom msDelay(10); send_command(message); } return changed; } char lcd_editPortMapping(char *title) { // Returns TRUE if port mapping changed char pos, j, changed, row, col, msgbuf[10]; char keepLooping; char inputLength; char label[25]; // shows above edit box int button; struct iomessage message; // in order to transmit to slave row=1; changed=0; inputLength=2; // 0 to 99 max lcd_drawScreen(4, title); lcd_Font("12x24"); while ((row <= 7) && !secTimeout(menu_timeout)) // row < number of names (0..SYSTEM_NAME) { // display this device mapping details strcpy(msgbuf, " "); // fill with spaces lcd_Font("18BC"); lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); sprintf(label, "Device Addr %d Config", row); lcd_DispText(label, 25, 50, MODE_NORMAL); lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_Font("8x16"); lcd_DispText("You Must Reboot\nAfter Saving Changes!", 20, 160, MODE_NORMAL); // white out previous details lcd_BFcolorsB(lcd_WHITE, lcd_WHITE); lcd_Rectangle(50, 115, 130, 155, 1); // show editable device configuration number lcd_BFcolorsB(lcd_BLACK, lcd_LGREY); lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); lcd_DispText("\n\n", 0, 0, MODE_NORMAL); // show current config # lcd_BFcolorsB(lcd_BLACK, lcd_WHITE); //lcd_DispText(param.station_name[row].name, 0, 0, MODE_NORMAL); // show the station name //lcd_DispText("\n", 0, 0, MODE_NORMAL); sprintf(label, "Config # %d ", param.portMapping[row]); lcd_DispText(label, 0, 0, MODE_NORMAL); lcd_BFcolorsB(lcd_BLACK, lcd_LGREY); col=0; keepLooping=TRUE; while ( (keepLooping) && !secTimeout(menu_timeout) ) // go through each device address { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_OK: // next message keepLooping=FALSE; break; case BTN_CANCEL: // finish keepLooping=FALSE; break; case BTN_DEL: // backspace if (col>0) { if (col <= inputLength) msgbuf[col]=' '; col--; msgbuf[col]=' '; lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); // show the value } break; default: // ascii key if ((col < inputLength) && (button >= '0') && (button <= '9')) { // add digit to input buffer msgbuf[col]=button; col++; lcd_DispText(msgbuf, 54, 87, MODE_NORMAL); // show the value changed=TRUE; } break; } } } // put value back into main storage if ((button != BTN_CANCEL) && (msgbuf[0] != ' ')) param.portMapping[row] = (char) atoi(msgbuf); if (button==BTN_CANCEL) row=99; // all done else row++; // next item } return changed; } nodebug char lcd_enableAdvancedFeatures(char menu_level, char * description) { // get password for the requested level char reqdPW[5]; char altPW[5]; // for non-settable cfg (Colombo) PW char enteredPW[5]; char rtnVal; strcpy(altPW, "xxxx"); // start with pin that can't be entered // determine which password to compare with switch (menu_level) { case 2: strcpy(reqdPW, param.adminPassword); break; case 3: strcpy(reqdPW, param.maintPassword); break; case 4: strcpy(reqdPW, param.cfgPassword); strcpy(altPW, "<PASSWORD>"); break; // 2321 is always available default: reqdPW[0]=0; } rtnVal=FALSE; // assume no good if (strlen(reqdPW)==0) rtnVal=TRUE; else { // get the password/pin if (lcd_getPin(enteredPW, description)) { // allow entry of settable or alternate/fixed pin if ( (strcmp(enteredPW, reqdPW)==0) || (strcmp(enteredPW, altPW)==0) ) rtnVal=TRUE; else { // sorry charlie lcd_BFcolorsB( lcd_WHITE, lcd_RED); lcd_Font("24"); lcd_DispText(" INCORRECT PIN ", 17, 160, MODE_NORMAL); msDelay(2000); } } } return rtnVal; } nodebug char lcd_getPin(char *PIN, char *description) { // get a 4 digit pin from the touch screen int button; char keepLooping; char number[5]; // for storing entered digits char asteric[5]; // for display on screen char numDigits, maxDigits; char rtnval; char i; keepLooping=TRUE; numDigits=0; maxDigits=4; rtnval=0; // assume no good // Initialize 60 second menu timeout menu_timeout = SEC_TIMER + 60; // draw screen with keypad lcd_drawScreen(4, description); // print title and place to print the number lcd_Font("18BC"); lcd_DispText("ENTER 4 DIGIT PIN", 20, 50, MODE_NORMAL); lcd_DispBitmap( BMP_input_box, 45, 80 ); // show actual, min and max lcd_Font("32B"); // Setup for first character to display number[0]=0; number[1]=0; asteric[0]=0; asteric[1]=0; while ( (keepLooping) && !secTimeout(menu_timeout) ) { maintenance(); // watchdog, led activity, UDP commands button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; if ((button >= '0') && (button <= '9') && (numDigits < maxDigits)) { // add the digit to the string number[numDigits]=button; asteric[numDigits]='*'; numDigits++; number[numDigits]=0; // trailing null asteric[numDigits]=0; lcd_DispText(asteric, 50, 87, MODE_TRANS); // show the number } else if ((button == BTN_DEL) && (numDigits > 0)) { numDigits--; number[numDigits]=0; // trailing null asteric[numDigits]=0; // reprint the screen lcd_DispBitmap( BMP_input_box, 45, 80 ); lcd_DispText(asteric, 50, 87, MODE_TRANS); // show the number } else if (button == BTN_CANCEL) { keepLooping=FALSE; } else if (button == BTN_OK) { strcpy(PIN, number); keepLooping=FALSE; rtnval=1; } } } return rtnval; } void lcd_show_inputs() { // shows digital inputs on-screen for diagnosis char done; char j, col, msgbuf[17]; char inKey; int button; lcd_drawScreen(5, "SHOW DIGITAL INPUTS"); strcpy(msgbuf, sys_message[MSG_BLANK].msg); // buffer to show stations done=FALSE; // Loop until done or timeout while ((done==FALSE) && !secTimeout(menu_timeout)) { maintenance(); // watchdog, led activity, UDP commands menu_timeout = SEC_TIMER + 60; // never timeout like this button = lcd_GetTouch(100); // If BTN_SAVE, save changes if (button == BTN_EXIT) // Exit button { done=TRUE; } lcd_DispText("Arrival: ", 20, 50, MODE_NORMAL); lcd_DispText(di_carrierArrival ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nIn Chamber: ", 0, 0, MODE_NORMAL); lcd_DispText(di_carrierInChamber ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nDoor: ", 0, 0, MODE_NORMAL); lcd_DispText(di_doorClosed ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nSTAT: ", 0, 0, MODE_NORMAL); lcd_DispText(di_priorityRequest ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nReturn Carrier: ", 0, 0, MODE_NORMAL); lcd_DispText(di_returnCarrier ? "ON " : "OFF", 0, 0, MODE_NORMAL); lcd_DispText("\nSend Btns: ", 0, 0, MODE_NORMAL); sprintf(msgbuf, "%X ", di_requestToSend); lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); lcd_DispText("\nDiverter Pos: ", 0, 0, MODE_NORMAL); sprintf(msgbuf, "%X ", di_diverterPos); lcd_DispText(msgbuf, 0, 0, MODE_NORMAL); } } void lcd_clearMiddle(void) { // clears the space between the menu header and the buttons lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); lcd_Rectangle(1, 41, 320, 204, 1); // fill left side progress lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); } char * ltrim(char * text) { char i; i=0; while (text[i]==32) i++; return &text[i]; } nodebug void lcd_drawKeyboard() { lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_Font("24"); // draw alpha keyboard // the button ID for each button is its equivalent ASCII decimal value // first row lcd_ButtonDef( 49, BTN_MOM, BTN_TLXY, 0, 75, BTN_SEP, 32, 32, BTN_MARGINS, 0, 340-32, BTN_TYPE, BUTTON_PRESS, BTN_TEXT, "1", BTN_TXTOFFSET, 8, 5, BTN_BMP, BMP_button_up, BMP_button_dn, BTN_END ); lcd_ButtonDef( 50, BTN_TEXT, "2", BTN_END ); lcd_ButtonDef( 51, BTN_TEXT, "3", BTN_END ); lcd_ButtonDef( 52, BTN_TEXT, "4", BTN_END ); lcd_ButtonDef( 53, BTN_TEXT, "5", BTN_END ); lcd_ButtonDef( 54, BTN_TEXT, "6", BTN_END ); lcd_ButtonDef( 55, BTN_TEXT, "7", BTN_END ); lcd_ButtonDef( 56, BTN_TEXT, "8", BTN_END ); lcd_ButtonDef( 57, BTN_TEXT, "9", BTN_END ); lcd_ButtonDef( 48, BTN_TEXT, "0", BTN_END ); // second row lcd_ButtonDef( 81, BTN_TEXT, "Q", BTN_END ); lcd_ButtonDef( 87, BTN_TEXT, "W", BTN_END ); lcd_ButtonDef( 69, BTN_TEXT, "E", BTN_END ); lcd_ButtonDef( 82, BTN_TEXT, "R", BTN_END ); lcd_ButtonDef( 84, BTN_TEXT, "T", BTN_END ); lcd_ButtonDef( 89, BTN_TEXT, "Y", BTN_END ); lcd_ButtonDef( 85, BTN_TEXT, "U", BTN_END ); lcd_ButtonDef( 73, BTN_TEXT, "I", BTN_END ); lcd_ButtonDef( 79, BTN_TEXT, "O", BTN_END ); lcd_ButtonDef( 80, BTN_TEXT, "P", BTN_END ); // third row lcd_ButtonDef( 65, BTN_TEXT, "A", BTN_END ); lcd_ButtonDef( 83, BTN_TEXT, "S", BTN_END ); lcd_ButtonDef( 68, BTN_TEXT, "D", BTN_END ); lcd_ButtonDef( 70, BTN_TEXT, "F", BTN_END ); lcd_ButtonDef( 71, BTN_TEXT, "G", BTN_END ); lcd_ButtonDef( 72, BTN_TEXT, "H", BTN_END ); lcd_ButtonDef( 74, BTN_TEXT, "J", BTN_END ); lcd_ButtonDef( 75, BTN_TEXT, "K", BTN_END ); lcd_ButtonDef( 76, BTN_TEXT, "L", BTN_END ); lcd_ButtonDef( ':', BTN_TEXT, ":", BTN_END ); // fourth row lcd_ButtonDef( 90, BTN_TEXT, "Z", BTN_END ); lcd_ButtonDef( 88, BTN_TEXT, "X", BTN_END ); lcd_ButtonDef( 67, BTN_TEXT, "C", BTN_END ); lcd_ButtonDef( 86, BTN_TEXT, "V", BTN_END ); lcd_ButtonDef( 66, BTN_TEXT, "B", BTN_END ); lcd_ButtonDef( 78, BTN_TEXT, "N", BTN_END ); lcd_ButtonDef( 77, BTN_TEXT, "M", BTN_END ); lcd_ButtonDef( 46, BTN_TEXT, ".", BTN_END ); lcd_ButtonDef( 45, BTN_TEXT, "-", BTN_END ); lcd_Font("16B"); lcd_ButtonDef( 8, BTN_TEXT, "del", BTN_TXTOFFSET, 6, 10, BTN_END ); lcd_ButtonDef( 32, BTN_TEXT, "Space", BTN_TLXY, 114, 203, BTN_TXTOFFSET, 25, 10, BTN_BMP, BMP_92x32_button, BMP_92x32_button_dn, BTN_END ); } void lcd_showTransSummary() { // uses structure statistics : system summary statistics char myline[80]; // line to send to the lcd char * instr; // work pointer into myline long subtot; // total of transactions or alarms int button; button=0; while ( (button != BTN_EXIT) && !secTimeout(menu_timeout) ) { lcd_drawScreen(5, "TRANSACTION SUMMARY"); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 9, 9, BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TEXT, "Reset", BTN_END ); lcd_Font("8x12"); lcd_DispText(param.station_name[SYSTEM_NAME].name, 10, 50, MODE_NORMAL); lcd_DispText("\n Transactions:", 0, 0, MODE_NORMAL); sprintf(myline, "\n Incoming: %ld", statistics.trans_in); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\n Outgoing: %ld", statistics.trans_out); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\n Total Transactions: %ld", statistics.trans_in + statistics.trans_out); lcd_DispText(myline, 0, 0, MODE_NORMAL); //sprintf(myline, "\n Grand Total: %ld", transactionCount()); //lcd_DispText(myline, 0, 0, MODE_NORMAL); lcd_DispText("\n Alarms:", 0, 0, MODE_NORMAL); sprintf(myline, "\n Incomplete Delivery: %d", statistics.deliv_alarm); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\n Diverter Timeout: %d", statistics.divert_alarm); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\n Carrier Lift Timeout: %d", statistics.cic_lift_alarm); lcd_DispText(myline, 0, 0, MODE_NORMAL); subtot=statistics.deliv_alarm+statistics.divert_alarm+statistics.cic_lift_alarm; sprintf(myline, "\n Total Alarms: %ld", subtot); lcd_DispText(myline, 0, 0, MODE_NORMAL); // wait for any button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); if (button==BTN_CANCEL) { // Ask: Are You Sure? lcd_Font("16B"); lcd_BFcolorsB( lcd_LGREY, lcd_LGREY); // unfill color lcd_Rectangle(40, 100, 300, 160, 1); // fill white lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_Rectangle(40, 100, 300, 160, 0); // outline lcd_DispText("Press Reset again to confirm\nor Exit to cancel", 60, 115, MODE_TRANS); menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); if (button==BTN_CANCEL) { // OK to reset resetStatistics(); } else button=0; // don't really exit, just repaint the screen } } } struct logInfoType { char spare[4]; // available open space for data unsigned long xSF_Head; // Not used unsigned long xSF_Tail; // Not used unsigned long Head; // points to latest entry unsigned long Tail; // points to first entry (if both equal 0 then log is empty) char Ver; char spare2; // available open space for data } logInfo; unsigned long logInfoXaddr; // address to xmem for logInfo unsigned long logXaddr; // address to xmem for data log int SFAvailable; // Indicates if serial flash is available #define XMemLogMax 1000 #define SFLogMax 500000 long MaxLogEntries; // maximum number of events in either log #define LOG_VERSION 3 xmem void initTransLog(void) { struct trans_log_type trans; int status; int sf; long memOffset; char sbuf[80]; // allocate the xmem for header and log logInfoXaddr = xalloc(sizeof(logInfo)); // was 10, added 12 more (size of trans) logXaddr = xalloc(XMemLogMax * sizeof(trans)); lcd_Font("16"); // check for and init the serial flash (only in run mode) if (OPMODE == 0x80) sf = SF1000Init(); else sf = -3; if (sf==0) // will use SF instead of XMEM { SFAvailable=TRUE; MaxLogEntries=SFLogMax; lcd_DispText("Using Serial Flash for event log",0,0,MODE_NORMAL); } else { SFAvailable=FALSE; MaxLogEntries=XMemLogMax; lcd_DispText("Using xmem for event log",0,0,MODE_NORMAL); } // get the header to determine head and tail status = xmem2root( &logInfo, logInfoXaddr, sizeof(logInfo)); if (status != 0) { // error reading xmem sprintf(sbuf,"\nError %d initializing transaction log", status); lcd_DispText(sbuf,0,0,MODE_NORMAL); //printf("\nError %d initializing transaction log", status); } // if log version does not match then initialize log if (logInfo.Ver != LOG_VERSION) { // reinit log // start over from scratch logInfo.Tail=0; logInfo.Head=0; lcd_DispText("\nTransaction log reset\n",0,0,MODE_NORMAL); //printf("\nTransaction log reset\n"); // save the logInfo data logInfo.Ver = LOG_VERSION; root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } // make sure head/tail are plausible // either tail=0 and head=0..MaxLogEntries-1 // or tail=1..MaxLogEntries-1 and head=tail-1 else if ((logInfo.Tail<=logInfo.Head) && (logInfo.Head<MaxLogEntries)) { // OK sprintf(sbuf, "\nTrans log contains %ld entries\n", logInfo.Head-logInfo.Tail); lcd_DispText(sbuf,0,0,MODE_NORMAL); } else if ((logInfo.Tail>logInfo.Head) && (logInfo.Tail<MaxLogEntries)) { // OK sprintf(sbuf, "\nTrans log contains %ld entries\n", logInfo.Head + (MaxLogEntries-logInfo.Tail)); lcd_DispText(sbuf,0,0,MODE_NORMAL); } else { // NOT OK so reinitialize head and tail sprintf(sbuf,"\nTrans log reset due to inconsistent tail: %ld and head: %ld\n", logInfo.Tail, logInfo.Head); lcd_DispText(sbuf,0,0,MODE_NORMAL); logInfo.Tail=0; logInfo.Head=0; root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } } void checkSerialFlash() { // Show serial flash data and allow deep checking of transactions long iLong; int button; int sf; int attempts; char myline[80]; // line to send to the lcd lcd_drawScreen(5, "SERIAL FLASH INFO"); // add button to reset head/tail lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 9, 9, BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TEXT, "Reset", BTN_END ); lcd_Font("8x12"); lcd_DispText("Checking Serial Flash", 10, 50, MODE_NORMAL); sprintf(myline, "\nOPMODE = %x", OPMODE); lcd_DispText(myline, 0, 0, MODE_NORMAL); attempts=0; if (OPMODE == 0x80) { do { sf = SF1000Init(); attempts++; } while (sf && attempts < 200); } else sf = -3; switch (sf) { case 0: lcd_DispText("\nSerial Flash - Initialize OK", 0, 0, MODE_NORMAL); sprintf(myline, "\nDevice Type: %d", SF1000_Density_Value); lcd_DispText(myline, 0, 0, MODE_NORMAL); if (SF1000_Density_Value != DENS_8MB) lcd_DispText(" UNSUPPORTED SIZE", 0, 0, MODE_NORMAL); sprintf(myline, "\nBlock Size: %d", SF1000_Block_size); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nNumber of Blocks: %d", SF1000_Nbr_of_Blocks); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nTotal Bytes: %ld", SF1000_Unit_Bytes); lcd_DispText(myline, 0, 0, MODE_NORMAL); iLong = SF1000CheckWrites (0); sprintf (myline, "\nBlock 0 has been written %ld times", iLong ); lcd_DispText(myline, 0, 0, MODE_NORMAL); break; case -1: lcd_DispText("\nSerial Flash - Unknown Density", 0, 0, MODE_NORMAL); break; case -2: lcd_DispText("\nSerial Flash - Unknown Response", 0, 0, MODE_NORMAL); break; case -3: lcd_DispText("\nSerial Flash - Device Not Found", 0, 0, MODE_NORMAL); break; } sprintf(myline, "\nEvent Log Start %ld", logInfo.Tail); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nEvent Log End %ld", logInfo.Head); lcd_DispText(myline, 0, 0, MODE_NORMAL); // wait for any button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); if (button==BTN_CANCEL) { // Reset the head and tail pointers logInfo.Tail = 0; logInfo.Head = 0; // save head/tail back to xmem root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } } void analyzeEventLog() { // Check consistency of entries in the log and reset tail/head if needed // Valid entries have a date/time between 850,000,000 (Dec-2006) and current date/time (+ 1 month) // In case of log wrap-around, the date/time of a previous valid entry is greater than the next valid entry unsigned long lastTransDateTime; unsigned long newTail; unsigned long newHead; unsigned long savedTail; struct trans_log_type trans; long entry; int button; int foundStart; char myline[80]; // line to send to the lcd lastTransDateTime=0; entry=0; newTail=0; // assume for now it will be at the start newHead=0; savedTail=logInfo.Tail; lcd_drawScreen(5, "ANALYZE EVENT LOG"); lcd_Font("8x12"); lcd_DispText("Checking Log Consistency", 10, 50, MODE_NORMAL); sprintf(myline, "\nCurrent first entry %ld", logInfo.Tail); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nCurrent last entry %ld", logInfo.Head); lcd_DispText(myline, 0, 0, MODE_NORMAL); logInfo.Tail=0; // have to set tail to zero to get absolute entry references foundStart=FALSE; // Not yet while (entry < MaxLogEntries) { if (entry%100==0) { // update progress sprintf(myline, "Checking Entry %ld", entry); lcd_DispText(myline, 10, 110, MODE_NORMAL); maintenance(); } getTransaction(entry, &trans); if ((trans.start_tm > 850000000) && (trans.start_tm < SEC_TIMER+2592000)) { // good entry foundStart=TRUE; // is it before or after last entry if (trans.start_tm < lastTransDateTime) { // assume it is wrap around of the log newHead=entry-1; newTail=entry; } entry++; } else { // invalid entry if (foundStart) { // already found a good entry so stop now if (entry>0)newHead=entry; entry=MaxLogEntries+1; } else { // didn't find start yet so keep going entry++; newTail=entry; // Hope we find the start } } } logInfo.Tail=savedTail; // reset saved tail // show last entry checked sprintf(myline, "Checking Entry %ld", MaxLogEntries); lcd_DispText(myline, 10, 110, MODE_NORMAL); // Show new head and tail and ask if it should be retained sprintf(myline, "\nDetected first entry %ld", newTail); lcd_DispText(myline, 0, 0, MODE_NORMAL); sprintf(myline, "\nDetected last entry %ld", newHead); lcd_DispText(myline, 0, 0, MODE_NORMAL); // if it changed then ask if it should be kept if ((logInfo.Tail != newTail) || (logInfo.Head != newHead)) { lcd_DispText("\nAccept Detected Entries?", 0, 0, MODE_NORMAL); lcd_ButtonDef( BTN_CANCEL, BTN_TXTOFFSET, 9, 9, BTN_TLXY, 5, 205, // starting x,y for buttons BTN_TEXT, "Accept", BTN_END ); } else {lcd_DispText("\nEntries are consistent", 0, 0, MODE_NORMAL);} // wait for any button menu_timeout = SEC_TIMER + 60; while(((button=lcd_GetTouch(100)) == -1) && !secTimeout(menu_timeout) ) maintenance(); // Was Accept button pressed if (button==BTN_CANCEL) { // keep the new entries logInfo.Tail = newTail; logInfo.Head = newHead; // save head/tail back to xmem root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); } } void addSecureTransaction(struct secure_log_type secTrans) { // map secure trans data into trans log and save // also works for standard card scans struct trans_log_type trans; char extra; // used for station # trans.trans_num = secTrans.trans_num; trans.start_tm = secTrans.start_tm; trans.duration = (secTrans.sid[1] << 8) + secTrans.sid[0]; trans.source_sta = secTrans.sid[2]; trans.dest_sta = secTrans.sid[3]; trans.status = secTrans.status; trans.flags = secTrans.sid[4]; extra = secTrans.flags; // contains the station # if (secTrans.scanType == 2) { trans.status = ESTS_CARD_SCAN; trans.trans_num = transactionCount()+1; // maybe just temporary sendUDPtransaction(trans, extra); // just send, don't log } else addTransaction(trans, extra); // add to log and send } void addTransaction(struct trans_log_type trans, char xtra) { long memOffset; int sf; // Push the transaction into local xmem memOffset = logInfo.Head * sizeof(trans); if (SFAvailable) { // write to serial flash while ( (sf=SF1000Write ( memOffset, &trans, sizeof(trans) )) == -3 ); } else { // write to xmem root2xmem( logXaddr+memOffset, &trans, sizeof(trans)); sf=0; } if (sf==0) // did we save ok? { // update the log pointers logInfo.Head++; // increment logHead if (logInfo.Head==MaxLogEntries) logInfo.Head=0; // check for wraparound if (logInfo.Head==logInfo.Tail) // check for full log { logInfo.Tail++; // bump the tail if (logInfo.Tail==MaxLogEntries) logInfo.Tail=0; // check for wraparound } } // save head/tail back to xmem root2xmem( logInfoXaddr, &logInfo, sizeof(logInfo)); //printf("\nAdded transaction at %ld with status %d and flags %d\n", SEC_TIMER, (int)trans.status, (int)trans.flags); // now send out the UDP message sendUDPtransaction( trans, xtra ); } long sizeOfTransLog(void) { // how many entries in the log if ((logInfo.Tail<=logInfo.Head) && (logInfo.Head<MaxLogEntries)) { // OK return logInfo.Head-logInfo.Tail; } else if ((logInfo.Tail>logInfo.Head) && (logInfo.Tail<MaxLogEntries)) { // OK, head before tail return logInfo.Head + (MaxLogEntries-logInfo.Tail); } else return 0; } int getTransaction(long entry, struct trans_log_type *trans) { // returns the n'th entry in the trans log (flash or xmem) // entry can be 0 .. sizeOfLog-1 // return value = 0 if success or 1 if entry non-existant long memOffset; if (entry >= MaxLogEntries) return 1; memOffset = ((logInfo.Tail+entry) % MaxLogEntries) * sizeof(*trans); if (SFAvailable) SF1000Read ( memOffset, trans, sizeof(*trans)); else xmem2root( trans, logXaddr+memOffset, sizeof(*trans)); if (entry >= sizeOfTransLog()) return 1; else return 0; } //#define RS232_MONITOR_F void uploadTransLog() { // open UDP port and transmit the log long entry; char j; struct trans_log_type log; struct tm time; unsigned long startTime; // give some status lcd_drawScreen(3, "UPLOAD LOG"); lcd_Font("24"); lcd_DispText("In progress ...", 80, 80, MODE_NORMAL); // show the default name for (entry=0; entry<sizeOfTransLog(); entry++) { // get entry if (getTransaction(entry, &log) == 0) { // send the transaction to the server sendUDPtransaction( log, 0 ); // wait till the socket is empty to pace the transmission startTime = MS_TIMER; while ((sock_tbused(&sock) > 0) && ((MS_TIMER-startTime) < 500)) maintenance(); } maintenance(); } } void downloadTransLog(int numDays) { // open com port and transmit the log char buf[120]; char crlf[3]; long entry; char j; struct trans_log_type log; struct tm time; unsigned long startTime; crlf[0]=13; crlf[1]=10; crlf[2]=0; // give some status lcd_drawScreen(3, "DOWNLOAD LOG"); lcd_Font("24"); lcd_DispText("In progress ...", 80, 80, MODE_NORMAL); // show the default name // open com port serFdatabits(PARAM_8BIT); serFparity(PARAM_NOPARITY); serFopen(19200); // write header mktm(&time, SEC_TIMER); sprintf(buf,"%s Transaction Log Dump at %02d/%02d/%02d %02d:%02d:%02d%s", param.station_name[SYSTEM_NAME].name, time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, crlf); serFputs(buf); sprintf(buf, "Date,Time,Source,Destination,Duration,Status,Flags%s", crlf); serFputs(buf); for (entry=0; entry<sizeOfTransLog(); entry++) { // get entry if (getTransaction(entry, &log) == 0) { mktm(&time, log.start_tm); // within date range? if (((SEC_TIMER - log.start_tm)/86400) <= numDays) { // within range so download this record if (log.status <= LAST_TRANS_EVENT) { // format entry sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,%s,%d,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, log.source_sta < SYSTEM_NAME ? param.station_name[log.source_sta].name : "??", log.dest_sta < SYSTEM_NAME ? param.station_name[log.dest_sta].name : "??", //(int)(log.duration - log.start_tm), log.duration, (int)log.status, (int)log.flags, crlf ); } else if (log.status == ESTS_DOOROPEN) { // This is a door open event sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,,%d,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "DOOR OPEN IN TRANS", log.duration, (int) log.status, (int) log.flags, crlf ); } else if (log.status == ESTS_MANPURGE) { // This is a manual purge event sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,%d,%d,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "MANUAL PURGE", log.dest_sta, log.duration, (int) log.status, (int) log.flags, crlf ); } else if (log.status == ESTS_AUTOPURGE) { // This is an automatic purge event sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,,%d,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "AUTOMATIC PURGE", log.duration, (int) log.status, (int) log.flags, crlf ); } else if (log.status == ESTS_SECURE_REMOVAL) { // This is a secure transaction removal event sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,%s,%ld,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, log.flags < SYSTEM_NAME ? param.station_name[log.flags].name : "??", "SECURE ID", (* (unsigned long*) &log.duration) - CARDBASE, (int) log.status, (int) log.flags, crlf ); } else { // otherwise unknown type sprintf(buf, "%02d/%02d/%02d,%02d:%02d:%02d,%s,,%d,%d,%d%s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "UNKNOWN STATUS", log.duration, (int) log.status, (int) log.flags, crlf ); } // make sure there is space in the buffer startTime = MS_TIMER; while ((serFwrFree() < FOUTBUFSIZE) && ((MS_TIMER-startTime) < 500)) maintenance(); // write to com port serFputs(buf); } } maintenance(); } startTime = MS_TIMER; // wait for buffer to empty while ((serFwrUsed() != 0) && ((MS_TIMER-startTime) < 1000)) maintenance(); // close com port msDelay(20); // wait till last character is sent serFclose(); } #define TRANS_PER_PAGE 10 void lcd_showTransactions(char format) { // shows the transaction log on the screen // format = 1 = only show alarms long page; long lastPage; int button; int transPerPage; // count how many pages we can show page=0; lastPage = sizeOfTransLog() / TRANS_PER_PAGE; if (format==1) lastPage = 0; lcd_drawScreen(8, "TRANSACTION LOG"); // redraw main screen lcd_showTransPage(page, lastPage, format); button=0; while ((button != BTN_CANCEL) && !secTimeout(menu_timeout)) { maintenance(); button = lcd_GetTouch(100); if (button != -1) { // valid button pressed menu_timeout = SEC_TIMER + 60; switch( button ) { case BTN_PREV: if (page > 0) page--; else page=lastPage; // allow wraparound lcd_showTransPage(page, lastPage, format); break; case BTN_NEXT: if (page < lastPage) page++; else page=0; // allow wraparound lcd_showTransPage(page, lastPage, format); break; } } } } void lcd_showTransPage(long page, long lastPage, char format) { // page 0 shows the last transaction int x; int y, dy; long entry; char j; char buf[80]; char UID[UIDLen]; char UIDstr[13]; struct trans_log_type trans; struct tm time; //strcpy(buf, "mm/dd/yy hh:mm:ss sourcesta.. -> destinsta.. sss sec"); entry = sizeOfTransLog() -1 - page * TRANS_PER_PAGE; j=0; y=44; dy=14; x=5; lcd_Font("6x9"); // print header sprintf(buf, "DATE TIME FROM TO Sec StFl"); lcd_DispText(buf, x, y, MODE_NORMAL); y+=dy; while ( (j < TRANS_PER_PAGE) && (entry >= 0) ) //< sizeOfTransLog())) { if (getTransaction(entry, &trans) == 0) { mktm(&time, trans.start_tm); lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); if (trans.status <= LAST_TRANS_EVENT) { // This is a transaction sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-11s-> %-11s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, trans.source_sta < SYSTEM_NAME ? param.station_name[trans.source_sta].name : "??", trans.dest_sta < SYSTEM_NAME ? param.station_name[trans.dest_sta].name : "??", trans.duration, (int) trans.status, (int) trans.flags ); if (trans.status != 0) lcd_BFcolorsB( lcd_RED, lcd_WHITE); // alarm trans colors else if (trans.flags & (FLAG_STAT | FLAG_SECURE)) lcd_BFcolorsD( 0xAA0, 0xFFF); //lcd_BFcolorsB( lcd_YELLOW, lcd_WHITE); // stat trans colors else if (trans.flags & (FLAG_CRETURN | FLAG_ARETURN | FLAG_ARETURNING)) lcd_BFcolorsB( lcd_GREEN, lcd_WHITE); // c.return trans colors //else lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); } else if (trans.status == ESTS_DOOROPEN) { // This is a door open event sprintf(buf, " %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_hour, time.tm_min, time.tm_sec, "DOOR OPEN IN TRANS", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_MAGENTA, lcd_WHITE); } else if (trans.status == ESTS_MANPURGE) { // This is a manual purge event sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "MANUAL PURGE", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); } else if (trans.status == ESTS_AUTOPURGE) { // This is an automatic purge event sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "AUTOMATIC PURGE", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_BLUE, lcd_WHITE); } else if (trans.status == ESTS_SECURE_REMOVAL) { // This is a secure transaction removal event // sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-11s %-10s %6ld %2x%2x", // time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, // trans.flags < SYSTEM_NAME ? param.station_name[trans.flags].name : "??", // "SECURE ID", // (* (unsigned long*) &trans.duration) - CARDBASE, // (int) trans.status, (int) trans.flags ); UID[0] = (char) trans.duration >> 8; UID[1] = (char) trans.duration && 0xFF; UID[2] = trans.source_sta; UID[3] = trans.dest_sta; UID[4] = trans.flags; UID_Decode(UID, UIDstr); sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-10s %-12s", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "SECURE ID", UIDstr); lcd_BFcolorsD( 0xAA0, 0xFFF); } else { // unknown entry type sprintf(buf, "%02d/%02d/%02d %02d:%02d:%02d %-25s %3d %2x%2x", time.tm_mon, time.tm_mday, time.tm_year%100, time.tm_hour, time.tm_min, time.tm_sec, "UNKNOWN STATUS", trans.duration, (int) trans.status, (int) trans.flags ); lcd_BFcolorsB( lcd_GREY, lcd_WHITE); } // Display record unless it is blank or supressed by format if (trans.status != ESTS_BLANK) { if ((format==0) || (trans.status>0 && trans.status<LAST_TRANS_EVENT)) { // ok to show lcd_DispText(buf, x, y, MODE_NORMAL); y+=dy; j++; } } } entry--; } if (j < TRANS_PER_PAGE) { // clear the rest of the work area lcd_BFcolorsB( lcd_WHITE, lcd_WHITE); lcd_Rectangle(1, y, 320, 204, 1); // fill left side progress lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); } lcd_showPage(page+1, lastPage+1); } void lcd_showPage(long thisPage, long lastPage) { // show page x of y char buf[25]; sprintf(buf, "Page %ld of %ld ", thisPage, lastPage); lcd_Font("6x9"); lcd_BFcolorsB( lcd_BLACK, lcd_WHITE); lcd_DispText(buf, 145, 218, MODE_NORMAL); } /* void lcd_screenSaver(char brightness) { // lower brightness after 60 seconds of dim command // works like a 2-state watchdog. if brightness is not LCD_BRIGHT after 60 sec then make dim static char lastBright; static unsigned long dimTimer; #GLOBAL_INIT { lastBright==LCD_BRIGHT; dimTimer=MS_TIMER; } if ((brightness==LCD_BRIGHT) && (lastBright==LCD_DIM)) { lcd_Backlight(LCD_DIM); //brightness); dimTimer=MS_TIMER; } else if (brightness == LCD_DIM) { if (MS_TIMER - dimTimer > 60000) { lcd_Backlight(LCD_DIM); //brightness); dimTimer=MS_TIMER; // retrys again in 60 sec } } } */ // TCP web server interface int tcpServerCheck() { // Issue HTTP request to system server for status information // Process returned information // TCPIP buffer is global int status; int ii; unsigned long tcpWaitTimer; unsigned long processTime; static int usrcount; char postContent[50]; char msgbuf[30]; struct tm timeptr; // always open the socket //printf("\nOpen TCP socket %ld\n", MS_TIMER); processTime = MS_TIMER; message_add(SYSTEMLCD, MSG_CHECKING_SERVER1, MSG_CHECKING_SERVER2, ONESHOT); if (!tcp_open(&tcpsock, 0, resolve(param.serverID), 80, NULL)) printf("TCP Failed to open %ld\n", MS_TIMER - processTime); else { //printf("Wait for established %ld\n", MS_TIMER - processTime); while(!sock_established(&tcpsock)) { if (!tcp_tick(&tcpsock)) { printf("TCP Failed to establish %ld\n", MS_TIMER - processTime); break; } } } if (sock_established(&tcpsock)) { //printf("TCP socket ready %ld!\n", MS_TIMER - processTime); // build sync timestamp from param.UIDSync mktm(&timeptr, param.UIDSync); sprintf(postContent,"sysnum=%d&trct=%ld&rno=%d&gao=%d&refr=%04d%02d%02d%02d%02d%02d", param.systemNum, transactionCount(), param.UIDRecNo, UID_GetAddOnly, timeptr.tm_year+1900, timeptr.tm_mon, timeptr.tm_mday, timeptr.tm_hour, timeptr.tm_min, timeptr.tm_sec); //sprintf(postContent,"sysnum=%d&trct=%d&refr=%s", 20, 1434, "20131028000000"); sprintf(tcpBuffer,"GET %s?%s\n HTTP/1.1\nHost: %s\n\n","/pts/web/app.php/sys2321", postContent, param.serverID); //printf("%s\n", tcpBuffer); sock_puts(&tcpsock,tcpBuffer); // wait for bytes to be ready OR TIMEOUT ii=-1; tcpWaitTimer = MS_TIMER; while((ii < 0) && (!Timeout(tcpWaitTimer, 2000))) { ii=sock_bytesready(&tcpsock); tcp_tick(&tcpsock); } // printf("sock_bytesready = %d %ld\n", ii, MS_TIMER - processTime); // printf("a.Socket state %d %ld\n", tcp_tick(&tcpsock), MS_TIMER - processTime); // get the response message if (ii>0) ii=sock_gets(&tcpsock,tcpBuffer,ii < sizeof(tcpBuffer) ? ii : sizeof(tcpBuffer)); if (ii>0) { printf("%s\n",tcpBuffer); // parse for UID records and add/del as needed lcd_printMessage(3, "CHECKING NEW USERS"); status = UID_Parse(tcpBuffer); // parse and process UID records Sync_Clock(tcpBuffer); // set date/time from server // Check for discontinuous transaction record msgbuf[0]=0; // no message yet if (status == 50) pingTimer = SEC_TIMER - 1; // trigger another server check for next block if (status == 0) { usrcount = 0; // all done UID_GetAddOnly = 0; // all up to date, ok to accept deletes } if (status == -1) { // put up a message sprintf(msgbuf, " ADD USER FAILED "); } else if (status > 0) { usrcount += status; sprintf(msgbuf, "%4d USERS CHANGED ", usrcount); } if (msgbuf[0] > 0) // if we have a message then show it { lcd_printMessage(3, msgbuf); msDelay(1000); } //printf("Done %ld\n", MS_TIMER - processTime); } else printf("No data in sock_gets %ld\n", MS_TIMER - processTime); //printf("b.Socket state %d %s %ld\n", tcp_tick(&tcpsock), sockstate(&tcpsock), MS_TIMER - processTime); } // perform check of parameter flash write timer Param_Flash_Write(3); // ip_print_ifs(); return 0; } ////////////////////////// // USER ID FUNCTIONS ////////////////////////// int UID_Add(char *ID) { // add the given 12 byte UID to the list and return the position added (-1 if can't add) // first search to make sure ID doesn't already exist int i; char blank[UIDLen]; char enc[UIDLen]; if (UID_Encode(ID, enc) >= 0) { // failed to encode i = UID_Search(enc); if (i == -1) { // not found so add the first blank entry memset(blank, 0, UIDLen); // make blank for (i=0; i<UIDSize; i++) { // if (memcmp(param.UID[i], blank, UIDLen) == 0) { // stick it here and return i memcpy(param.UID[i], enc, UIDLen); return i; } } // what? no blanks?? } else { // already in there so return that index return i; } } return -1; } int UID_Del(char *ID) { // clear out one or all user UID's // ID is the 12 byte representation // return 0 if success, -1 if failed or not found char enc[UIDLen]; int i; if (ID==NULL) { // erase all UID's for (i=0; i<UIDSize; i++) { memset(param.UID[i], 0, UIDLen); } param.UIDSync = 0; // reset sync timestamp param.UIDRecNo = 0; return 0; } else { if (UID_Encode(ID, enc) >= 0) { i = UID_Search(enc); if (i >= 0) { memset(param.UID[i], 0, UIDLen); return 0; } } } return -1; } int UID_Search(char *ID) { // search for the given 5-byte UID and return the position // returns index of match or -1 if no match int i; for (i=0; i<UIDSize; i++) { if (memcmp(param.UID[i], ID, UIDLen) == 0) return i; } return -1; } int UID_Get(int UIndex) { // return the (6 or 12 byte)? UID at position UIndex } int UID_Send(char *UID, char how) { // send the 12 byte UID to the remote stations // how = 1 to add, 0 to delete // if UID[0] > 99 and how = delete then send delete-all // returns 0 if successful, 1 if failed struct iomessage cmd; int status; int i; char enc[UIDLen]; status=0; // assume none good if (UID_Encode(UID, enc) >= 0) { if (UID[0]=='d') enc[0]='d'; // to trigger delete all cmd.station=0; for (i=0; i<UIDLen; i++) cmd.data[i]=enc[i]; // byte 1-5 cmd.command = how ? UID_ADD : UID_DEL; msDelay(100); // it takes the diverter 95 msec to retransmit to the remotes for (i=1; i<=MAX_DEVADDRS; i++) { if ( (1 << (i-1)) & availableDevices ) // if i is a remote devAddr { hitwd(); cmd.devAddr=i; if (send_command(cmd)==1) status |= (1 << (i-1)); } } } return (status == availableDevices) ? 0 : 1; } unsigned int UID_Cksum() { // calculate checksum of all valid UIDs } int UID_Encode(char *UID, char *Result) { // convert 12 byte string into 5 byte UID // Result must be sized to handle 5 bytes // Return -1 if invalid UID or 0 if success // char Buf[3]; // int i; // int res; // for (i=0; i<6; i++) // { // strncpy(Buf, &UID[i*2], 2); // res = atoi(Buf); // if (res <= 99 && res >= 0) Result[i] = res; // else return -1; // } // return 0; int i; int hval; int carry; unsigned long lval; unsigned long llast; unsigned long incr; char hdig[4]; // high 3 digits char ldig[10]; // low 9 digits // assuming length of 12 // split at 3/9 and get decimal equivalent strncpy(hdig, UID, 3); hdig[3]=0; strcpy(ldig, &UID[3]); hval = atoi(hdig); lval = atol(ldig); // do the math incr = 1000000000; llast = lval; carry=0; for (i=0; i<hval; i++) { // long math loop lval = lval + incr; if (lval<llast) carry++; llast = lval; } // transfer back into Result Result[0] = (char)carry; Result[1] = (char)((lval >> 24) & 0xFF) ; Result[2] = (char)((lval >> 16) & 0xFF) ; Result[3] = (char)((lval >> 8) & 0XFF); Result[4] = (char)((lval & 0XFF)); return 0; } int UID_Decode(char *UID, char *Result) { // convert 5 byte UID into 12 byte string // Result must be sized to handle 12+1 bytes // Return -1 if invalid UID or 0 if success // int i; // int res; // for (i=0; i<6; i++) // { // if (UID[i] >=0 && UID[i] <=99) sprintf(&Result[i*2], "%02d", UID[i]); // else return -1; // } // return 0; int i; unsigned long lval; unsigned long ba; unsigned long bm; unsigned long lo; int hi; int hval; // setup the math lval = (unsigned long)UID[1] << 24; lval = lval | (unsigned long)UID[2] << 16; lval = lval | (unsigned long)UID[3] << 8; lval = lval | (unsigned long)UID[4]; hval = (int)(UID[0]<<4) + (int)((lval & 0xF0000000)>>28); // how many times to loop lo = lval & 0x0FFFFFFF; // highest byte in hi hi=0; ba = 0x10000000; // add this bm = 1000000000; // mod this for (i=0; i<hval; i++) { // do the long math lo = lo + ba; // add hi += (int)(lo / bm); // mod lo = lo % bm; // div } // now put into string snprintf(Result, 13, "%d%09lu", hi, lo); Result[12]=0; // null term return 0; } int UID_Parse(char *UIDBuffer) { // parse through input string for UID's and add or delete them as needed // returns the quantity of user records found (add or delete) // or -1 if add failed or send failed // sets flash write timer to trigger next event char * Ubuf; char action; char UID[15]; // could be a date code as well int UIndex; int i; int iadd; int ii; int isend; int stop; int retval; unsigned long tempsync; retval=0; iadd=0; isend=0; // specify input key to find in the buffer Ubuf = strstr(UIDBuffer, "users["); if (Ubuf != NULL) { UIndex = 6; // first user // loop through string until no more while (UIndex > 0) { action = Ubuf[UIndex]; UIndex++; // get the UID // next digits, up to 12 or 15 i=0; stop=0; while (!stop && i<15) { if (isdigit(Ubuf[UIndex+i])) UID[i]=Ubuf[UIndex+i]; else stop=1; i++; } i--; // gone one too far UID[i]=0; // add null term UIndex += i; if (i >= 1) // at least 1 digit { if (action == '+') { i=UID_Add(UID); if (i==-1) iadd=-1; // capture add failure ii=UID_Send(UID, 1); // send add to remotes printf("Add UID %d %d %s\n", i, ii, UID); if (ii) { isend=-1; printf("FAILED to send %s\n", UID); } retval++; } else if (action == '-') { i=UID_Del(UID); ii=UID_Send(UID, 0); // send del to remotes printf("Del UID %d %d %s\n", i, ii, UID); if (ii) { isend=-1; printf("FAILED to send %s\n", UID); } retval++; } else if (action == 'e') // sync date { if (iadd==0 && isend==0) tempsync = cvtTime(UID, 0); // will only sync if no more records at this sync } else if (action == 'l') // sync record number { if ((iadd==0) && (isend==0)) { param.UIDRecNo = atoi(UID); // only if no add or send failure if (param.UIDRecNo == 0) { // only updtae time sync when record sync is 0 param.UIDSync = tempsync; printf("Time sync at %s\n", UID); } else { printf("Rec sync at %d\n", param.UIDRecNo); } } } } // move to next token or end // ,+ or ,- or ,d if (Ubuf[UIndex] == ',') UIndex ++; // next else UIndex = 0; // done } // setup next flash write trigger whenever new users are found if (retval > 0) Param_Flash_Write(2); } if ((iadd==-1) || (isend==-1)) retval=-1; // return -1 for any add or send failure return retval; } int Sync_Clock(char *Buffer) { // parse through input string for server clock time and apply here char * Ubuf; Ubuf = strstr(Buffer, "time["); if (Ubuf != NULL) { // date/time starts at Ubuf + 5 Ubuf += 5; cvtTime(Ubuf,1); // sync RTC } } unsigned long cvtTime(char *timestring, char setRTC) { // take time packed string and convert to timestamp // timestring is YYYYMMDDHHMMSS // set identifies if system time should be set (0 = no) char Buf[5]; struct tm timeptr; unsigned long timerval; // put into time structure for conversion strncpy(Buf, &timestring[12], 2); timeptr.tm_sec = atoi(Buf); strncpy(Buf, &timestring[10], 2); timeptr.tm_min = atoi(Buf); strncpy(Buf, &timestring[8], 2); timeptr.tm_hour = atoi(Buf); strncpy(Buf, &timestring[6], 2); timeptr.tm_mday = atoi(Buf); strncpy(Buf, &timestring[4], 2); timeptr.tm_mon = atoi(Buf); strncpy(Buf, &timestring[0], 4); timeptr.tm_year = atoi(Buf)-1900; timerval = mktime(&timeptr); // are we syncing the RTC? if (setRTC) { tm_wr(&timeptr); SEC_TIMER = timerval; setTimeMessages(MSG_DATE_TIME, timerval); syncDateAndTime(); // send to slave } return timerval; } int UID_ResyncAll() { // clear all users, reload from server, send to remotes // just need to clear the sync-timestamp and the system naturally reconstructs char UID[13]; int i; UID_Del(NULL); // delete local list UID[0]='d'; // trigger remotes to delete all for (i=1; i<13; i++) UID[i]='0'; UID[12]=0; // null term just in case UID_Send(UID, 0); // delete all at remotes as well pingTimer = SEC_TIMER; // force a server check UID_GetAddOnly = 1; // only retrieve adds until no more left } int UID_Not_Zero(char *UID) { // checks if UID is all zeros or not // returns 0 if all zeros // returns 1 if not all zeros int i; int result; result=0; for (i=0; i<UIDLen; i++) { if (UID[i] > 0) result=1; } return result; } void UID_Clear(char *UID) { // Sets UID to all zeros memset(UID, 0, UIDLen); } void UID_Copy(char *Udest, char *Usrc) { memcpy(Udest, Usrc, UIDLen); } void Param_Flash_Write(char command) { // command: // 1 = reset/clear timer // 2 = set timer // 3 = check timer and execute flash write static unsigned long PFW_timer; if (command == 1) { // reset/clear timer PFW_timer=0; } else if (command == 2) { // set timer (fixed 15 minutes = 900 sec) PFW_timer=SEC_TIMER + 60; } else if (command == 3) { // check timer and execute flash write if ((PFW_timer > 0) && (PFW_timer <= SEC_TIMER)) // timer is active and triggers { // write local flash and send flash write command to remotes writeParameterSettings(); syncParametersToRemote(); // clear timer PFW_timer=0; } } }<file_sep>/*************************************************************************** Samples\Random.c Z-World, Inc, 2000 This program generates pseudo-random integers between 2000 and 2999 The library rand() function returns a floating-point value (not POSIX). ***************************************************************************/ #class auto #define STDIO_ENABLE_LONG_STRINGS int UID_Encode(char *UID, char *Result); int UID_Decode(char *UID, char *Result); void show_me(char *UID); void main () { int i; char id[14]; char Res[16]; // demo some numbers show_me("154224091045"); show_me("155224091045"); show_me("156224091045"); show_me("157224091045"); show_me("150224091045"); show_me("151000001045"); show_me("150024001005"); show_me("154000000000"); show_me("154999999999"); show_me("154000000000"); show_me("154618822656"); show_me("154618822655"); } void show_me(char *id) { int i; char Res[14]; char Reid[14]; i = UID_Encode(id, Res); printf("%d %s = %02X%02X%02X%02X%02X\n", i, id, Res[0], Res[1], Res[2], Res[3], Res[4]); i = UID_Decode(Res, Reid); printf("%d %02X%02X%02X%02X%02X = %s\n\n", i, Res[0], Res[1], Res[2], Res[3], Res[4], Reid); return; } int UID_Encode(char *UID, char *Result) { // convert 12 byte string into 5 byte decimal // Result must be sized to handle 5 bytes // Return -1 if invalid UID or 0 if success int i; int hval; int carry; unsigned long lval; unsigned long llast; unsigned long incr; char hdig[4]; // high 3 digits char ldig[10]; // low 9 digits // assuming length of 12 // split at 3/9 strncpy(hdig, UID, 3); hdig[3]=0; strcpy(ldig, &UID[3]); lval = atol(ldig); hval = atoi(hdig); incr = 1000000000; llast = lval; carry=0; for (i=0; i<hval; i++) { lval = lval + incr; if (lval<llast) carry++; llast = lval; } Result[0] = (char)carry; Result[1] = (char)((lval >> 24) & 0xFF) ; Result[2] = (char)((lval >> 16) & 0xFF) ; Result[3] = (char)((lval >> 8) & 0XFF); Result[4] = (char)((lval & 0XFF)); //memcpy(&Result[1], &lval, 4); return 0; } int UID_Decode(char *UID, char *Result) { // convert 5 byte UID into 12 byte string // Result must be sized to handle 12+1 bytes // Return -1 if invalid UID or 0 if success int i; unsigned long lval; unsigned long ba; unsigned long bm; unsigned long lo; int hi; int hval; //memcpy(&c, &UID[1], 4); lval = (unsigned long)UID[1] << 24; lval = lval | (unsigned long)UID[2] << 16; lval = lval | (unsigned long)UID[3] << 8; lval = lval | (unsigned long)UID[4]; hval = (int)(UID[0]<<4) + (int)((lval & 0xF0000000)>>28); // how many times to loop lo = lval & 0x0FFFFFFF; // highest byte in hi hi=0; ba = 0x10000000; // add this bm = 1000000000; // mod this for (i=0; i<hval; i++) { lo = lo + ba; // add hi += (int)(lo / bm); // mod lo = lo % bm; // div } // now put into string snprintf(Result, 13, "%d%09lu", hi, lo); Result[12]=0; return 0; }<file_sep>/******************************************************************* MAINSTREAM_DIVERTER_V4xx.C Colombo Semi-Automatic Pneumatic Tube Transfer System Purpose: Remote station control program. Processes local i/o and main_station control commands. Target: Z-World BL2500 Rabbit Language: Dynamic C v9.x Created: Aug 16, 2008 by <NAME> (C) MS Technology Solutions History: 12-Jun-06 v301 Original version created from RMOT235.c 21-Sep-06 v302 skipped version to sync with main 21-Sep-06 v303 Invert logic state of read-bank inputs 24-Sep-06 v304 Further refinement of I/O, add InUse/CIC/Flashing 22-Oct-06 v307 Sync version with Main. Integrate 4 open-door alerts. 04-Jan-07 v311 Sync version with Main. Extend command to 5 data bytes. 08-Jan-07 v312 Do not invert requestToSend inputs 10-Jan-07 v313 Setup for using ALL_DEVICES = 0xFF in .devAddr 14-Jan-07 v314 Integrate turnaround head diverter 19-Jan-07 v316 Diverter map missing [8] and causing out-of-bounds crash 24-Jan-07 v318 Continued improvements 25-Jan-07 v319 Enable TX control a bit sooner to improve communications HD & slave both known at station 8, so ready/not-ready commands now return devAddr 27-Jan-07 v320 fix bug returning response with device address (THIS_LPLC) -> (THIS_LPLC-1) Clean up implentation & reporting of latched arrival interrupt 28-Jan-07 v321 Delay response commands to give main time to be ready 01-Feb-07 v322 Switch from standard blower to heavy duty APU 03-Feb-07 v323 Initialize blower when starting up head diverter 11-Feb-07 v326 Handle failure of readDigBank when rn1100 is failed/missing Fix bug in sending arrival status to main 27-Mar-07 v342 Invert logic state of carrier in chamber and arrival optics 31-Mar-07 v343 Revert to original logic of CIC and arrival optics Set digital inputs low upon loss of connection to RN1100 10-Apr-07 v346 Set diverter addr-2 passthrough to port 4 instead of 1 03-May-07 v347 Delay clearing of arrival latch for 1 second 04-May-07 v348 Fix handling of latched arrival 24-May-07 v349 Fix bug in CIC lights not working, no IO Shift 05-Jun-07 v350 Don't clear latchedCarrierArrival until transaction is complete (remove 1 second clear) 15-Jul-07 v351 Improve exercise_io so that arrival alert and inuse light up Report latched arrival only when state is wait_for_remote_arrive Implement feature for remote alternate address request-to-send, to send to master or slave 23-Jul-07 v352 Implement compile-time selectable blower interface 25-Jul-07 v353 Bug fix for standard blower in head diverter setup (blwrConfig must equal 1) 27-Jul-07 v354 Shore up possible weakness in head diverter optic detection Head diverter arrival optic is on input 0 31-Jul-07 v355 Don't use interrupt for head diverter, raw arrival input only 29-Aug-07 v356 DEVELOPMENT VERSION 29-Dec-07 v365 Released Version - sync w/ main Get blower selection by main menu setting Get diverter port mapping configuration by main menu setting Support for point to point configuration, remote with one station, no diverter, re-mapped I/O 13-Apr-08 v366 Support for reporting blower errors Reduce blower timeout to 12 seconds so it happens before carrier lift timeout 16-Apr-08 v367 Fix mistake in initBlower: blowerPosition==0 --> blowerPosition()==0 Return blowerPosition to the main station for head diverters with APU 16-Aug-08 v400 Created from MAINSTREAM_REMOTE_V367.C 16-Nov-08 v403 Added diverter configuration 8, two position diverter, operates station 2, passes 3-7 06-Dec-08 v404 Added handling of secure transaction 21-Dec-08 v405 Misc improvements to secure handling 03-Mar-09 v409 Bump version to 409 Add communication of secure card parameters 10-Apr-10 v410 Create new diverter configurations Head diverter using 3 ports: 1 for main, 2 for two sub-stations Standard diverter with no ports and two stations used with new head diverter config 18-Apr-10 v411 Fixes to allow for non-tcpip configurations 11-May-10 v412 Fix bug in using uninitialized msg_address in get_command - introduced in remote v3.19, jan 2007 Allow the use of diverter_map 0 when calling set_diverter 26-Mar-11 v413 Pass Head Diverter arrival state always, not just in-process to allow for blocked optic msg When notified of purge mode, flash in-use and cic alternating 02-May-11 v414 Seems that as TRUE == 0x01 instead of 0xFF then passing latchCarrierArrival as TRUE does not satisfy the expected logic at the main system controller (needs to be a specific station) 06-Jun-11 v415 Fixed CIC outputs. Missed the shifting of CIC outputs when it got reworked. ***************************************************************/ #memmap xmem // Required to reduce root memory usage #class auto #define FIRMWARE_VERSION "DIVERTER V4.15" #define VERSION 15 // compile as "STANDARD" or "POINT2POINT" or "DIVERTERONLY" remote // STANDARD are directly connected where DIVERTERONLY are using dedicated remotes (TCPIP) #define RT_STANDARD 1 #define RT_POINT2POINT 2 #define RT_DIVERTERONLY 3 #define REMOTE_TYPE RT_STANDARD //#define REMOTE_TYPE RT_DIVERTERONLY //#define REMOTE_TYPE RT_POINT2POINT //int lastcommand; // for debug //#define USE_TCPIP 1 // define PRINT_ON for additional debug printing via printf // #define PRINT_ON 1 #use "bl25xx.lib" Controller library #use "rn_cfg_bl25.lib" Configuration library #use "rnet.lib" RabbitNet library #use "rnet_driver.lib" RabbitNet library #use "rnet_keyif.lib" RN1600 keypad library #use "rnet_lcdif.lib" RN1600 LCD library #define USE_BLOWER #use "MAINSTREAM.lib" Mainstream v4xx function library // RabbitNet RN1600 Setup //int DevRN1600; // Rabbit Net Device Number Keypad/LCD int DevRN1100; // Rabbit Net Device Number Digital I/O //configure to sinking safe state #define OUTCONFIG 0xFFFF #define SHOW_CYCLE_TIME // Setup interrupt handling for carrier arrival input // Set equal to 1 to use fast interrupt in I&D space #define FAST_INTERRUPT 0 char latchCarrierArrival; void my_isr1(); void arrivalEnable(char how); // Communications data structures #define NUMDATA 5 struct iomessage /* Communications command structure */ { char device; char command; char station; char data[NUMDATA]; }; #define NUMUDPDATA 15 struct UDPmessageType // UDP based messages { char device; char devType; // M for main station char command; // can be heartbeat, event, transaction char station; unsigned long timestamp; char data[NUMUDPDATA]; }; // Define communications using TCP/IP (UDP) #ifdef USE_TCPIP // #define UDP_DEBUG // #define DCRTCP_VERBOSE #define TCPCONFIG 106 // need to use 100+ to use static IP defined here #define MAX_UDP_SOCKET_BUFFERS 1 #define DISABLE_TCP // Not using TCP #define MY_STATIC_IP "192.168.0.10" #define MY_BASE_IP "192.168.0.2%d" char myIPaddress[18]; // string to hold runtime IP address #define MY_IP_NETMASK "255.255.255.0" #define LOCAL_PORT 1234 // for inbound messages // #define REMOTE_IP "255.255.255.255" //255.255.255.255" /*broadcast*/ #define REMOTE_PORT 1235 // for outbound messages #use "dcrtcp.lib" udp_Socket sock; #endif // still define the function prototypes int sendUDPHeartbeat(char sample); int sendUDPcommand(struct UDPmessageType message); int getUDPcommand(struct UDPmessageType *message); void processUDPcommand(struct UDPmessageType message); void processUDPio(void); void monitorUDPactivity(char deviceID); void sendUDPCardParameters(void); // Including parameter block structure // Parameters are NOT read to / written from FLASH struct par_block_type { // These parameters are defined on the fly at run-time char opMode; // STD_REMOTE or HEAD_DIVERTER char subStaAddressing; // to indicate if substation can select slave for destination char blowerType; char portMapping; char cardL3Digits; // Constant left 3 digits of valid secure cards unsigned long cardR9Min; // Secure card ID minimum value for the right 9 digits unsigned long cardR9Max; // Secure card ID maximum value for the right 9 digits } param; #define STD_REMOTE 0 #define HEAD_DIVERTER 1 #define HEAD_DIVERTER2 2 char mainStation; #define SLAVE 0x08 // Station number of the slave #define SLAVE_b 0x80 // Bit representation #define NUM_STATIONS 8 char THIS_DEVICE; // board address for communications and setup char MY_STATIONS; // to mask supported stations char IO_SHIFT; // to map expansion board i/o char diverter_map[9]; // to assign diverter positions to stations char activeStations; // to track who is out there and active // Global variables unsigned long thistime, lasttime, lost; char securePIN_hb, securePIN_lb; struct { unsigned long id; char time; } secureCard[10]; char secureAck; char nextSecureStation(void); //unsigned long secureCardID[10]; /* Declare general function prototypes */ void msDelay(unsigned int msec); //char bit2station(char station_b);// station_b refers to bit equivalent: 0100 //char station2bit(char station); // station refers to decimal value: 3 --^ void init_counter(void); void process_local_io(void); void processCycleTime(void); void set_remote_io(char *remotedata); void init_io(void); void exercise_io(void); void send_response(struct iomessage message); char get_command(struct iomessage *message); void process_command(struct iomessage message); void enable_commands(void); void arrival_alert(char code, char station); char isMyStation(char station); void toggleLED(char LEDDev); void maintenance(void); char Timeout(unsigned long start_time, unsigned long duration); int readParameterSettings(void); int writeParameterSettings(void); /* Declare local and expansion bus input prototypes */ char carrierInChamber(char station_mask); char doorClosed(char station_mask); char carrierArrival(char station_mask); char requestToSend(char station_mask); char requestToSend2(char station_mask); //char diverter_pos(void); // Declare global equivalents for inputs coming from dedicated remotes (UDP) char g_carrierInChamber; char g_doorClosed; char g_carrierArrival; char g_requestToSend; char g_requestToSend2; /* Declare local and expansion bus output prototypes */ char rts_latch; // Used for latching requestToSend char rts2_latch; // Used for latching 2nd requestToSend (to slave) void inUse(char how, char station_b); void alert(char how, char station_b); void alarm(char how); // void diverter(char how); void setDiverter(char station); void processDiverter(void); void setDiverterMap(char portMap); // Declare watchdog and powerlow handlers char watchdogCount(void); char powerlowCount(void); void incrementWDCount(void); void incrementPLCount(void); void loadResetCounters(void); // Digital I/O definitions char outputvalue [6]; // buffer for some outputs char remoteoutput [5]; // buffer for main commanded outputs // INPUTS int readDigInput(char channel); int readDigBank(char bank); // banks 0,1 on Coyote; banks 2,3 on RN1100 // dio_ON|OFF must be used ONLY in primatives readDigInput and setDigOutput // they reflect the real state of the logic inputs and outputs #define dio_ON 0 #define dio_OFF 1 #define di_HDArrival readDigInput(0) // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT #warnt "Compiling as point-to-point configuration" #define di_carrierArrival readDigInput(0) #define di_requestToSend readDigInput(1) #define di_requestToSend2 0 #define di_doorClosed readDigInput(2) #define di_carrierInChamber readDigInput(3) #endif #if REMOTE_TYPE == RT_STANDARD #define di_carrierArrival (((readDigBank(0)) & 0x1E) >> 1) #define di_carrierInChamber (((readDigBank(1)) & 0xF0) >> 4) #define di_requestToSend (readDigBank(2) & 0x0F) #define di_requestToSend2 (readDigBank(3) & 0x0F) #define di_doorClosed ((readDigBank(2) & 0xF0) >> 4) #endif #if REMOTE_TYPE == RT_DIVERTERONLY // define di_carrierArrival only to support definition in my_isr1 #define di_carrierArrival readDigInput(0) #endif #define di_remoteAddress ((readDigBank(0) & 0xE0) >> 5) #define di_diverterPos (readDigBank(1) & 0x0F) #define di_shifterPosIdle readDigInput(12) #define di_shifterPosPrs readDigInput(13) #define di_shifterPosVac readDigInput(14) // OUTPUTS void setDigOutput(int channel, int value); #define do_shift 0 // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT #define do_doorAlert(which,value) setDigOutput(0,value) #define do_arrivalAlert(which,value) setDigOutput(1,value) #define do_CICLight(which,value) setDigOutput(2,value) #define do_inUseLight(which,value) setDigOutput(3,value) // inUseLight on output 3,4,7 causes RS485 transmitter to enable (PA4) // Root cause was use of static CHAR elements in maintenance() instead of static INT #endif #if REMOTE_TYPE == RT_STANDARD #define do_doorAlert(which,value) setDigOutput(0+do_shift+which,value) #define do_arrivalAlert(which,value) setDigOutput(8+do_shift+which,value) #define do_inUseLight(which,value) setDigOutput(12+do_shift+which,value) #define do_inUse2Light(which,value) setDigOutput(20+do_shift+which,value) #define do_CICLight(which,value) setDigOutput(16+do_shift+which,value) #endif #define do_diverter(value) setDigOutput(4+do_shift,value) //#define do_alarm(value) setDigOutput(xx+do_shift,value) #define do_blower(value) setDigOutput(5+do_shift,value) #define do_blowerVac(value) setDigOutput(6+do_shift,value) #define do_blowerPrs(value) setDigOutput(7+do_shift,value) #define ALARM_MASK 0x20 // #define beep(value) rn_keyBuzzerAct(DevRN1600, value, 0) void inUse(char how, char station_b); void inUse2(char how, char station_b); void alarm(char how); /* "how" types & values and other constants */ #define ON 0xFF #define OFF 0x00 #define FLASH 0x01 #define READY 0x01 #define NOT_READY 0xFF //#define TRUE 0xFF //#define FALSE 0x00 #define aaRESET 0x00 #define aaSET 0x01 #define aaTEST 0x02 #define ToREMOTE 0x01 #define ToMAIN 0x02 #define ALL_DEVICES 0xFF /* Serial communications send and receive commands */ #define NAK 0x15 #define ACK 0x06 #define STX 0x02 #define ETX 0x03 #define DINBUFSIZE 63 #define DOUTBUFSIZE 63 #define SET_DIVERTER 'A' #define DIVERTER_STATUS 'B' #define REMOTE_PAYLOAD 'C' #define SECURE_REMOVAL 'C' #define ACK_SECURE_REMOVAL 'D' #define RETURN_INPUTS 'E' #define INPUTS_ARE 'E' #define SET_OUTPUTS 'G' #define CLEAR_OUTPUTS 'H' #define SET_OPMODE 'I' #define ARE_YOU_READY 'J' #define RETURN_EXTENDED 'K' #define SET_TRANS_COUNT 'L' #define SET_DATE_TIME 'M' #define SET_STATION_NAME 'N' #define CANCEL_PENDING 'O' #define TAKE_COMMAND 'P' #define DISPLAY_MESSAGE 'Q' #define SET_PHONE_NUMS 'R' #define SET_PARAMETERS 'S' #define SET_CARD_PARAMS 'T' #define TRANS_COMPLETE 'X' #define RESET 'Y' #define MALFUNCTION 'Z' // Define all system states - MUST BE IDENTICAL TO MAIN #define IDLE_STATE 0x01 #define PREPARE_SEND 0x02 #define WAIT_FOR_DIVERTERS 0x03 #define BEGIN_SEND 0x04 #define WAIT_FOR_MAIN_DEPART 0x05 #define WAIT_FOR_REM_ARRIVE 0x06 #define HOLD_TRANSACTION 0x07 #define WAIT_FOR_REM_DEPART 0x08 #define WAIT_FOR_MAIN_ARRIVE 0x09 #define WAIT_FOR_TURNAROUND 0x0A #define SHIFT_TURNAROUND 0x0B #define CANCEL_STATE 0x0C #define MALFUNCTION_STATE 0x0D #define FINAL_COMMAND 0x0E // Define transaction direction constants #define DIR_SEND 1 #define DIR_RETURN 2 /* Declare miscellaneous timeouts */ #define DIVERTER_TIMEOUT 30000 // How long to set diverter // May be longer than mainsta timeout /******************************************************************/ char arrival_from; // indicates if main is ready for receive or in arrival alert char purge_mode; // indicates if main is in purge mode (flash lights differently) /* Array index values for remote data, returned by INPUTS_ARE command. */ #define REMOTE_CIC 0 #define REMOTE_DOOR 1 #define REMOTE_ARRIVE 2 #define REMOTE_RTS 3 #define REMOTE_RTS2 4 main() { int i; unsigned long timeout; struct iomessage message; unsigned long heartbeat_timer; unsigned long heartbeat_interval; struct UDPmessageType UDPmessage; char key, simonsays; auto rn_search newdev; int status; /* Initialize i/o */ loadResetCounters(); // load counters for watchdog and powerlow resets // Initialize the controller brdInit(); // Initialize the controller rn_init(RN_PORTS, 1); // Initialize controller RN ports // Check if Rabbitnet boards are connected newdev.flags = RN_MATCH_PRDID; newdev.productid = RN1100; if ((DevRN1100 = rn_find(&newdev)) == -1) { printf("\n no RN1100 found\n"); } else status = rn_digOutConfig(DevRN1100, OUTCONFIG); //configure safe state // check if last reset was due to watchdog //if (wderror()) incrementWDCount(); hitwd(); init_io(); arrival_alert(aaRESET, 0); toggleLED(255); // initialize LED outputs readParameterSettings(); /* read board address and set configuration i/o mappings */ THIS_DEVICE = (di_remoteAddress); //if (PRINT_ON) printf("\nThis is remote plc # %d", THIS_DEVICE); // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT THIS_DEVICE = 1; #endif // flash the plc number //flasher(0); for (i=0; i<THIS_DEVICE; i++) { msDelay(200); ledOut(0,1); msDelay(150); ledOut(0,0); hitwd(); } // Set the diverter mapping based on the Remote ID# setDiverterMap(param.portMapping); // setup interrupt handler for arrival optics #if __SEPARATE_INST_DATA__ && FAST_INTERRUPT interrupt_vector ext1_intvec my_isr1; #else SetVectExtern3000(1, my_isr1); // re-setup ISR's to show example of retrieving ISR address using GetVectExtern3000 //SetVectExtern3000(1, GetVectExtern3000(1)); #endif // WrPortI(I1CR, &I1CRShadow, 0x09); // enable external INT1 on PE1, rising edge, priority 1 arrivalEnable(FALSE); // Disable for now #ifdef USE_TCPIP // setup default static IP using THIS_DEVICE (myIPaddress = MY_BASE_IP + THIS_DEVICE) sprintf(myIPaddress, MY_BASE_IP, THIS_DEVICE); printf("My IP address: %s\n", myIPaddress); // configure the interface if(sock_init()) printf("IP sock_init() failed\n"); // Initialize UDP communications ifconfig(IF_ETH0, IFS_DHCP, 1, IFS_IPADDR,aton(myIPaddress), IFS_NETMASK,aton(MY_IP_NETMASK), IFS_DHCP_FALLBACK, 1, IFS_UP, IFS_END); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); //lcd_print(1, 0, "No IP Communications"); msDelay(1000); } #endif // if (PRINT_ON) printf("\nWD and PL Reset Counters %d %d", watchdogCount(), powerlowCount()); exercise_io(); /* Initialize serial port 1 */ enable_commands(); thistime=MS_TIMER; lost=0; heartbeat_interval=500; simonsays=TRUE; while(simonsays) { // loop forever maintenance(); // Hit WD, flash LEDs, write outputs /* check for and process incoming commands */ if (get_command(&message)) process_command(message); if (getUDPcommand(&UDPmessage) > 0) processUDPcommand(UDPmessage); /* check for and process remote stations with dedicated processors*/ //processUDPio(); /* check for and process local inputs */ process_local_io(); arrival_alert(aaTEST, 0); if ((MS_TIMER - heartbeat_timer) > heartbeat_interval) { // Send a UDP heartbeat sendUDPHeartbeat(1); heartbeat_timer=MS_TIMER; monitorUDPactivity(0); // force a refresh of station activity in case all are off } #ifdef SHOW_CYCLE_TIME processCycleTime(); #endif } /* end while */ } /********************************************************/ char transStation, diverterStation, transFlags; char carrier_attn, carrier_attn2; char system_state, systemDirection; //char remote_stat_alert; //unsigned long arrival_time; /********************************************************/ char whichCA; nodebug root interrupt void my_isr1() { latchCarrierArrival=activeStations; // can't tell which station so send via all whichCA=di_carrierArrival; //carrierArrival(255); WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 } void arrivalEnable(char how) { // should call this routine once to enable interrupt and once to disable #GLOBAL_INIT { latchCarrierArrival=FALSE; } latchCarrierArrival=FALSE; // clear existing latch if (how) { //outport(ITC,(inport(ITC))|0x02); // enable INT1 //WrPortI(I1CR, &I1CRShadow, 0x09); // enable external INT1 on PE1, rising edge, priority 1 WrPortI(I1CR, &I1CRShadow, 0x0A); // enable external INT1 on PE1, rising and falling edge, priority 2 } else { //outport(ITC,(inport(ITC))&~0x02); // disable INT1 WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 } } void setDiverterMap(char portMap) { // Sets up the diverter port mapping based on the supplied parameter // Also sets the parameter opMode to standard or head-diverter // Entry in diverter_map is the binary diverter port number (1,2,4,8) param.opMode = STD_REMOTE; switch (portMap) { case 0: break; case 1: MY_STATIONS = 0x0F; // mask for stations used by this device IO_SHIFT = 0; // 4 for stations 5-7, 0 for stations 1-3 diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 8; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT MY_STATIONS = 0x01; // mask for stations used by this device diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; #endif break; case 2: MY_STATIONS = 0x70; // mask for stations used by this device IO_SHIFT = 4; // 4 for stations 5-7, 0 for stations 1-3 diverter_map[0] = 0; diverter_map[1] = 8; diverter_map[2] = 8; diverter_map[3] = 8; diverter_map[4] = 8; diverter_map[5] = 1; diverter_map[6] = 2; diverter_map[7] = 4; diverter_map[8] = 0; // for main to main break; case 3: MY_STATIONS = 0x03; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 4; diverter_map[5] = 8; diverter_map[6] = 8; diverter_map[7] = 8; diverter_map[8] = 0; // for main to main break; case 4: MY_STATIONS = 0x0C; // mask for stations used by this device IO_SHIFT = 2; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 1; diverter_map[4] = 2; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main break; case 5: MY_STATIONS = 0x70; // mask for stations used by this device IO_SHIFT = 4; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 1; diverter_map[6] = 2; diverter_map[7] = 4; diverter_map[8] = 0; // for main to main break; case 6: MY_STATIONS = 0x01; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 2; diverter_map[4] = 2; diverter_map[5] = 2; diverter_map[6] = 2; diverter_map[7] = 2; diverter_map[8] = 0; // for main to main break; case 7: // HEAD DIVERTER USE ONLY param.opMode = HEAD_DIVERTER; MY_STATIONS = 0x80; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main initBlower(); // only head diverter uses a blower break; case 8: // Operate station 2, ignore station 1, pass through stations 3-7 MY_STATIONS = 0x02; // mask for stations used by this device IO_SHIFT = 1; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 1; diverter_map[3] = 2; diverter_map[4] = 2; diverter_map[5] = 2; diverter_map[6] = 2; diverter_map[7] = 2; diverter_map[8] = 0; // for main to main break; case 9: // HEAD DIVERTER USE ONLY - ALTERNATE CONFIGURATION param.opMode = HEAD_DIVERTER2; MY_STATIONS = 0x80; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 1; diverter_map[1] = 2; diverter_map[2] = 4; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main initBlower(); // only head diverter uses a blower break; case 10: // for use with head diverter configuration #9 // controls station 1 & 2 but no actual diverter MY_STATIONS = 0x03; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main break; default: // any other undefined selection MY_STATIONS = 0x00; // mask for stations used by this device IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main break; } #ifndef USE_TCPIP activeStations = MY_STATIONS; #endif } #ifdef SHOW_CYCLE_TIME void processCycleTime() { // calculate and display cycle time statistics #define CYCLETIME_UPDATE 2000 static int ct_min, ct_avg, ct_max; static int ct_loops; static unsigned long cycle_start; static unsigned long ct_last; unsigned long cycle_time; if (MS_TIMER - cycle_start >= CYCLETIME_UPDATE) { if (ct_loops > 0) ct_avg = (int)((MS_TIMER - cycle_start) / ct_loops); printf("\n n=%d min=%d avg=%d max=%d", ct_loops, ct_min, ct_avg, ct_max); ct_max=0; ct_min=32767; ct_loops=0; cycle_start=MS_TIMER; } else { cycle_time = MS_TIMER - ct_last; ct_loops = ct_loops + 1; if (cycle_time > ct_max) ct_max = (int)cycle_time; if (cycle_time < ct_min) ct_min = (int)cycle_time; } ct_last = MS_TIMER; } #endif void init_io() { char i; for (i=0; i<4; i++) // four or five output ports { outputvalue[i] = 0; remoteoutput[i] = 0; } blower(blwrOFF); alarm(OFF); secureAck=0; for (i=0; i<10; i++) secureCard[i].id=0; purge_mode=0; } void exercise_io() { // if (!wderror()) // { alert(ON, MY_STATIONS); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); maintenance(); msDelay(1000); maintenance(); msDelay(1000); //inUse(ON, MY_STATIONS); maintenance(); msDelay(200); inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); msDelay(200); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); alert(ON, MY_STATIONS); maintenance(); msDelay(200); // } inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); hitwd(); // hit the watchdog } /********************************************************/ void process_local_io() { char rts_data, rts2_data, cic_data; /* bitwise station bytes */ char door_closed; char on_bits, flash_bits; /* which ones on and flash */ char on_bits2, flash_bits2; /* which ones on and flash for 2nd in-use light */ char s, sb; /* work vars for station & stationbit */ char i; //static unsigned long LA_Timer; // to latch the arrival signal #GLOBAL_INIT { rts_latch=0; rts2_latch=0; transStation=0; diverterStation=0; carrier_attn=0; carrier_attn2=0; //arrival_time=0; arrival_from=0; //LA_Timer=0; mainStation=0; param.subStaAddressing=FALSE; g_carrierInChamber=0; g_doorClosed=0; g_carrierArrival=0; g_requestToSend=0; g_requestToSend2=0; } /* Check for diverter and blower attention */ processDiverter(); processBlower(); /* Use local buffers for some inputs */ if (param.opMode == STD_REMOTE) { // stuff for standard remote inputs rts_data=requestToSend(MY_STATIONS); rts2_data=requestToSend2(MY_STATIONS); cic_data=carrierInChamber(MY_STATIONS); door_closed=doorClosed(MY_STATIONS); // handle carrier in chamber light // Need to shift CIC input back to (1..4) range for correct output // don't latch inputs if in purge mode if (purge_mode==0) { /* Latch request_to_send for new requests */ rts_latch |= (rts_data & cic_data & door_closed) & ~carrier_attn & ~rts2_data; // de-latch when rts2 pressed rts2_latch |= (rts2_data & cic_data & door_closed) & ~carrier_attn2 & ~rts_data; // de-latch when rts pressed } /* Don't latch requests from station in current transaction */ rts_latch &= ~station2bit(transStation); rts2_latch &= ~station2bit(transStation); /* Turn off those who have lost their carrier or opened door */ rts_latch &= cic_data; rts2_latch &= cic_data; rts_latch &= door_closed; rts2_latch &= door_closed; // Setup in-use lights for primary and optional secondary in-use lights on_bits = station2bit(transStation); flash_bits = rts_latch | rts_data; flash_bits |= ~door_closed; // flash open doors flash_bits |= carrier_attn; // flash stations needing attention (unremoved delivery) on_bits2 = station2bit(transStation); flash_bits2 = rts2_latch | rts2_data; flash_bits2 |= ~door_closed; // flash open doors flash_bits2 |= carrier_attn2; // flash stations needing attention (unremoved delivery) if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) flash_bits2 |= station2bit(diverterStation); else flash_bits |= station2bit(diverterStation); // NEED TO LOOK INTO HOW ARRIVAL_FROM WORKS // if main arrival active, flash inuse at who sent to main if (arrival_from) { on_bits &= ~arrival_from; // Not on solid flash_bits |= arrival_from; // On flash instead } // set the in use lights as necessary inUse(OFF, ~on_bits & ~flash_bits & MY_STATIONS & ~station2bit(transStation)); inUse(ON, on_bits); inUse(FLASH, flash_bits & ~station2bit(transStation)); inUse2(OFF, ~on_bits2 & ~flash_bits2 & MY_STATIONS & ~station2bit(transStation)); inUse2(ON, on_bits2); inUse2(FLASH, flash_bits2 & ~station2bit(transStation)); // latch the arrival signal i = carrierArrival(MY_STATIONS); if (i) latchCarrierArrival=i; // latch this value } else { // stuff for head diverter //i = di_HDArrival; // && (system_state==WAIT_FOR_TURNAROUND) if (di_HDArrival && (system_state==WAIT_FOR_TURNAROUND)) latchCarrierArrival=TRUE; // latch this value rts_data=0; // No push to send buttons cic_data=0; // No carrier in chamber optics door_closed=0; // No door switches } } /********************************************************/ void process_command(struct iomessage message) { char wcmd, wdata; char ok; char i; char station; char * sid; //static char system_state, new_state; static char new_state; struct iomessage response; struct UDPmessageType UDPmessage; static unsigned long lastSecureRemoveMsg; #GLOBAL_INIT { system_state=IDLE_STATE; new_state=system_state; lastSecureRemoveMsg=0; } response.command=0; response.station=message.station; // set initial default /* determine what type of command */ switch(message.command) { case ARE_YOU_READY: // debug to see what may be causing loss of communication //lastcommand=message.command; // enable arrival interrupt / latch if (param.opMode == STD_REMOTE) arrivalEnable(TRUE); // don't enable interrupt for head diverter response.command=ARE_YOU_READY; // assume ready for now response.data[0]=1<<(THIS_DEVICE-1); transStation=message.station; systemDirection=message.data[0]; mainStation=message.data[1]; // get the main station to be used //transFlags=message.data[3]; // transaction flags such as STAT & Secure // Negate assumption if not ready if (isMyStation(message.station) && (param.opMode == STD_REMOTE)) { // stuff for standard remote rts_latch &= ~station2bit(message.station); // clear latch rts2_latch &= ~station2bit(message.station); // clear latch /* only if door closed, and (CIC or send-to-here) */ if ( doorClosed(station2bit(message.station)) && ( carrierInChamber(station2bit(message.station)) || message.data[0]==DIR_SEND) ) { // ready if (param.subStaAddressing && mainStation==SLAVE) { inUse2(ON, station2bit(message.station)); }else { inUse(ON, station2bit(message.station)); } } else { response.data[0]=0; // not ready if (param.subStaAddressing && mainStation==SLAVE) inUse2(OFF, station2bit(message.station)); else inUse(OFF, station2bit(message.station)); alert(ON, station2bit(message.station)); } } break; case SET_DIVERTER: // debug to see what may be causing loss of communication //lastcommand=message.command; switch (param.opMode) { case STD_REMOTE: // stuff for standard remote if (param.subStaAddressing && message.data[1]==SLAVE) inUse2(FLASH, station2bit(message.station)); else inUse(FLASH, station2bit(message.station)); setDiverter(message.station); break; case HEAD_DIVERTER: // stuff for standard head diverter setDiverter(message.data[0]); // head diverter comes in different byte break; case HEAD_DIVERTER2: // alternate head diverter // main on port 1, station 1 on port 2, station 2 on port 3 if (message.data[0]==1) // align to main on port 1 setDiverter(0); // align main else setDiverter(message.station); // align to station break; } mainStation=message.data[1]; // get the main station to be used param.subStaAddressing=message.data[2]; param.blowerType = message.data[3]; transFlags = message.data[4]; // transaction flags such as STAT & Secure break; case DIVERTER_STATUS: /* return logic of correct position */ // debug to see what may be causing loss of communication //lastcommand=message.command; // capture the securePIN securePIN_hb = message.data[2]; securePIN_lb = message.data[3]; // return response response.command=DIVERTER_STATUS; // which port dependent on opMode switch (param.opMode) { case STD_REMOTE: i = message.station; break; case HEAD_DIVERTER: i = message.data[0]; // main, remote, or slave break; case HEAD_DIVERTER2: if (message.data[0]==1) i=0; // main else i = message.station; // sub station for alternate config break; } // is that port aligned? or not used? if ( (di_diverterPos == diverter_map[i]) || (diverter_map[i] == 0) ) { response.data[0]=1<<(THIS_DEVICE-1); // DIVERTER_READY; } else { response.data[0]=0; // DIVERTER_NOT_READY; } break; case RETURN_INPUTS: /* return general status */ // debug to see what may be causing loss of communication //lastcommand=message.command; // main includes some status info here ... pull it out arrival_from=message.data[0]; new_state=message.data[1]; // NOT USING IT: system_direction=message.data[2]; // tell main how I am doing response.command=INPUTS_ARE; response.station=activeStations; // MY_STATIONS; // return this to enlighten main // fill in the rest of the response based on who I am if (param.opMode == STD_REMOTE) { // stuff for standard remote // are there any Secure Card ID's to pass along? station = nextSecureStation(); if (station && ((MS_TIMER - lastSecureRemoveMsg)>500)) { // instead of INPUTS_ARE need to send SECURE_REMOVAL lastSecureRemoveMsg = MS_TIMER; response.command=SECURE_REMOVAL; response.station=station; sid = (char *)&secureCard[station].id; response.data[0] = *sid++; // secureCardID byte 3 response.data[1] = *sid++; // secureCardID byte 2 response.data[2] = *sid++; // secureCardID byte 1 response.data[3] = *sid++; // secureCardID byte 0 response.data[4] = secureCard[station].time; } else { // Return latched carrier arrival if state is wait_for_remote_arrival //if (latchCarrierArrival && system_state==WAIT_FOR_REM_ARRIVE) ok=TRUE; //else ok=FALSE; // Return the arrival signal directly response.data[REMOTE_ARRIVE]=carrierArrival(MY_STATIONS); // but if it is none then send latched arrival under some conditions if ((response.data[REMOTE_ARRIVE]==0) && (latchCarrierArrival) && (system_state==WAIT_FOR_REM_ARRIVE)) response.data[REMOTE_ARRIVE]=latchCarrierArrival; response.data[REMOTE_CIC]=carrierInChamber(MY_STATIONS); response.data[REMOTE_DOOR]=doorClosed(MY_STATIONS); response.data[REMOTE_RTS]=rts_latch; response.data[REMOTE_RTS2]=rts2_latch; } } else { // stuff for head diverter // Return latched carrier arrival if state is wait_for_turnaround if ((latchCarrierArrival || di_HDArrival) && (system_state==WAIT_FOR_TURNAROUND)) ok=TRUE; else ok=FALSE; // Return the arrival signal, latched in process or steady state if (ok || di_HDArrival) response.data[REMOTE_ARRIVE]=MY_STATIONS; else response.data[REMOTE_ARRIVE]=0; response.data[REMOTE_CIC]=0; response.data[REMOTE_DOOR]=0; // HD has no stations MY_STATIONS; response.data[REMOTE_RTS]=0; if (blwrError==FALSE) response.data[REMOTE_RTS2]=blowerPosition(); else response.data[REMOTE_RTS2]=0xFF; // Blower has an error } break; case ACK_SECURE_REMOVAL: // Acknowledge of secure card id from station n // secureAckStation = message.station // message.data[0] contains bit-wise stations to acknowledge for (station=1; station<=NUM_STATIONS; station++) if (message.data[0] & (station2bit(station))) secureCard[station].id=0; break; case RETURN_EXTENDED: /* return extended data */ // debug to see what may be causing loss of communication //lastcommand=message.command; // return watchdog and powerlow counters response.command=RETURN_EXTENDED; response.data[0]=0;//watchdogCount(); response.data[1]=0;//powerlowCount(); response.data[2]=VERSION; break; case SET_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote /* set outputs from mainsta */ set_remote_io(&message.data[0]); } break; case CLEAR_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_OPMODE: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_PARAMETERS: // get the blower type and other parameters // debug to see what may be causing loss of communication //lastcommand=message.command; param.portMapping = message.data[0]; param.blowerType = message.data[1]; writeParameterSettings(); setDiverterMap(param.portMapping); break; case SET_CARD_PARAMS: // Setup the secure card parameters if (message.data[0]==0) { param.cardL3Digits = message.data[1]; } else if (message.data[0]==1) { param.cardR9Min = *(unsigned long *)&message.data[1]; } else if (message.data[0]==2) { param.cardR9Max = *(unsigned long *)&message.data[1]; // last one so save and send the data to remotes // writeParameterSettings(); SAVE WILL FOLLOW IMMEDIATELY FROM SET_PARAMETERS sendUDPCardParameters(); } break; case TRANS_COMPLETE: // debug to see what may be causing loss of communication //lastcommand=message.command; arrivalEnable(FALSE); // Disable arrival interrupt transStation=0; if (param.opMode == STD_REMOTE) { // stuff for standard remote alert(OFF, station2bit(message.station)); // set arrival alert if the transaction is to here if (message.data[0] == DIR_SEND && isMyStation(message.station)) { if (message.data[1]==1) // and Main says to set arrival alert { // OK to set alert // REDUNDANT inUse(FLASH, station2bit(message.station)); // until no cic if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) carrier_attn2 |= station2bit(message.station); // to flash inuse else carrier_attn |= station2bit(message.station); // to flash inuse arrival_alert(aaSET, message.station); } } else if (message.data[0] == DIR_RETURN && isMyStation(message.station)) { // capture the main arrival flag } } // nothing else for head diverter // pass this along to the remote stations UDPmessage.command = TRANS_COMPLETE; UDPmessage.station = message.station; UDPmessage.data[0] = message.data[0]; UDPmessage.data[1] = message.data[1]; UDPmessage.data[2] = message.data[2]; sendUDPcommand(UDPmessage); // ignore return value, will send again periodically break; case MALFUNCTION: // may be contributing to funky flashing // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // turn on alarm output only inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(ON); arrival_alert(aaRESET, 0); } arrivalEnable(FALSE); // Disable arrival interrupt rts_latch=0; rts2_latch=0; transStation=0; diverterStation=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; case RESET: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // Turn off all outputs inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(OFF); arrival_alert(aaRESET, 0); } blwrError=FALSE; // reset blower error arrivalEnable(FALSE); // Disable arrival interrupt /// rts_latch=0; Try to not clear latch on reset transStation=0; diverterStation=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; } /* send the response message if any AND the query was only to me */ if (response.command && (message.device==THIS_DEVICE)) { msDelay(2); // hold off response just a bit //response.lplc=THIS_DEVICE; send_response(response); } // process state change if (new_state != system_state) { // set blower for new state system_state=new_state; blower(blowerStateTable[system_state][blwrConfig]); } return; } void processUDPcommand(struct UDPmessageType UDPmessage) { #ifdef USE_TCPIP // Handle any incoming UDP packets for me int b_station; static unsigned long print_timer; unsigned long secureID; static int msg_count; #GLOBAL_INIT { msg_count=0; } // track and print UDP stats msg_count++; if (MS_TIMER - print_timer > 1000) { print_timer=MS_TIMER; printf("\n Got %d messages", msg_count); msg_count=0; //printf("\n Got UDP message %c at %ld", UDPmessage.command, UDPmessage.timestamp); } /* determine what type of command */ switch(UDPmessage.command) { case INPUTS_ARE: // place returned values into local variables // Note: need to shift input bit positions according to station number b_station = station2bit(UDPmessage.station); if (UDPmessage.data[0]) g_carrierInChamber |= b_station; // bit on else g_carrierInChamber &= ~b_station; // bit off if (UDPmessage.data[1]) g_doorClosed |= b_station; // bit on else g_doorClosed &= ~b_station; // bit off if (UDPmessage.data[2]) g_carrierArrival |= b_station; // bit on else g_carrierArrival &= ~b_station; // bit off if (UDPmessage.data[3]) g_requestToSend |= b_station; // bit on else g_requestToSend &= ~b_station; // bit off if (UDPmessage.data[4]) g_requestToSend2 |= b_station; // bit on else g_requestToSend2 &= ~b_station; // bit off // save version number // Secure Card ID starts at .data[9] secureID = *(unsigned long *)&UDPmessage.data[9]; if (secureID) { // non-zero ID to be cached secureCard[UDPmessage.station].id = secureID; secureCard[UDPmessage.station].time = UDPmessage.data[13]; // tell remote we got the card ID secureAck = UDPmessage.station; // if (secureCard[UDPmessage.station].id) // secureAck = UDPmessage.station; // else // secureAck = 0; } break; } // track the active stations to report when a station stops communicating monitorUDPactivity(UDPmessage.device); // do we need to send any UDP packets? // handle them #endif } void monitorUDPactivity(char deviceID) { // track the active stations to report when a station stops communicating // call with deviceID = 0 to refresh statistics #ifdef USE_TCPIP static int recentDevices[NUM_STATIONS+1]; static unsigned long refreshTimer; static int idx; #GLOBAL_INIT { for (idx=0; idx<=NUM_STATIONS; idx++) recentDevices[idx]=0; refreshTimer=0; activeStations=0; } // make sure this device is within range if (deviceID < 10) { // capture this device recentDevices[deviceID]++; } // update and report new statistic every 1 secon if (MS_TIMER - refreshTimer >1000) { // report the new statistic refreshTimer = MS_TIMER; activeStations = 0; for (idx=NUM_STATIONS; idx>0; idx--) // count down { activeStations = (activeStations << 1); // shift activeStations |= (recentDevices[idx]>0) ? 1 : 0; // include bit // clear the history buffer recentDevices[idx]=0; } } #endif } char nextSecureStation(void) { // if a secureCardID is in the buffer return the station number char i; for (i=1; i<9; i++) if (secureCard[i].id) return i; return 0; } unsigned long alert_timer[8]; // for stations 1..7 ... [0] is not used. void arrival_alert(char func, char station) { int i; switch (func) { case aaRESET: for (i=1; i<=7; i++) { alert_timer[i]=0; alert(OFF, station2bit(i)); } break; case aaSET: if (station>=1 && station<=7) // make sure s# is correct { alert_timer[ station ] = SEC_TIMER; } break; case aaTEST: for (i=1; i<=7; i++) // Check each station { if (alert_timer[i]) { if ( carrierInChamber( station2bit(i) )) // || (remote_stat_alert==i) ) { // Flash as necessary if ( (SEC_TIMER - alert_timer[i]) %20 >= 10 ) alert(ON, station2bit(i)); else alert(OFF, station2bit(i)); } //else if (clock() = alert_timer[i] > 1) else if (!doorClosed( station2bit(i) ) || i==transStation) { // no carrier, door open // or no carrier, in transit --> reset alert_timer[i]=0; alert(OFF, station2bit(i)); carrier_attn &= ~station2bit(i); // clear attn flag carrier_attn2 &= ~station2bit(i); // clear attn flag } } else { carrier_attn &= ~station2bit(i); // no timer, so no flag carrier_attn2 &= ~station2bit(i); // no timer, so no flag } } break; } } /************************************************************/ /************** DIGITAL I/O *************************/ /************************************************************/ #define devIUS 0 #define devIUF 1 #define devAlert 2 #define devAlarm 3 #define dev2IUS 4 #define dev2IUF 5 // #define devDoorAlert 4 int readDigInput(char channel) { // returns the state of digital input 0-39 // function supports inverted logic by assigning dio_ON and dio_OFF char rtnval; if (channel < 16) { // on-board inputs rtnval = digIn(channel); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digIn(DevRN1100, channel-16, &rtnval, 0) == -1) rtnval=1; } // 1 is off else rtnval = 0; } // deal with logic inversion if (rtnval) rtnval = dio_ON; else rtnval = dio_OFF; return rtnval; } int readDigBank(char bank) { // returns the state of digital input banks 0-3 // banks 0-1 on Coyote; banks 2-3 on RN1100 // function supports inverted logic by assigning dio_ON and dio_OFF static char rtnval[4]; // to cache previous inputs char returnVal; char temp; #GLOBAL_INIT { rtnval[0]=0; rtnval[1]=0; rtnval[2]=0; rtnval[3]=0; } if (bank < 2) { // on-board inputs rtnval[bank] = digBankIn(bank); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digBankIn(DevRN1100, bank-1, &temp, 0) == -1) rtnval[bank]=0xFF; // 1 is off else rtnval[bank]=temp; } } returnVal = rtnval[bank]; // deal with logic inversion if (dio_OFF) returnVal ^= 0xFF; return returnVal; } void setDigOutput(int channel, int value) { // sets the state of digital output 0-23 // call with logic value (0=OFF, 1=ON) // function is adapted to support inverted logic by assigning dio_ON and dio_OFF int outval; // check for logic inversion if (value) outval = dio_ON; else outval = dio_OFF; if (channel < 8) { // on-board outputs digOut(channel, outval); } else { // rn1100 outputs if (DevRN1100 != -1) rn_digOut(DevRN1100, channel-8, outval, 0); } } /*************************************************************/ void set_remote_io(char *remotedata) { /* save state of remote output request */ remoteoutput[0]=remotedata[0]; remoteoutput[1]=remotedata[1]; // remoteoutput[2]=remotedata[2]; // THIS IS devAlert - DON'T TAKE FROM MAIN remoteoutput[2]=remotedata[2]; // Instead use remotedata[2] to drive the door alert // remoteoutput[3]=remotedata[3]; purge_mode=remotedata[3]; /* write out all outputs .. some may need to be shifted */ // write4data(addrIUS, outputvalue[devIUS] | remoteoutput[devIUS]); // write4data(addrIUF, outputvalue[devIUF] | remoteoutput[devIUF]); // outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); // write4data(addrALT, outval); // write4data(addrALM, outputvalue[devAlarm] | remoteoutput[devAlarm]); // Write remotedata[devAlert] to output ports O5-O8 // hv_outval &= ~DOOR_ALERT_MASK; // turn off door alert bits // hv_outval = (remotedata[devAlert] & MY_STATIONS) >> IO_SHIFT; // hv_wr(hv_outval); } /******************************************************************/ char carrierInChamber(char stamask) { #if REMOTE_TYPE == RT_DIVERTERONLY return (g_carrierInChamber) & stamask; #else return (di_carrierInChamber << IO_SHIFT) & stamask; #endif } /******************************************************************/ char doorClosed(char stamask) { // Note: input is normally high on closed. char indata; #if REMOTE_TYPE == RT_DIVERTERONLY return (g_doorClosed & stamask); #else indata = di_doorClosed; return ((indata << IO_SHIFT) & stamask); #endif } /******************************************************************/ char carrierArrival(char stamask) { #if REMOTE_TYPE == RT_DIVERTERONLY return g_carrierArrival & stamask; #else return (di_carrierArrival << IO_SHIFT) & stamask; #endif } /******************************************************************/ char requestToSend(char stamask) { char indata; #if REMOTE_TYPE == RT_DIVERTERONLY return (g_requestToSend & stamask); #else indata = di_requestToSend; return ((indata << IO_SHIFT) & stamask); #endif } char requestToSend2(char stamask) { char indata; #if REMOTE_TYPE == RT_DIVERTERONLY return (g_requestToSend2 & stamask); #else indata = di_requestToSend2; return ((indata << IO_SHIFT) & stamask); #endif } /******************************************************************/ void inUse(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[devIUS] |= station_b; outputvalue[devIUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] |= station_b; } return; } void inUse2(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[dev2IUS] |= station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] |= station_b; } return; } /******************************************************************/ void alert(char how, char station_b) { if (how == ON) outputvalue[devAlert] |= station_b; if (how == OFF) outputvalue[devAlert] &= ~station_b; //outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); //write4data(addrALT, outval); //do_alert(outval, how); // OUTPUTS WRITTEN IN SYSTEM LOOP CALL TO updateOutputs(); return; } /******************************************************************/ void alarm(char how) { // outputvalue is checked in the inUse function to turn alarm on/off outputvalue[devAlarm] = how; return; } /******************************************************************/ unsigned long diverter_start_time; // these used primarily by diverter functions char diverter_setting; char diverter_attention; void setDiverter(char station) { /* Controls the setting of diverter positions Return from this routine is immediate. If diverter is not in position, it is turned on and a timer started. You MUST repeatedly call processDiverter() to complete processing of the diverter control position */ /* use mapping from station to diverter position */ if ((station>=0) && (station<9)) // Valid station # { diverter_setting = diverter_map[station]; // mapped setting // if position<>ANY (any=0) and not in position if ((diverter_setting>0) && (diverter_setting!=di_diverterPos)) { /* turn on diverter and start timer */ do_diverter(ON); diverter_start_time = MS_TIMER; diverter_attention = TRUE; diverterStation=station; } } return; } /******************************************************************/ void processDiverter() { /* Poll type processing of diverter control system */ /* Allows other processes to be acknowleged when setting diverter */ if (diverter_attention) { if ((diverter_setting == di_diverterPos) || Timeout(diverter_start_time, DIVERTER_TIMEOUT)) { // turn off diverter and clear status do_diverter(OFF); diverter_attention = FALSE; diverterStation=0; } } } void showactivity() { // update active processor signal ledOut(0, (MS_TIMER %250) < 125); // on fixed frequency //ledOut(1, (MS_TIMER %500) > 250); // off fixed frequency toggleLED(2); // toggle each call } void toggleLED(char LEDDev) { static char LEDState[4]; // if LEDDev not 0..3 then initialize LED states off if (LEDDev > 3) { LEDState[0]=0; LEDState[1]=0; LEDState[2]=0; LEDState[3]=0; } else { LEDState[LEDDev] ^= 1; // toggle LED state on/off ledOut(LEDDev, LEDState[LEDDev]); // send LED state } } void maintenance(void) { // handle all regularly scheduled calls // use of static CHAR was causing PA4 RS485 transmitter to enable without reason ... static INT works ok. static int out_alert, out_inuse, out_inuse2, out_doorAlert; char i, cic_data, pflash; hitwd(); // hit the watchdog timer showactivity(); //rn_keyProcess(DevRN1600, 0); // process keypad device // process command communications #ifdef USE_TCPIP tcp_tick(NULL); #endif //receive_command(); // process flashing inUse lights // out_alert = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); out_alert = ((outputvalue[devAlert]) >> IO_SHIFT); out_doorAlert = (remoteoutput[devAlert] >> IO_SHIFT); // flash on if ((MS_TIMER %500) < 300) { out_inuse = (outputvalue[devIUF] | outputvalue[devIUS]) >> IO_SHIFT; out_inuse2 = (outputvalue[dev2IUF] | outputvalue[dev2IUS]) >> IO_SHIFT; } // or flash off else { out_inuse = outputvalue[devIUS] >> IO_SHIFT; out_inuse2 = outputvalue[dev2IUS] >> IO_SHIFT; } // get carrier in chamber data cic_data=carrierInChamber(MY_STATIONS) >> IO_SHIFT; // if purge mode handle lights different if (purge_mode==1) { if ((MS_TIMER%300) < 150) { out_inuse=0; out_inuse2=0; cic_data=MY_STATIONS >> IO_SHIFT; } else { out_inuse=MY_STATIONS >> IO_SHIFT; out_inuse2=MY_STATIONS >> IO_SHIFT; cic_data=0; } } // Write out alerts and inUse light and CIC // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT do_arrivalAlert(0, out_alert & 1); do_doorAlert(0, out_doorAlert & 1); do_inUseLight(0, out_inuse & 1); do_CICLight(0, cic_data & 1); #endif #if REMOTE_TYPE == RT_STANDARD for (i=0; i<4; i++) { do_arrivalAlert(i, out_alert & (1<<i)); do_doorAlert(i, out_doorAlert & (1<<i)); do_inUseLight(i, out_inuse & (1<<i)); do_inUse2Light(i, out_inuse2 & (1<<i)); do_CICLight(i, cic_data & (1<<i)); } #endif // Process alarm output //do_alarm(outputvalue[devAlarm]); } /******************************************************************/ // Blower Processing Routines - supports both standard and APU blowers /******************************************************************/ // Interface definition // char blwrConfig; // to become a parameter from eeprom // blwrConfig 0 = Standard blower // blwrConfig 1 = High capacity APU blower // #define blwrOFF 0 // #define blwrIDLE 1 // #define blwrVAC 2 // #define blwrPRS 3 // void initBlower(void); // void blower(char blowerOperatingValue); // use blwrOFF, blwrIDLE, blwrVAC, blwrPRS // char processBlower(void); // char blowerPosition(void); /* char blower_mode, blower_limbo, last_shifter_pos, lastDir; unsigned long blower_timer; void initBlower() { // trys to find any shifter position, then goes to idle unsigned long mytimer; blwrConfig = 1; // Turnaround configuration // Clear global blower variables last_shifter_pos=0; lastDir=0; blower_limbo=FALSE; blwrError=FALSE; // turn off all outputs do_blower(OFF); do_blowerVac(OFF); do_blowerPrs(OFF); // remainder of initialization is for APU blowers only if (param.blowerType == blwrType_APU) { // if not in any position, try to find any position if (blowerPosition() == 0) { // hunt for any position do_blowerPrs(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); if (blowerPosition()==0) { // still not found...so go the other way do_blowerPrs(OFF); do_blowerVac(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); do_blowerVac(OFF); if (blowerPosition()==0) blwrError = TRUE; // capture unknown position error } } // after all that, now command to goto idle blower(blwrIDLE); } } void blower(char request) { // operates both standard blowers and APU blowers // sets the direction of the blower shifter // use blwrVAC, blwrPRS, blwrIDLE, or OFF char hv_save; char how; static char lastHow; #GLOBAL_INIT { blwrConfig = 1; // Turnaround configuration lastHow = 0; } // Handling of standard blower type if (param.blowerType == blwrType_STD) { // No such state as idle in standard blowers so map to OFF if (request==blwrIDLE) request=blwrOFF; how = request; // make sure correct parameter is used. anything but VAC and PRS is OFF if ((how != blwrVAC) && (how != blwrPRS)) how = blwrOFF; // if going from one on-state to the other on-state then turn off first if ((how != blwrOFF) && (lastHow != blwrOFF) && (how != lastHow)) { // can't run in both directions at the same time do_blowerPrs(OFF); do_blowerVac(OFF); msDelay(100); // wait a little while } // turn on appropriate bit if (how == blwrPRS) do_blowerPrs(ON); else if (how == blwrVAC) do_blowerVac(ON); else { do_blowerPrs(OFF); do_blowerVac(OFF); } // Add alternate blower on/off control per Joe request on 10-Jul-07 if (how != blwrOFF) do_blower(ON); else do_blower(OFF); // remember last setting lastHow = how; } // end of standard blower // Handling of APU blower type else if ((param.blowerType == blwrType_APU) && (request != lastHow)) { // store in local work space blower_mode=request; blower_limbo=FALSE; lastHow=request; // clear previous state // hv_save=output_buffer; // turn off shifters do_blowerPrs(OFF); do_blowerVac(OFF); // CW for Pressure to Idle or Any to Vacuum // CCW for Vacuum to Idle or Any to Pressure if (blower_mode == blwrVAC) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blower_mode == blwrPRS) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blower_mode == blwrIDLE) { if (blowerPosition() == blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blowerPosition() == blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blowerPosition() == 0) { // go to idle but don't know which way if (lastDir==blwrVAC) { do_blowerVac(ON); blower_limbo=TRUE; lastDir=blwrVAC; } else if (lastDir==blwrPRS) { do_blowerPrs(ON); blower_limbo=TRUE; lastDir=blwrPRS; } else { // use last position to know which way to go blower_limbo = TRUE; // incomplete operation if (last_shifter_pos==blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (last_shifter_pos==blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else blower_limbo=FALSE; // idle to idle is ok to leave alone } } // else go-idle and already in idle position } else if (blower_mode == OFF) do_blower(OFF); // power off blower_timer = MS_TIMER; } return; } char processBlower() { // call repeatedly to handle process states of the blower // returns non-zero when shifter or blower error char rtnval; rtnval=0; // assume all is good // Remainder only for APU blowers if (param.blowerType == blwrType_APU) { if (blower_mode==OFF) return rtnval; // nothing happening, go home. if (blower_mode==ON) return rtnval; // running ... nothing to do // check for idled blower timeout if ((blower_mode==blwrIDLE) && (last_shifter_pos == blwrIDLE) && (lastDir==0) ) { // turn off idle'd blower after 2 minutes if (MS_TIMER - blower_timer > 120000) { // turn off all blower outputs do_blowerPrs(OFF); do_blowerVac(OFF); do_blower(OFF); blower_mode=OFF; lastDir=0; } return rtnval; } // check for incomplete change of direction and reset shifter outputs. // if was in limbo, and now in a known position, reset shifter if (blowerPosition() && blower_limbo) blower(blower_mode); // if in position .. but only the first time FIX. if (blower_mode == blowerPosition()) { // turn off shifter, turn on blower do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; // if going for idle position, mode is not ON ... just idle if (blower_mode != blwrIDLE) { blower_mode = ON; // generic ON state do_blower(ON); } blower_timer=MS_TIMER; // use also for blower idle time } else if (MS_TIMER - blower_timer > 12000) { // timeout ... shut off all outputs do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; blower_mode=OFF; rtnval=1; // set error code blwrError=TRUE; } } return rtnval; } char blowerPosition() { // returns the current position of the blower shifter // also keeps track of the last valid shifter position char rtnval, inval; rtnval=0; if (di_shifterPosVac) rtnval=blwrVAC; if (di_shifterPosPrs) rtnval=blwrPRS; if (di_shifterPosIdle) rtnval=blwrIDLE; if (rtnval) last_shifter_pos=rtnval; return rtnval; } /* /******************************************************** IP Communication drivers *********************************************************/ int getUDPcommand(struct UDPmessageType *UDPmessage) { #ifdef USE_TCPIP // be sure to allocate enough space in buffer to handle possible incoming messages (up to 128 bytes for now) auto char buf[128]; auto int length, retval; int idx; char * UDPbuffer; // to index into UDPmessage byte by byte length = sizeof(buf); retval = udp_recv(&sock, buf, length); if (retval < -1) { printf("Error %d receiving datagram! Closing and reopening socket...\n", retval); sock_close(&sock); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); } } else { // is the command for me? // map it into the UDPmessage structure UDPbuffer = (char *) UDPmessage; for (idx = 0; idx < sizeof(*UDPmessage); idx++) UDPbuffer[idx] = buf[idx]; // Return it } return retval; #endif } int sendUDPcommand(struct UDPmessageType UDPmessage) { #ifdef USE_TCPIP // Send the supplied command over UDP // Appends some info to the standard message // .device // .timestamp auto int length, retval; char * UDPbuffer; // to index into UDPmessage byte by byte // fill the packet with additional data UDPmessage.device = THIS_DEVICE; // system id UDPmessage.devType = 2; // diverter UDPmessage.timestamp = MS_TIMER; length = sizeof(UDPmessage); // how many bytes to send UDPbuffer = (char *) &UDPmessage; /* send the packet */ retval = udp_send(&sock, UDPbuffer, length); if (retval < 0) { printf("Error sending datagram! Closing and reopening socket...\n"); sock_close(&sock); if(!udp_open(&sock, LOCAL_PORT, -1/*resolve(REMOTE_IP)*/, REMOTE_PORT, NULL)) { printf("udp_open failed!\n"); } } #endif } int sendUDPHeartbeat(char sample) { // Sends a periodic message to the remote stations #ifdef USE_TCPIP struct UDPmessageType HBmessage; HBmessage.command = REMOTE_PAYLOAD; HBmessage.station = MY_STATIONS; HBmessage.data[0] = arrival_from; // HBmessage.data[1] = system_state; // HBmessage.data[2] = 0; // remote alert - not used HBmessage.data[3] = transStation; // HBmessage.data[4] = mainStation; // HBmessage.data[5] = diverterStation; // HBmessage.data[6] = param.subStaAddressing; // HBmessage.data[7] = transFlags; // HBmessage.data[8] = secureAck; // secure ACK secureAck = 0; // clear Ack after sending HBmessage.data[9] = securePIN_hb; // secure PIN high byte HBmessage.data[10] = securePIN_lb; // secure PIN low byte HBmessage.data[11] = systemDirection; // transaction direction HBmessage.data[12] = purge_mode; HBmessage.data[13] = 0; // nothing sendUDPcommand(HBmessage); // ignore return value, will send again periodically #endif } void sendUDPCardParameters(void) { // Sends secure card parameters the remote stations #ifdef USE_TCPIP struct UDPmessageType HBmessage; HBmessage.command = SET_CARD_PARAMS; HBmessage.station = MY_STATIONS; HBmessage.data[0] = param.cardL3Digits; // *(unsigned long*)&HBmessage.data[1] = param.cardR9Min; // *(unsigned long*)&HBmessage.data[5] = param.cardR9Max; // sendUDPcommand(HBmessage); // ignore return value, will send again periodically #endif } /******************************************************** Communication I/O drivers *********************************************************/ /* Initialize buffers and counters */ #define BAUD_RATE 19200 #define CMD_LENGTH 11 #define RCV_TIMEOUT 2 #define rbuflen 30 #define sbuflen 5 char rbuf[rbuflen], sbuf[sbuflen]; char bufstart; //rcc void disable485whenDone(void) { while (serDwrUsed()); // wait for all bytes to be transmitted while (RdPortI(SDSR) & 0x0C); // wait for last byte to complete serDrdFlush(); // flush the read buffer ser485Rx(); // disable transmitter } /********************************************************/ void enable_commands() { // open serial port D serDopen(BAUD_RATE); ser485Rx(); // enable the receiver serDrdFlush(); // flush the read buffer } /********************************************************/ void send_response(struct iomessage message) { /* Transmits a message/command to the main system. Command string defined as: <STX> <device> <Command> <Station> <Data0..3> <ETX> <CHKSUM> */ char i; char cmdstr[CMD_LENGTH]; char cmdlen; char rcvbuf[CMD_LENGTH]; char rcvlen; unsigned long timeout, cmdsent; cmdlen=CMD_LENGTH; // enable transmitter and send ser485Tx(); /* formulate the full command string */ cmdstr[0] = STX; cmdstr[1] = THIS_DEVICE; cmdstr[2] = message.command; cmdstr[3] = message.station; for (i=0; i<NUMDATA; i++) cmdstr[i+4]=message.data[i]; cmdstr[CMD_LENGTH-2] = ETX; cmdstr[CMD_LENGTH-1] = 0; for (i=0; i<CMD_LENGTH-1; i++) cmdstr[CMD_LENGTH-1] += cmdstr[i]; /* calculate checksum */ // send it cmdlen = serDwrite(cmdstr, CMD_LENGTH); if (cmdlen != CMD_LENGTH) printf("Send command failed, only sent %d chars \n", cmdlen); disable485whenDone(); } /********************************************************/ char get_command(struct iomessage *message) { /* Repeatedly call this function to process incoming commands efficiently. */ int charsinbuf; char msg_address; //worklen, char rtnval, chksum, i; unsigned long t1, t2; char tossed[50]; // charsinbuf = rbuflen-rcc; // worklen = charsinbuf-bufstart; rtnval=FALSE; /* assume none for now */ // align frame to <STX> i=0; t1=MS_TIMER; while ((serDrdUsed() > 0) && (serDpeek() != STX)) { tossed[i]=serDgetc(); i++; } t2=MS_TIMER; if (i>0) { //printf("%ld %ld tossed %d: ",t1, t2, i); //while (i>0) { i--; printf(" %d", tossed[i]); } //printf("\n"); } // if at least 1 command in buffer then get them charsinbuf=0; if (serDrdUsed() >= CMD_LENGTH) charsinbuf = serDread(rbuf, CMD_LENGTH, RCV_TIMEOUT); bufstart = 0; if (charsinbuf==CMD_LENGTH) /* all characters received */ { /* verify STX, ETX, checksum then respond */ if ((rbuf[bufstart] == STX) && (rbuf[bufstart+CMD_LENGTH-2] == ETX)) { // enable transmitter if message is addressed to me only // set msg_address here since i'm using it next msg_address = rbuf[bufstart+1]; if (msg_address==THIS_DEVICE) ser485Tx(); //for (i=0; i<CMD_LENGTH-1; i++) printf(" %d", rbuf[bufstart+i]); /* check checksum */ chksum=0; for (i=0; i<CMD_LENGTH-1; i++) chksum+=rbuf[bufstart+i]; if (chksum != rbuf[bufstart+CMD_LENGTH-1]) { // no good, send NAK sbuf[0]=NAK; rtnval=FALSE; } else { /* looks good, send ACK */ sbuf[0]=ACK; rtnval=TRUE; } // don't set msg_address here. need to use it up above //msg_address = rbuf[bufstart+1]; // send response if message is addressed to me only if (msg_address==THIS_DEVICE) { // enable transmitter and send ser485Tx(); serDwrite(sbuf, 1); disable485whenDone(); } // If this message for me OR everyone then process it. if ((msg_address==THIS_DEVICE) || (msg_address==ALL_DEVICES)) { // message for me (and possibly others) /* return the command for processing */ message->device=msg_address; message->command=rbuf[bufstart+2]; message->station=rbuf[bufstart+3]; for (i=0; i<NUMDATA; i++) message->data[i]=rbuf[i+bufstart+4]; } else rtnval=FALSE; // command not for me! // Maybe shouldn't flush the buffer // serDrdFlush(); // flush the read buffer } } //else //{ printf("missing chars %d\n", charsinbuf); serDrdFlush(); } return rtnval; } /******************************************************************/ char isMyStation(char station) { return (station2bit(station) & MY_STATIONS); } /******************************************************************/ void msDelay(unsigned int delay) { auto unsigned long start_time; start_time = MS_TIMER; if (delay < 500) while( (MS_TIMER - start_time) <= delay ); else while( (MS_TIMER - start_time) <= delay ) hitwd(); } char Timeout(unsigned long start_time, unsigned long duration) { return ((MS_TIMER - start_time) < duration) ? FALSE : TRUE; } /*******************************************************/ // WATCHDOG AND POWER-LOW RESET COUNTERS /*******************************************************/ char valid_resets; // at myxdata+0 char watchdog_resets; // at myxdata+1 char powerlow_resets; // at myxdata+2 //xdata myxdata[10]; /*******************************************************/ char watchdogCount() { return watchdog_resets; } char powerlowCount() { return powerlow_resets; } /*******************************************************/ void incrementWDCount() { watchdog_resets++; //root2xmem( &watchdog_resets, myxdata+1, 1); } /*******************************************************/ void incrementPLCount() { powerlow_resets++; //root2xmem( &powerlow_resets, myxdata+2, 1); } /*******************************************************/ void loadResetCounters() { // read valid_resets and check //xmem2root( myxdata, &valid_resets, 1); if (valid_resets != 69) { // set to zero and mark valid watchdog_resets=0; //root2xmem( &watchdog_resets, myxdata+1, 1); powerlow_resets=0; //root2xmem( &powerlow_resets, myxdata+2, 1); valid_resets=69; //root2xmem( &valid_resets, myxdata, 1); } else { // Read watchdog and power-low counters //xmem2root( myxdata+1, &watchdog_resets, 1); //xmem2root( myxdata+2, &powerlow_resets, 1); } } int readParameterSettings(void) { // Read the parameter block param int rtn_code; rtn_code = readUserBlock(&param, 0, sizeof(param)); return rtn_code; } int writeParameterSettings(void) { // Write the parameter block param int rtn_code; rtn_code = writeUserBlock(0, &param, sizeof(param)); return rtn_code; } <file_sep>/******************************************************************* REMOTE2.C Colombo Semi-Automatic Pneumatic Tube Transfer System Purpose: Remote station control program. Processes local i/o and main_station control commands. Target: Z-World BL2500 Rabbit Language: Dynamic C v8.x Created: Jun 12, 2006 by <NAME> (C) MS Technology Solutions History: 12-Jun-06 v301 Original version created from RMOT235.c 21-Sep-06 v302 skipped version to sync with main 21-Sep-06 v303 Invert logic state of read-bank inputs 24-Sep-06 v304 Further refinement of I/O, add InUse/CIC/Flashing 22-Oct-06 v307 Sync version with Main. Integrate 4 open-door alerts. 04-Jan-07 v311 Sync version with Main. Extend command to 5 data bytes. 08-Jan-07 v312 Do not invert requestToSend inputs 10-Jan-07 v313 Setup for using ALL_DEVICES = 0xFF in .devAddr 14-Jan-07 v314 Integrate turnaround head diverter 19-Jan-07 v316 Diverter map missing [8] and causing out-of-bounds crash 24-Jan-07 v318 Continued improvements 25-Jan-07 v319 Enable TX control a bit sooner to improve communications HD & slave both known at station 8, so ready/not-ready commands now return devAddr 27-Jan-07 v320 fix bug returning response with device address (THIS_LPLC) -> (THIS_LPLC-1) Clean up implentation & reporting of latched arrival interrupt 28-Jan-07 v321 Delay response commands to give main time to be ready 01-Feb-07 v322 Switch from standard blower to heavy duty APU 03-Feb-07 v323 Initialize blower when starting up head diverter 11-Feb-07 v326 Handle failure of readDigBank when rn1100 is failed/missing Fix bug in sending arrival status to main 27-Mar-07 v342 Invert logic state of carrier in chamber and arrival optics 31-Mar-07 v343 Revert to original logic of CIC and arrival optics Set digital inputs low upon loss of connection to RN1100 10-Apr-07 v346 Set diverter addr-2 passthrough to port 4 instead of 1 03-May-07 v347 Delay clearing of arrival latch for 1 second 04-May-07 v348 Fix handling of latched arrival 24-May-07 v349 Fix bug in CIC lights not working, no IO Shift 05-Jun-07 v350 Don't clear latchedCarrierArrival until transaction is complete (remove 1 second clear) 15-Jul-07 v351 Improve exercise_io so that arrival alert and inuse light up Report latched arrival only when state is wait_for_remote_arrive Implement feature for remote alternate address request-to-send, to send to master or slave 23-Jul-07 v352 Implement compile-time selectable blower interface 25-Jul-07 v353 Bug fix for standard blower in head diverter setup (blwrConfig must equal 1) 27-Jul-07 v354 Shore up possible weakness in head diverter optic detection Head diverter arrival optic is on input 0 31-Jul-07 v355 Don't use interrupt for head diverter, raw arrival input only 29-Aug-07 v356 DEVELOPMENT VERSION 29-Dec-07 v365 Released Version - sync w/ main Get blower selection by main menu setting Get diverter port mapping configuration by main menu setting Support for point to point configuration, remote with one station, no diverter, re-mapped I/O 13-Apr-08 v366 Support for reporting blower errors Reduce blower timeout to 12 seconds so it happens before carrier lift timeout 16-Apr-08 v367 Fix mistake in initBlower: blowerPosition==0 --> blowerPosition()==0 Return blowerPosition to the main station for head diverters with APU 08-Sep-08 v368 Improve robustness of carrier arrival interrupt handling. Copy from v400. ***************************************************************/ #memmap xmem // Required to reduce root memory usage #class auto #define FIRMWARE_VERSION "REMOTE V3.68" #define VERSION 68 // compile as "STANDARD" or "POINT2POINT" remote #define RT_STANDARD 1 #define RT_POINT2POINT 2 //#define REMOTE_TYPE RT_STANDARD #define REMOTE_TYPE RT_POINT2POINT //int lastcommand; // for debug // define PRINT_ON for additional debug printing via printf // #define PRINT_ON 1 #use "bl25xx.lib" Controller library #use "rn_cfg_bl25.lib" Configuration library #use "rnet.lib" RabbitNet library #use "rnet_driver.lib" RabbitNet library #use "rnet_keyif.lib" RN1600 keypad library #use "rnet_lcdif.lib" RN1600 LCD library // RabbitNet RN1600 Setup //int DevRN1600; // Rabbit Net Device Number Keypad/LCD int DevRN1100; // Rabbit Net Device Number Digital I/O //configure to sinking safe state #define OUTCONFIG 0xFFFF // Setup interrupt handling for carrier arrival input // Set equal to 1 to use fast interrupt in I&D space #define FAST_INTERRUPT 0 char latchCarrierArrival; void my_isr1(); void arrivalEnable(char how); // Data structures #define NUMDATA 5 struct iomessage /* Communications command structure */ { char lplc; char command; char station; char data[NUMDATA]; }; // Including parameter block structure // Parameters are NOT read to / written from FLASH struct par_block_type { // These parameters are defined on the fly at run-time char opMode; // STD_REMOTE or HEAD_DIVERTER char subStaAddressing; // to indicate if substation can select slave for destination char blowerType; char portMapping; } param; #define STD_REMOTE 0 #define HEAD_DIVERTER 1 char mainStation; #define SLAVE 0x08 // Station number of the slave #define SLAVE_b 0x80 // Bit representation char THIS_LPLC; // board address for communications and setup char MY_STATIONS; // to mask supported stations char IO_SHIFT; // to map expansion board i/o char diverter_map[9]; // to assign diverter positions to stations // Global variables unsigned long thistime, lasttime, lost; /* Declare general function prototypes */ void msDelay(unsigned int msec); char bit2station(char station_b);// station_b refers to bit equivalent: 0100 char station2bit(char station); // station refers to decimal value: 3 --^ void init_counter(void); void process_local_io(void); void set_remote_io(char *remotedata); void init_io(void); void exercise_io(void); void send_response(struct iomessage message); char get_command(struct iomessage *message); void process_command(struct iomessage message); void enable_commands(void); void arrival_alert(char code, char station); char isMyStation(char station); void toggleLED(char LEDDev); void maintenance(void); char Timeout(unsigned long start_time, unsigned long duration); int readParameterSettings(void); int writeParameterSettings(void); /* Declare local and expansion bus input prototypes */ char carrierInChamber(char station_mask); char doorClosed(char station_mask); char carrierArrival(char station_mask); char requestToSend(char station_mask); char requestToSend2(char station_mask); //char diverter_pos(void); /* Declare local and expansion bus output prototypes */ char rts_latch; // Used for latching requestToSend char rts2_latch; // Used for latching 2nd requestToSend (to slave) void inUse(char how, char station_b); void alert(char how, char station_b); void alarm(char how); // void diverter(char how); void setDiverter(char station); void processDiverter(void); void setDiverterMap(char portMap); // Declare watchdog and powerlow handlers char watchdogCount(void); char powerlowCount(void); void incrementWDCount(void); void incrementPLCount(void); void loadResetCounters(void); // Digital I/O definitions char outputvalue [6]; // buffer for some outputs char remoteoutput [5]; // buffer for main commanded outputs // INPUTS int readDigInput(char channel); int readDigBank(char bank); // banks 0,1 on Coyote; banks 2,3 on RN1100 // dio_ON|OFF must be used ONLY in primatives readDigInput and setDigOutput // they reflect the real state of the logic inputs and outputs #define dio_ON 0 #define dio_OFF 1 #define di_HDArrival readDigInput(0) // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT #warnt "Compiling as point-to-point configuration" #define di_carrierArrival readDigInput(0) #define di_requestToSend readDigInput(1) #define di_requestToSend2 0 #define di_doorClosed readDigInput(2) #define di_carrierInChamber readDigInput(3) #else #define di_carrierArrival (((readDigBank(0)) & 0x1E) >> 1) #define di_carrierInChamber (((readDigBank(1)) & 0xF0) >> 4) #define di_requestToSend (readDigBank(2) & 0x0F) #define di_requestToSend2 (readDigBank(3) & 0x0F) #define di_doorClosed ((readDigBank(2) & 0xF0) >> 4) #endif #define di_remoteAddress ((readDigBank(0) & 0xE0) >> 5) #define di_diverterPos (readDigBank(1) & 0x0F) #define di_shifterPosIdle readDigInput(12) #define di_shifterPosPrs readDigInput(13) #define di_shifterPosVac readDigInput(14) // OUTPUTS void setDigOutput(int channel, int value); #define do_shift 0 // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT #define do_doorAlert(which,value) setDigOutput(0,value) #define do_arrivalAlert(which,value) setDigOutput(1,value) #define do_CICLight(which,value) setDigOutput(2,value) #define do_inUseLight(which,value) setDigOutput(3,value) // inUseLight on output 3,4,7 causes RS485 transmitter to enable (PA4) // Root cause was use of static CHAR elements in maintenance() instead of static INT #else #define do_doorAlert(which,value) setDigOutput(0+do_shift+which,value) #define do_arrivalAlert(which,value) setDigOutput(8+do_shift+which,value) #define do_inUseLight(which,value) setDigOutput(12+do_shift+which,value) #define do_inUse2Light(which,value) setDigOutput(20+do_shift+which,value) #define do_CICLight(which,value) setDigOutput(16+do_shift+which,value) #endif #define do_diverter(value) setDigOutput(4+do_shift,value) //#define do_alarm(value) setDigOutput(xx+do_shift,value) #define do_blower(value) setDigOutput(5+do_shift,value) #define do_blowerVac(value) setDigOutput(6+do_shift,value) #define do_blowerPrs(value) setDigOutput(7+do_shift,value) #define ALARM_MASK 0x20 // #define beep(value) rn_keyBuzzerAct(DevRN1600, value, 0) void inUse(char how, char station_b); void inUse2(char how, char station_b); void alarm(char how); /* "how" types & values and other constants */ #define ON 0xFF #define OFF 0x00 #define FLASH 0x01 #define READY 0x01 #define NOT_READY 0xFF //#define TRUE 0xFF //#define FALSE 0x00 #define aaRESET 0x00 #define aaSET 0x01 #define aaTEST 0x02 #define ToREMOTE 0x01 #define ToMAIN 0x02 #define ALL_DEVICES 0xFF /* Serial communications send and receive commands */ #define NAK 0x15 #define ACK 0x06 #define STX 0x02 #define ETX 0x03 #define DINBUFSIZE 63 #define DOUTBUFSIZE 63 #define SET_DIVERTER 'A' #define DIVERTER_STATUS 'B' #define DIVERTER_READY 'C' #define DIVERTER_NOT_READY 'D' #define RETURN_INPUTS 'E' #define INPUTS_ARE 'E' #define SET_OUTPUTS 'G' #define CLEAR_OUTPUTS 'H' #define SET_OPMODE 'I' #define ARE_YOU_READY 'J' #define RETURN_EXTENDED 'K' #define SET_TRANS_COUNT 'L' #define SET_DATE_TIME 'M' #define SET_STATION_NAME 'N' #define CANCEL_PENDING 'O' #define TAKE_COMMAND 'P' #define DISPLAY_MESSAGE 'Q' #define SET_PHONE_NUMS 'R' #define SET_PARAMETERS 'S' #define TRANS_COMPLETE 'X' #define RESET 'Y' #define MALFUNCTION 'Z' // Define all system states - MUST BE IDENTICAL TO MAIN #define IDLE_STATE 0x01 #define PREPARE_SEND 0x02 #define WAIT_FOR_DIVERTERS 0x03 #define BEGIN_SEND 0x04 #define WAIT_FOR_MAIN_DEPART 0x05 #define WAIT_FOR_REM_ARRIVE 0x06 #define HOLD_TRANSACTION 0x07 #define WAIT_FOR_REM_DEPART 0x08 #define WAIT_FOR_MAIN_ARRIVE 0x09 #define WAIT_FOR_TURNAROUND 0x0A #define SHIFT_TURNAROUND 0x0B #define CANCEL_STATE 0x0C #define MALFUNCTION_STATE 0x0D #define FINAL_COMMAND 0x0E // Define transaction direction constants #define DIR_SEND 1 #define DIR_RETURN 2 // Declare blower interfaces #define blwrType_STD 1 #define blwrType_APU 2 // change blwrType for the type of blower being used //#define blwrType blwrType_STD #define blwrOFF 0 #define blwrIDLE 1 #define blwrVAC 2 #define blwrPRS 3 char blwrConfig; // later to become parameter from eeprom char blwrError; void blower(char blowerOperatingValue); // use blwrOFF, blwrIDLE, blwrVAC, blwrPRS char processBlower(void); char blowerPosition(void); void initBlower(void); // Blower state is based on system_state -> [system_state][blwrConfig] // blwrConfig in remote systems is always 1 for head diverter. // No remote configuration uses a blwrConfig of 0 // Independent of blower type standard or APU const char blowerStateTable[15][2] = { blwrOFF, blwrOFF, // Undefined state 0 blwrIDLE, blwrIDLE, // 0x01 (Idle) blwrIDLE, blwrIDLE, // 0x02 blwrIDLE, blwrIDLE, // 0x03 blwrIDLE, blwrIDLE, // 0x04 blwrPRS, blwrVAC, // 0x05 (Main departure) blwrPRS, blwrPRS, // 0x06 (Remote arrival) blwrIDLE, blwrIDLE, // 0x07 blwrVAC, blwrVAC, // 0x08 (Remote departure) blwrVAC, blwrPRS, // 0x09 (Main arrival) blwrIDLE, blwrVAC, // 0x0A (Wait for turnaround) blwrIDLE, blwrIDLE, // 0x0B blwrIDLE, blwrIDLE, // 0x0C blwrOFF, blwrOFF, // 0x0D blwrIDLE, blwrIDLE };// 0x0E /* Declare miscellaneous timeouts */ #define DIVERTER_TIMEOUT 30000 // How long to set diverter // May be longer than mainsta timeout /******************************************************************/ char arrival_from; // indicates if main is ready for receive or in arrival alert /* Array index values for remote data, returned by INPUTS_ARE command. */ #define REMOTE_CIC 0 #define REMOTE_DOOR 1 #define REMOTE_ARRIVE 2 #define REMOTE_RTS 3 #define REMOTE_RTS2 4 main() { int i; unsigned long timeout; struct iomessage message; char key, simonsays; auto rn_search newdev; int status; /* Initialize i/o */ loadResetCounters(); // load counters for watchdog and powerlow resets // Initialize the controller brdInit(); // Initialize the controller rn_init(RN_PORTS, 1); // Initialize controller RN ports // Check if Rabbitnet boards are connected newdev.flags = RN_MATCH_PRDID; newdev.productid = RN1100; if ((DevRN1100 = rn_find(&newdev)) == -1) { printf("\n no RN1100 found\n"); } else status = rn_digOutConfig(DevRN1100, OUTCONFIG); //configure safe state // check if last reset was due to watchdog //if (wderror()) incrementWDCount(); hitwd(); init_io(); arrival_alert(aaRESET, 0); toggleLED(255); // initialize LED outputs readParameterSettings(); /* read board address and set configuration i/o mappings */ THIS_LPLC = (di_remoteAddress); //if (PRINT_ON) printf("\nThis is remote plc # %d", THIS_LPLC); // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT THIS_LPLC = 1; #endif // flash the plc number //flasher(0); for (i=0; i<THIS_LPLC; i++) { msDelay(200); ledOut(0,1); msDelay(150); ledOut(0,0); hitwd(); } // if (PRINT_ON) printf("\nWD and PL Reset Counters %d %d", watchdogCount(), powerlowCount()); exercise_io(); // Set the diverter mapping based on the Remote ID# setDiverterMap(param.portMapping); // setup interrupt handler for arrival optics #if __SEPARATE_INST_DATA__ && FAST_INTERRUPT interrupt_vector ext1_intvec my_isr1; #else SetVectExtern3000(1, my_isr1); // re-setup ISR's to show example of retrieving ISR address using GetVectExtern3000 //SetVectExtern3000(1, GetVectExtern3000(1)); #endif // WrPortI(I1CR, &I1CRShadow, 0x09); // enable external INT1 on PE1, rising edge, priority 1 arrivalEnable(FALSE); // Disable for now /* Initialize serial port 1 */ enable_commands(); thistime=MS_TIMER; lost=0; simonsays=TRUE; while(simonsays) { // loop forever maintenance(); // Hit WD, flash LEDs, write outputs /* check for and process incoming commands */ if (get_command(&message)) process_command(message); /* check for and process local inputs */ process_local_io(); arrival_alert(aaTEST, 0); } /* end while */ } /********************************************************/ char trans_station, diverter_station; char carrier_attn, carrier_attn2; char system_state; /********************************************************/ unsigned long arrivalDuration; char arrivalISRstate; #define AISR_RISING 1 #define AISR_FALLING 2 nodebug root interrupt void my_isr1() { /* latchCarrierArrival=TRUE; //whichCA=di_carrierArrival; //carrierArrival(255); WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 */ // New concept ... // arrivalEnable sets up for falling edge interrupt // Detect that here and then reverse setup to detect rising edge // Once rising edge detected then validate duration // If duration is good (> x ms) then latch and disable interrupt // Otherwise reset interrupt for rising edge since it was previously active if (arrivalISRstate == AISR_FALLING) // Carrier has entered optic zone { // Setup to detect rising edge WrPortI(I1CR, &I1CRShadow, 0x0A); arrivalDuration = MS_TIMER; arrivalISRstate = AISR_RISING; } else if (arrivalISRstate == AISR_RISING) // Carrier has left optic zone { // WrPortI(I1CR, &I1CRShadow, 0x00); // disable interrupt arrivalDuration = MS_TIMER - arrivalDuration; arrivalISRstate = 0; // No more activity if (arrivalDuration > 10) latchCarrierArrival=TRUE; // Got a good arrival // note: 10 ms pulse for a 12 inch carrier is 100 FPS or 61.4 MPH else { WrPortI(I1CR, &I1CRShadow, 0x06); // Too short, reset for another try arrivalISRstate = AISR_FALLING; } } } void arrivalEnable(char how) { // should call this routine once to enable interrupt and once to disable #GLOBAL_INIT { latchCarrierArrival=FALSE; } latchCarrierArrival=FALSE; // clear existing latch if (how) { // enable INT1 WrPortI(I1CR, &I1CRShadow, 0x06); // enable external INT1 on PE1, falling edge, priority 2 arrivalISRstate = AISR_FALLING; } else { // disable INT1 WrPortI(I1CR, &I1CRShadow, 0x00); // disble external INT1 on PE1 arrivalISRstate = 0; } } void setDiverterMap(char portMap) { // Sets up the diverter port mapping based on the supplied parameter // Also sets the parameter opMode to standard or head-diverter // Entry in diverter_map is the binary diverter port number (1,2,4,8) param.opMode = STD_REMOTE; switch (portMap) { case 0: break; case 1: MY_STATIONS = 0x0F; // mask for stations used by this lplc IO_SHIFT = 0; // 4 for stations 5-7, 0 for stations 1-3 diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 8; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT MY_STATIONS = 0x01; // mask for stations used by this lplc diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; #endif break; case 2: MY_STATIONS = 0x70; // mask for stations used by this lplc IO_SHIFT = 4; // 4 for stations 5-7, 0 for stations 1-3 diverter_map[0] = 0; diverter_map[1] = 8; diverter_map[2] = 8; diverter_map[3] = 8; diverter_map[4] = 8; diverter_map[5] = 1; diverter_map[6] = 2; diverter_map[7] = 4; diverter_map[8] = 0; // for main to main break; case 3: MY_STATIONS = 0x03; // mask for stations used by this lplc IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 4; diverter_map[5] = 8; diverter_map[6] = 8; diverter_map[7] = 8; diverter_map[8] = 0; // for main to main break; case 4: MY_STATIONS = 0x0C; // mask for stations used by this lplc IO_SHIFT = 2; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 1; diverter_map[4] = 2; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main break; case 5: MY_STATIONS = 0x70; // mask for stations used by this lplc IO_SHIFT = 4; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 1; diverter_map[6] = 2; diverter_map[7] = 4; diverter_map[8] = 0; // for main to main break; case 6: MY_STATIONS = 0x01; // mask for stations used by this lplc IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 2; diverter_map[4] = 2; diverter_map[5] = 2; diverter_map[6] = 2; diverter_map[7] = 2; diverter_map[8] = 0; // for main to main break; case 7: // HEAD DIVERTER USE ONLY param.opMode = HEAD_DIVERTER; MY_STATIONS = 0x80; // mask for stations used by this lplc IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 1; diverter_map[2] = 2; diverter_map[3] = 4; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main initBlower(); // only head diverter uses a blower break; default: // any other undefined selection MY_STATIONS = 0x00; // mask for stations used by this lplc IO_SHIFT = 0; // maps i/o 1-4 to stations x-x diverter_map[0] = 0; diverter_map[1] = 0; diverter_map[2] = 0; diverter_map[3] = 0; diverter_map[4] = 0; diverter_map[5] = 0; diverter_map[6] = 0; diverter_map[7] = 0; diverter_map[8] = 0; // for main to main break; } } void init_io() { char i; for (i=0; i<4; i++) // four or five output ports { outputvalue[i] = 0; remoteoutput[i] = 0; } blower(blwrOFF); alarm(OFF); } void exercise_io() { // if (!wderror()) // { alert(ON, MY_STATIONS); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); maintenance(); msDelay(1000); maintenance(); msDelay(1000); //inUse(ON, MY_STATIONS); maintenance(); msDelay(200); inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); msDelay(200); inUse(ON, MY_STATIONS); inUse2(ON, MY_STATIONS); alert(ON, MY_STATIONS); maintenance(); msDelay(200); // } inUse(OFF, MY_STATIONS); inUse2(OFF, MY_STATIONS); alert(OFF, MY_STATIONS); maintenance(); hitwd(); // hit the watchdog } /********************************************************/ void process_local_io() { char rts_data, rts2_data, cic_data; /* bitwise station bytes */ char door_closed; char on_bits, flash_bits; /* which ones on and flash */ char on_bits2, flash_bits2; /* which ones on and flash for 2nd in-use light */ char s, sb; /* work vars for station & stationbit */ char i; //static unsigned long LA_Timer; // to latch the arrival signal #GLOBAL_INIT { rts_latch=0; rts2_latch=0; trans_station=0; diverter_station=0; carrier_attn=0; carrier_attn2=0; //arrival_time=0; arrival_from=0; //LA_Timer=0; mainStation=0; param.subStaAddressing=FALSE; } /* Check for diverter and blower attention */ processDiverter(); processBlower(); /* Use local buffers for some inputs */ if (param.opMode == STD_REMOTE) { // stuff for standard remote inputs rts_data=requestToSend(MY_STATIONS); rts2_data=requestToSend2(MY_STATIONS); cic_data=carrierInChamber(MY_STATIONS); door_closed=doorClosed(MY_STATIONS); // handle carrier in chamber light // Need to shift CIC input back to (1..4) range for correct output // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT do_CICLight(0, (cic_data>>IO_SHIFT) & 1); #else for (i=0; i<4; i++) do_CICLight(i, (cic_data>>IO_SHIFT) & (1<<i)); #endif /* Latch request_to_send for new requests */ rts_latch |= (rts_data & cic_data & door_closed) & ~carrier_attn & ~rts2_data; // de-latch when rts2 pressed rts2_latch |= (rts2_data & cic_data & door_closed) & ~carrier_attn2 & ~rts_data; // de-latch when rts pressed /* Don't latch requests from station in current transaction */ rts_latch &= ~station2bit(trans_station); rts2_latch &= ~station2bit(trans_station); /* Turn off those who have lost their carrier or opened door */ rts_latch &= cic_data; rts2_latch &= cic_data; rts_latch &= door_closed; rts2_latch &= door_closed; // Setup in-use lights for primary and optional secondary in-use lights on_bits = station2bit(trans_station); flash_bits = rts_latch | rts_data; flash_bits |= ~door_closed; // flash open doors flash_bits |= carrier_attn; // flash stations needing attention (unremoved delivery) on_bits2 = station2bit(trans_station); flash_bits2 = rts2_latch | rts2_data; flash_bits2 |= ~door_closed; // flash open doors flash_bits2 |= carrier_attn2; // flash stations needing attention (unremoved delivery) if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) flash_bits2 |= station2bit(diverter_station); else flash_bits |= station2bit(diverter_station); // NEED TO LOOK INTO HOW ARRIVAL_FROM WORKS // if main arrival active, flash inuse at who sent to main if (arrival_from) { on_bits &= ~arrival_from; // Not on solid flash_bits |= arrival_from; // On flash instead } // set the in use lights as necessary inUse(OFF, ~on_bits & ~flash_bits & MY_STATIONS & ~station2bit(trans_station)); inUse(ON, on_bits); inUse(FLASH, flash_bits & ~station2bit(trans_station)); inUse2(OFF, ~on_bits2 & ~flash_bits2 & MY_STATIONS & ~station2bit(trans_station)); inUse2(ON, on_bits2); inUse2(FLASH, flash_bits2 & ~station2bit(trans_station)); // latch the arrival signal i = carrierArrival(MY_STATIONS); if (i) latchCarrierArrival=TRUE; // latch this value } else { // stuff for head diverter //i = di_HDArrival; // && (system_state==WAIT_FOR_TURNAROUND) if (di_HDArrival && (system_state==WAIT_FOR_TURNAROUND)) latchCarrierArrival=TRUE; // latch this value rts_data=0; // No push to send buttons cic_data=0; // No carrier in chamber optics door_closed=0; // No door switches } } /********************************************************/ void process_command(struct iomessage message) { char wcmd, wdata; char ok; char i; //static char system_state, new_state; static char new_state; static unsigned long LCA_Timer; struct iomessage response; #GLOBAL_INIT { system_state=IDLE_STATE; new_state=system_state; LCA_Timer=0; } response.command=0; response.station=message.station; // set initial default /* determine what type of command */ switch(message.command) { case ARE_YOU_READY: // debug to see what may be causing loss of communication //lastcommand=message.command; // enable arrival interrupt / latch if (param.opMode == STD_REMOTE) arrivalEnable(TRUE); // don't enable interrupt for head diverter response.command=ARE_YOU_READY; // assume ready for now response.data[0]=1<<(THIS_LPLC-1); trans_station=message.station; mainStation=message.data[1]; // get the main station to be used // Negate assumption if not ready if (isMyStation(message.station) && (param.opMode == STD_REMOTE)) { // stuff for standard remote rts_latch &= ~station2bit(message.station); // clear latch rts2_latch &= ~station2bit(message.station); // clear latch /* only if door closed, and (CIC or send-to-here) */ if ( doorClosed(station2bit(message.station)) && ( carrierInChamber(station2bit(message.station)) || message.data[0]==DIR_SEND) ) { // ready if (param.subStaAddressing && mainStation==SLAVE) { inUse2(ON, station2bit(message.station)); }else { inUse(ON, station2bit(message.station)); } } else { response.data[0]=0; // not ready if (param.subStaAddressing && mainStation==SLAVE) inUse2(OFF, station2bit(message.station)); else inUse(OFF, station2bit(message.station)); alert(ON, station2bit(message.station)); } } break; case SET_DIVERTER: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote if (param.subStaAddressing && message.data[1]==SLAVE) inUse2(FLASH, station2bit(message.station)); else inUse(FLASH, station2bit(message.station)); setDiverter(message.station); } else { // stuff for head diverter setDiverter(message.data[0]); // head diverter comes in different byte } mainStation=message.data[1]; // get the main station to be used param.subStaAddressing=message.data[2]; param.blowerType = message.data[3]; break; case DIVERTER_STATUS: /* return logic of correct position */ // debug to see what may be causing loss of communication //lastcommand=message.command; response.command=DIVERTER_STATUS; // which port dependent on opMode if (param.opMode == STD_REMOTE) i = message.station; else i = message.data[0]; // is that port aligned? or not used? if ( (di_diverterPos == diverter_map[i]) || (diverter_map[i] == 0) ) { response.data[0]=1<<(THIS_LPLC-1); // DIVERTER_READY; } else { response.data[0]=0; // DIVERTER_NOT_READY; } break; case RETURN_INPUTS: /* return general status */ // debug to see what may be causing loss of communication //lastcommand=message.command; // main includes some status info here ... pull it out arrival_from=message.data[0]; new_state=message.data[1]; // NOT USING IT: system_direction=message.data[2]; // tell main how I am doing response.command=INPUTS_ARE; response.station=MY_STATIONS; // return this to enlighten main // fill in the rest of the response based on who I am if (param.opMode == STD_REMOTE) { // stuff for standard remote // Return latched carrier arrival if state is wait_for_remote_arrival if (latchCarrierArrival && system_state==WAIT_FOR_REM_ARRIVE) ok=TRUE; else ok=FALSE; // Return the arrival signal response.data[REMOTE_ARRIVE]=carrierArrival(MY_STATIONS); // but if it is none then send latched arrival under some conditions if ((response.data[REMOTE_ARRIVE]==0) && (latchCarrierArrival) && (system_state==WAIT_FOR_REM_ARRIVE)) response.data[REMOTE_ARRIVE]=latchCarrierArrival; response.data[REMOTE_CIC]=carrierInChamber(MY_STATIONS); response.data[REMOTE_DOOR]=doorClosed(MY_STATIONS); response.data[REMOTE_RTS]=rts_latch; response.data[REMOTE_RTS2]=rts2_latch; } else { // stuff for head diverter // Return latched carrier arrival if state is wait_for_turnaround if ((latchCarrierArrival || di_HDArrival) && (system_state==WAIT_FOR_TURNAROUND)) ok=TRUE; else ok=FALSE; // Return the arrival signal if (ok) response.data[REMOTE_ARRIVE]=MY_STATIONS; else response.data[REMOTE_ARRIVE]=0; response.data[REMOTE_CIC]=0; response.data[REMOTE_DOOR]=0; // HD has no stations MY_STATIONS; response.data[REMOTE_RTS]=0; if (blwrError==FALSE) response.data[REMOTE_RTS2]=blowerPosition(); else response.data[REMOTE_RTS2]=0xFF; // Blower has an error } break; case RETURN_EXTENDED: /* return extended data */ // debug to see what may be causing loss of communication //lastcommand=message.command; // return watchdog and powerlow counters response.command=RETURN_EXTENDED; response.data[0]=0;//watchdogCount(); response.data[1]=0;//powerlowCount(); response.data[2]=VERSION; break; case SET_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote /* set outputs from mainsta */ set_remote_io(&message.data[0]); } break; case CLEAR_OUTPUTS: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_OPMODE: // debug to see what may be causing loss of communication //lastcommand=message.command; break; case SET_PARAMETERS: // get the blower type and other parameters // debug to see what may be causing loss of communication //lastcommand=message.command; param.portMapping = message.data[0]; param.blowerType = message.data[1]; writeParameterSettings(); setDiverterMap(param.portMapping); break; case TRANS_COMPLETE: // debug to see what may be causing loss of communication //lastcommand=message.command; arrivalEnable(FALSE); // Disable arrival interrupt trans_station=0; if (param.opMode == STD_REMOTE) { // stuff for standard remote alert(OFF, station2bit(message.station)); // set arrival alert if the transaction is to here if (message.data[0] == DIR_SEND && isMyStation(message.station)) { if (message.data[1]==1) // and Main says to set arrival alert { // OK to set alert // REDUNDANT inUse(FLASH, station2bit(message.station)); // until no cic if ((mainStation==SLAVE) && (param.subStaAddressing==TRUE)) carrier_attn2 |= station2bit(message.station); // to flash inuse else carrier_attn |= station2bit(message.station); // to flash inuse arrival_alert(aaSET, message.station); } } else if (message.data[0] == DIR_RETURN && isMyStation(message.station)) { // capture the main arrival flag } } // nothing else for head diverter break; case MALFUNCTION: // may be contributing to funky flashing // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // turn on alarm output only inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(ON); arrival_alert(aaRESET, 0); } arrivalEnable(FALSE); // Disable arrival interrupt rts_latch=0; rts2_latch=0; trans_station=0; diverter_station=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; case RESET: // debug to see what may be causing loss of communication //lastcommand=message.command; if (param.opMode == STD_REMOTE) { // stuff for standard remote only // Turn off all outputs inUse(OFF, MY_STATIONS); // clear local i/o inUse2(OFF, MY_STATIONS); // clear local i/o alert(OFF, MY_STATIONS); alarm(OFF); arrival_alert(aaRESET, 0); } blwrError=FALSE; // reset blower error arrivalEnable(FALSE); // Disable arrival interrupt /// rts_latch=0; Try to not clear latch on reset trans_station=0; diverter_station=0; response.data[0]=0; // clear remote i/o response.data[1]=0; response.data[2]=0; response.data[3]=0; set_remote_io(&response.data[0]); break; } /* send the response message if any AND the query was only to me */ if (response.command && (message.lplc==THIS_LPLC)) { msDelay(2); // hold off response just a bit //response.lplc=THIS_LPLC; send_response(response); } // process state change if (new_state != system_state) { // set blower for new state system_state=new_state; blower(blowerStateTable[system_state][blwrConfig]); } return; } unsigned long alert_timer[8]; // for stations 1..7 ... [0] is not used. void arrival_alert(char func, char station) { int i; switch (func) { case aaRESET: for (i=1; i<=7; i++) { alert_timer[i]=0; alert(OFF, station2bit(i)); } break; case aaSET: if (station>=1 && station<=7) // make sure s# is correct { alert_timer[ station ] = SEC_TIMER; } break; case aaTEST: for (i=1; i<=7; i++) // Check each station { if (alert_timer[i]) { if ( carrierInChamber( station2bit(i) )) // || (remote_stat_alert==i) ) { // Flash as necessary if ( (SEC_TIMER - alert_timer[i]) %20 >= 10 ) alert(ON, station2bit(i)); else alert(OFF, station2bit(i)); } //else if (clock() = alert_timer[i] > 1) else if (!doorClosed( station2bit(i) ) || i==trans_station) { // no carrier, door open // or no carrier, in transit --> reset alert_timer[i]=0; alert(OFF, station2bit(i)); carrier_attn &= ~station2bit(i); // clear attn flag carrier_attn2 &= ~station2bit(i); // clear attn flag } } else { carrier_attn &= ~station2bit(i); // no timer, so no flag carrier_attn2 &= ~station2bit(i); // no timer, so no flag } } break; } } /************************************************************/ /************** DIGITAL I/O *************************/ /************************************************************/ #define devIUS 0 #define devIUF 1 #define devAlert 2 #define devAlarm 3 #define dev2IUS 4 #define dev2IUF 5 // #define devDoorAlert 4 int readDigInput(char channel) { // returns the state of digital input 0-39 // function supports inverted logic by assigning dio_ON and dio_OFF char rtnval; if (channel < 16) { // on-board inputs rtnval = digIn(channel); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digIn(DevRN1100, channel-16, &rtnval, 0) == -1) rtnval=1; } // 1 is off else rtnval = 0; } // deal with logic inversion if (rtnval) rtnval = dio_ON; else rtnval = dio_OFF; return rtnval; } int readDigBank(char bank) { // returns the state of digital input banks 0-3 // banks 0-1 on Coyote; banks 2-3 on RN1100 // function supports inverted logic by assigning dio_ON and dio_OFF static char rtnval[4]; // to cache previous inputs char returnVal; char temp; #GLOBAL_INIT { rtnval[0]=0; rtnval[1]=0; rtnval[2]=0; rtnval[3]=0; } if (bank < 2) { // on-board inputs rtnval[bank] = digBankIn(bank); } else { // rn1100 inputs if (DevRN1100 != -1) { if (rn_digBankIn(DevRN1100, bank-1, &temp, 0) == -1) rtnval[bank]=0xFF; // 1 is off else rtnval[bank]=temp; } } returnVal = rtnval[bank]; // deal with logic inversion if (dio_OFF) returnVal ^= 0xFF; return returnVal; } void setDigOutput(int channel, int value) { // sets the state of digital output 0-23 // call with logic value (0=OFF, 1=ON) // function is adapted to support inverted logic by assigning dio_ON and dio_OFF int outval; // check for logic inversion if (value) outval = dio_ON; else outval = dio_OFF; if (channel < 8) { // on-board outputs digOut(channel, outval); } else { // rn1100 outputs if (DevRN1100 != -1) rn_digOut(DevRN1100, channel-8, outval, 0); } } /*************************************************************/ void set_remote_io(char *remotedata) { /* save state of remote output request */ remoteoutput[0]=remotedata[0]; remoteoutput[1]=remotedata[1]; // remoteoutput[2]=remotedata[2]; // THIS IS devAlert - DON'T TAKE FROM MAIN remoteoutput[2]=remotedata[2]; // Instead use remotedata[2] to drive the door alert remoteoutput[3]=remotedata[3]; /* write out all outputs .. some may need to be shifted */ // write4data(addrIUS, outputvalue[devIUS] | remoteoutput[devIUS]); // write4data(addrIUF, outputvalue[devIUF] | remoteoutput[devIUF]); // outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); // write4data(addrALT, outval); // write4data(addrALM, outputvalue[devAlarm] | remoteoutput[devAlarm]); // Write remotedata[devAlert] to output ports O5-O8 // hv_outval &= ~DOOR_ALERT_MASK; // turn off door alert bits // hv_outval = (remotedata[devAlert] & MY_STATIONS) >> IO_SHIFT; // hv_wr(hv_outval); } /******************************************************************/ char carrierInChamber(char stamask) { return (di_carrierInChamber << IO_SHIFT) & stamask; } /******************************************************************/ char doorClosed(char stamask) { // Note: input is normally high on closed. char indata; indata = di_doorClosed; return ((indata << IO_SHIFT) & stamask); } /******************************************************************/ char carrierArrival(char stamask) { return (di_carrierArrival << IO_SHIFT) & stamask; } /******************************************************************/ char requestToSend(char stamask) { char indata; indata = di_requestToSend; return ((indata << IO_SHIFT) & stamask); } char requestToSend2(char stamask) { char indata; indata = di_requestToSend2; return ((indata << IO_SHIFT) & stamask); } /******************************************************************/ void inUse(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[devIUS] |= station_b; outputvalue[devIUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[devIUS] &= ~station_b; outputvalue[devIUF] |= station_b; } return; } void inUse2(char how, char station_b) { if (how == ON) { /* solid on, flash off */ outputvalue[dev2IUS] |= station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == OFF) { /* solid off, flash off */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] &= ~station_b; } if (how == FLASH) { /* solid off, flash on */ outputvalue[dev2IUS] &= ~station_b; outputvalue[dev2IUF] |= station_b; } return; } /******************************************************************/ void alert(char how, char station_b) { if (how == ON) outputvalue[devAlert] |= station_b; if (how == OFF) outputvalue[devAlert] &= ~station_b; //outval = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); //write4data(addrALT, outval); //do_alert(outval, how); // OUTPUTS WRITTEN IN SYSTEM LOOP CALL TO updateOutputs(); return; } /******************************************************************/ void alarm(char how) { // outputvalue is checked in the inUse function to turn alarm on/off outputvalue[devAlarm] = how; return; } /******************************************************************/ unsigned long diverter_start_time; // these used primarily by diverter functions char diverter_setting; char diverter_attention; void setDiverter(char station) { /* Controls the setting of diverter positions Return from this routine is immediate. If diverter is not in position, it is turned on and a timer started. You MUST repeatedly call processDiverter() to complete processing of the diverter control position */ /* use mapping from station to diverter position */ if ((station>0) && (station<9)) // Valid station # { diverter_setting = diverter_map[station]; // mapped setting // if position<>ANY (any=0) and not in position if ((diverter_setting>0) && (diverter_setting!=di_diverterPos)) { /* turn on diverter and start timer */ do_diverter(ON); diverter_start_time = MS_TIMER; diverter_attention = TRUE; diverter_station=station; } } return; } /******************************************************************/ void processDiverter() { /* Poll type processing of diverter control system */ /* Allows other processes to be acknowleged when setting diverter */ if (diverter_attention) { if ((diverter_setting == di_diverterPos) || Timeout(diverter_start_time, DIVERTER_TIMEOUT)) { // turn off diverter and clear status do_diverter(OFF); diverter_attention = FALSE; diverter_station=0; } } } void showactivity() { // update active processor signal ledOut(0, (MS_TIMER %500) < 250); // on fixed frequency ledOut(1, (MS_TIMER %500) > 250); // off fixed frequency toggleLED(2); // toggle each call } void toggleLED(char LEDDev) { static char LEDState[4]; // if LEDDev not 0..3 then initialize LED states off if (LEDDev > 3) { LEDState[0]=0; LEDState[1]=0; LEDState[2]=0; LEDState[3]=0; } else { LEDState[LEDDev] ^= 1; // toggle LED state on/off ledOut(LEDDev, LEDState[LEDDev]); // send LED state } } void maintenance(void) { // handle all regularly scheduled calls // use of static CHAR was causing PA4 RS485 transmitter to enable without reason ... static INT works ok. static int out_alert, out_inuse, out_inuse2, out_doorAlert; char i; hitwd(); // hit the watchdog timer showactivity(); //rn_keyProcess(DevRN1600, 0); // process keypad device // process command communications //tcp_tick(NULL); //receive_command(); // process flashing inUse lights // out_alert = ((outputvalue[devAlert] | remoteoutput[devAlert]) >> IO_SHIFT); out_alert = ((outputvalue[devAlert]) >> IO_SHIFT); out_doorAlert = (remoteoutput[devAlert] >> IO_SHIFT); // flash on if ((MS_TIMER %500) < 200) { out_inuse = (outputvalue[devIUF] | outputvalue[devIUS]) >> IO_SHIFT; out_inuse2 = (outputvalue[dev2IUF] | outputvalue[dev2IUS]) >> IO_SHIFT; } // or flash off else { out_inuse = outputvalue[devIUS] >> IO_SHIFT; out_inuse2 = outputvalue[dev2IUS] >> IO_SHIFT; } // Write out alerts and inUse light // Check for and setup point to point configuration #if REMOTE_TYPE == RT_POINT2POINT do_arrivalAlert(0, out_alert & 1); do_inUseLight(0, out_inuse & 1); do_doorAlert(0, out_doorAlert & 1); #else for (i=0; i<4; i++) { do_arrivalAlert(i, out_alert & (1<<i)); do_inUseLight(i, out_inuse & (1<<i)); do_inUse2Light(i, out_inuse2 & (1<<i)); do_doorAlert(i, out_doorAlert & (1<<i)); } #endif // Process alarm output //do_alarm(outputvalue[devAlarm]); } /******************************************************************/ // Blower Processing Routines - supports both standard and APU blowers /******************************************************************/ // Interface definition // char blwrConfig; // to become a parameter from eeprom // blwrConfig 0 = Standard blower // blwrConfig 1 = High capacity APU blower // #define blwrOFF 0 // #define blwrIDLE 1 // #define blwrVAC 2 // #define blwrPRS 3 // void initBlower(void); // void blower(char blowerOperatingValue); // use blwrOFF, blwrIDLE, blwrVAC, blwrPRS // char processBlower(void); // char blowerPosition(void); char blower_mode, blower_limbo, last_shifter_pos, lastDir; unsigned long blower_timer; void initBlower() { // trys to find any shifter position, then goes to idle unsigned long mytimer; blwrConfig = 1; // Turnaround configuration // Clear global blower variables last_shifter_pos=0; lastDir=0; blower_limbo=FALSE; blwrError=FALSE; // turn off all outputs do_blower(OFF); do_blowerVac(OFF); do_blowerPrs(OFF); // remainder of initialization is for APU blowers only if (param.blowerType == blwrType_APU) { // if not in any position, try to find any position if (blowerPosition() == 0) { // hunt for any position do_blowerPrs(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); if (blowerPosition()==0) { // still not found...so go the other way do_blowerPrs(OFF); do_blowerVac(ON); mytimer=MS_TIMER; while (Timeout(mytimer, 5000)==FALSE && blowerPosition()==0) hitwd(); do_blowerVac(OFF); if (blowerPosition()==0) blwrError = TRUE; // capture unknown position error } } // after all that, now command to goto idle blower(blwrIDLE); } } void blower(char request) { // operates both standard blowers and APU blowers // sets the direction of the blower shifter // use blwrVAC, blwrPRS, blwrIDLE, or OFF char hv_save; char how; static char lastHow; #GLOBAL_INIT { blwrConfig = 1; // Turnaround configuration lastHow = 0; } // Handling of standard blower type if (param.blowerType == blwrType_STD) { // No such state as idle in standard blowers so map to OFF if (request==blwrIDLE) request=blwrOFF; how = request; // make sure correct parameter is used. anything but VAC and PRS is OFF if ((how != blwrVAC) && (how != blwrPRS)) how = blwrOFF; // if going from one on-state to the other on-state then turn off first if ((how != blwrOFF) && (lastHow != blwrOFF) && (how != lastHow)) { // can't run in both directions at the same time do_blowerPrs(OFF); do_blowerVac(OFF); msDelay(100); /* wait a little while */ } /* turn on appropriate bit */ if (how == blwrPRS) do_blowerPrs(ON); else if (how == blwrVAC) do_blowerVac(ON); else { do_blowerPrs(OFF); do_blowerVac(OFF); } // Add alternate blower on/off control per Joe request on 10-Jul-07 if (how != blwrOFF) do_blower(ON); else do_blower(OFF); // remember last setting lastHow = how; } // end of standard blower // Handling of APU blower type else if ((param.blowerType == blwrType_APU) && (request != lastHow)) { // store in local work space blower_mode=request; blower_limbo=FALSE; lastHow=request; /* clear previous state */ // hv_save=output_buffer; // turn off shifters do_blowerPrs(OFF); do_blowerVac(OFF); // CW for Pressure to Idle or Any to Vacuum // CCW for Vacuum to Idle or Any to Pressure if (blower_mode == blwrVAC) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blower_mode == blwrPRS) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blower_mode == blwrIDLE) { if (blowerPosition() == blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (blowerPosition() == blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else if (blowerPosition() == 0) { // go to idle but don't know which way if (lastDir==blwrVAC) { do_blowerVac(ON); blower_limbo=TRUE; lastDir=blwrVAC; } else if (lastDir==blwrPRS) { do_blowerPrs(ON); blower_limbo=TRUE; lastDir=blwrPRS; } else { // use last position to know which way to go blower_limbo = TRUE; // incomplete operation if (last_shifter_pos==blwrPRS) { do_blowerVac(ON); lastDir=blwrVAC; } else if (last_shifter_pos==blwrVAC) { do_blowerPrs(ON); lastDir=blwrPRS; } else blower_limbo=FALSE; // idle to idle is ok to leave alone } } // else go-idle and already in idle position } else if (blower_mode == OFF) do_blower(OFF); // power off blower_timer = MS_TIMER; } return; } char processBlower() { // call repeatedly to handle process states of the blower // returns non-zero when shifter or blower error char rtnval; rtnval=0; // assume all is good // Remainder only for APU blowers if (param.blowerType == blwrType_APU) { if (blower_mode==OFF) return rtnval; // nothing happening, go home. if (blower_mode==ON) return rtnval; // running ... nothing to do // check for idled blower timeout if ((blower_mode==blwrIDLE) && (last_shifter_pos == blwrIDLE) && (lastDir==0) ) { // turn off idle'd blower after 2 minutes if (MS_TIMER - blower_timer > 120000) { // turn off all blower outputs do_blowerPrs(OFF); do_blowerVac(OFF); do_blower(OFF); blower_mode=OFF; lastDir=0; } return rtnval; } // check for incomplete change of direction and reset shifter outputs. // if was in limbo, and now in a known position, reset shifter if (blowerPosition() && blower_limbo) blower(blower_mode); // if in position .. but only the first time FIX. if (blower_mode == blowerPosition()) { // turn off shifter, turn on blower do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; // if going for idle position, mode is not ON ... just idle if (blower_mode != blwrIDLE) { blower_mode = ON; // generic ON state do_blower(ON); } blower_timer=MS_TIMER; // use also for blower idle time } else if (MS_TIMER - blower_timer > 12000) { // timeout ... shut off all outputs do_blowerPrs(OFF); do_blowerVac(OFF); lastDir=0; blower_mode=OFF; rtnval=1; // set error code blwrError=TRUE; } } return rtnval; } char blowerPosition() { // returns the current position of the blower shifter // also keeps track of the last valid shifter position char rtnval, inval; rtnval=0; if (di_shifterPosVac) rtnval=blwrVAC; if (di_shifterPosPrs) rtnval=blwrPRS; if (di_shifterPosIdle) rtnval=blwrIDLE; if (rtnval) last_shifter_pos=rtnval; return rtnval; } /******************************************************** Communication I/O drivers *********************************************************/ /* Initialize buffers and counters */ #define BAUD_RATE 19200 #define CMD_LENGTH 11 #define RCV_TIMEOUT 2 #define rbuflen 30 #define sbuflen 5 char rbuf[rbuflen], sbuf[sbuflen]; char bufstart; //rcc void disable485whenDone(void) { while (serDwrUsed()); // wait for all bytes to be transmitted while (RdPortI(SDSR) & 0x0C); // wait for last byte to complete serDrdFlush(); // flush the read buffer ser485Rx(); // disable transmitter } /********************************************************/ void enable_commands() { // open serial port D serDopen(BAUD_RATE); ser485Rx(); // enable the receiver serDrdFlush(); // flush the read buffer } /********************************************************/ void send_response(struct iomessage message) { /* Transmits a message/command to the main system. Command string defined as: <STX> <lplc> <Command> <Station> <Data0..3> <ETX> <CHKSUM> */ char i; char cmdstr[CMD_LENGTH]; char cmdlen; char rcvbuf[CMD_LENGTH]; char rcvlen; unsigned long timeout, cmdsent; cmdlen=CMD_LENGTH; // enable transmitter and send ser485Tx(); /* formulate the full command string */ cmdstr[0] = STX; cmdstr[1] = THIS_LPLC; cmdstr[2] = message.command; cmdstr[3] = message.station; for (i=0; i<NUMDATA; i++) cmdstr[i+4]=message.data[i]; cmdstr[CMD_LENGTH-2] = ETX; cmdstr[CMD_LENGTH-1] = 0; for (i=0; i<CMD_LENGTH-1; i++) cmdstr[CMD_LENGTH-1] += cmdstr[i]; /* calculate checksum */ // send it cmdlen = serDwrite(cmdstr, CMD_LENGTH); if (cmdlen != CMD_LENGTH) printf("Send command failed, only sent %d chars \n", cmdlen); disable485whenDone(); } /********************************************************/ char get_command(struct iomessage *message) { /* Repeatedly call this function to process incoming commands efficiently. */ int charsinbuf; char msg_address; //worklen, char rtnval, chksum, i; unsigned long t1, t2; char tossed[50]; // charsinbuf = rbuflen-rcc; // worklen = charsinbuf-bufstart; rtnval=FALSE; /* assume none for now */ // align frame to <STX> i=0; t1=MS_TIMER; while ((serDrdUsed() > 0) && (serDpeek() != STX)) { tossed[i]=serDgetc(); i++; } t2=MS_TIMER; if (i>0) { //printf("%ld %ld tossed %d: ",t1, t2, i); //while (i>0) { i--; printf(" %d", tossed[i]); } //printf("\n"); } // if at least 1 command in buffer then get them charsinbuf=0; if (serDrdUsed() >= CMD_LENGTH) charsinbuf = serDread(rbuf, CMD_LENGTH, RCV_TIMEOUT); bufstart = 0; if (charsinbuf==CMD_LENGTH) /* all characters received */ { /* verify STX, ETX, checksum then respond */ if ((rbuf[bufstart] == STX) && (rbuf[bufstart+CMD_LENGTH-2] == ETX)) { // enable transmitter if message is addressed to me only if (msg_address==THIS_LPLC) ser485Tx(); /* check checksum */ chksum=0; for (i=0; i<CMD_LENGTH-1; i++) chksum+=rbuf[bufstart+i]; if (chksum != rbuf[bufstart+CMD_LENGTH-1]) { // no good, send NAK sbuf[0]=NAK; rtnval=FALSE; } else { /* looks good, send ACK */ sbuf[0]=ACK; rtnval=TRUE; } msg_address = rbuf[bufstart+1]; // send response if message is addressed to me only if (msg_address==THIS_LPLC) { // enable transmitter and send ser485Tx(); serDwrite(sbuf, 1); disable485whenDone(); } // If this message for me OR everyone then process it. if ((msg_address==THIS_LPLC) || (msg_address==ALL_DEVICES)) { // message for me (and possibly others) /* return the command for processing */ message->lplc=msg_address; message->command=rbuf[bufstart+2]; message->station=rbuf[bufstart+3]; for (i=0; i<NUMDATA; i++) message->data[i]=rbuf[i+bufstart+4]; } else rtnval=FALSE; // command not for me! // Maybe shouldn't flush the buffer // serDrdFlush(); // flush the read buffer } } //else //{ printf("missing chars %d\n", charsinbuf); serDrdFlush(); } return rtnval; } /******************************************************************/ char isMyStation(char station) { return (station2bit(station) & MY_STATIONS); } /******************************************************************/ char station2bit(char station) { /* Converts the station number assignment to an equivalent bit value. ie. station 3 -> 0100 (=4) .. same as 2^(sta-1) NOTE: Returns 0 if station is not 1..8 */ if (station) return 1 << (station-1); return 0; } /******************************************************************/ char bit2station(char station_b) { /* Converts a bit assignment to the bit number value ie. 0100 -> station 3. NOTE: Returns 0 if more than 1 station bit is active */ char stanum, i; stanum = 0; for (i=0; i<8; i++) { if (1<<i == station_b) stanum=i+1; } return stanum; } void msDelay(unsigned int delay) { auto unsigned long start_time; start_time = MS_TIMER; if (delay < 500) while( (MS_TIMER - start_time) <= delay ); else while( (MS_TIMER - start_time) <= delay ) hitwd(); } char Timeout(unsigned long start_time, unsigned long duration) { return ((MS_TIMER - start_time) < duration) ? FALSE : TRUE; } /*******************************************************/ // WATCHDOG AND POWER-LOW RESET COUNTERS /*******************************************************/ char valid_resets; // at myxdata+0 char watchdog_resets; // at myxdata+1 char powerlow_resets; // at myxdata+2 //xdata myxdata[10]; /*******************************************************/ char watchdogCount() { return watchdog_resets; } char powerlowCount() { return powerlow_resets; } /*******************************************************/ void incrementWDCount() { watchdog_resets++; //root2xmem( &watchdog_resets, myxdata+1, 1); } /*******************************************************/ void incrementPLCount() { powerlow_resets++; //root2xmem( &powerlow_resets, myxdata+2, 1); } /*******************************************************/ void loadResetCounters() { // read valid_resets and check //xmem2root( myxdata, &valid_resets, 1); if (valid_resets != 69) { // set to zero and mark valid watchdog_resets=0; //root2xmem( &watchdog_resets, myxdata+1, 1); powerlow_resets=0; //root2xmem( &powerlow_resets, myxdata+2, 1); valid_resets=69; //root2xmem( &valid_resets, myxdata, 1); } else { // Read watchdog and power-low counters //xmem2root( myxdata+1, &watchdog_resets, 1); //xmem2root( myxdata+2, &powerlow_resets, 1); } } int readParameterSettings(void) { // Read the parameter block param int rtn_code; rtn_code = readUserBlock(&param, 0, sizeof(param)); return rtn_code; } int writeParameterSettings(void) { // Write the parameter block param int rtn_code; rtn_code = writeUserBlock(0, &param, sizeof(param)); return rtn_code; } <file_sep>#use "bl25xx.lib" Controller library /************************************************************************ SF_BL25_SPD.C Used the BL2500 and the SF1016 *************************************************************************/ #define SPI_SER_C #define SPI_CLK_DIVISOR 20 // was 20 #define SF1000_CS_PORT PADR // CS = PA0 J3:1 pulled high with // 4.7K resistor. #define SF1000_CS_PORTSHADOW PADRShadow #define SF1000_CS_BIT 0 #define CS_ENABLE BitWrPortI ( SF1000_CS_PORT, &SF1000_CS_PORTSHADOW, 1, SF1000_CS_BIT );\ SPIxor = 0xFF; // invert the received bits #define CS_DISABLE BitWrPortI ( SF1000_CS_PORT, &SF1000_CS_PORTSHADOW, 0, SF1000_CS_BIT ); #define SF1000_DEBUG debug #define SF1000_DEBUG_DELAY 7 // 7 is default in SF1000.lib #use SF1000.lib union { char cData[1024]; int iData[512]; } Block; union { int ival; char cval[2]; } Value; main() { unsigned long Tstart, Telap; int block, i, j, k, TestBlock, NbrOfBlocks; int BlockCount; long FlashAddr, iLong; float Tblock; int attempts; brdInit(); // Initialize the controller attempts = 0; do { i = SF1000Init (); // initialize the flash if ( i ) { if ( i == -1 ) printf ( "Invalid configuration value: %d\n", i ); if ( i == -2 ) printf ( "Unknown response: %d\n", (int)SF1000_String[0] ); if ( i == -3 ) printf ( "Device not responding: %d\n", (int)SF1000_String[0] ); attempts++; } }while(i && attempts < 20); if(i) { printf("failure\n"); while(1); } iLong = (long)SF1000_Block_size*(long)SF1000_Nbr_of_Blocks/1000000L; printf ( "Density = %d, Block Size = %d,\n\rNbr of Blocks = %d, Total Memory = %ldMB\n\r", SF1000_Density_Value, SF1000_Block_size, SF1000_Nbr_of_Blocks, iLong ); printf ( "\n\nShort Test...............\n\r" ); TestBlock = 1; //SF1000_Nbr_of_Blocks/2 + 1; i=5; iLong = SF1000CheckWrites (TestBlock); printf ( "\nBlock %d has been written %ld times\n\rWrite once more", TestBlock, iLong ); FlashAddr = (long)(TestBlock)*SF1000_Block_size; while ( (j=SF1000Write ( FlashAddr, (char*)&i, 2 )) != 0 )printf("\n%d",j); printf ( "\nWrite result %d", j); i=4; while ( (j=SF1000Read( FlashAddr, (char*)&i, 2)) !=0)printf("\ni=%d j=%d",i,j); printf ( "\nRead back value %d, status %d", i, j); iLong = SF1000CheckWrites (TestBlock); printf ( "\nBlock %d has been written %ld times\n\rWrite once more", TestBlock, iLong ); while ( SF1000Write ( FlashAddr, (char*)&i, 2 ) == -3 ); iLong = SF1000CheckWrites (TestBlock); printf ( "\n\rBlock %d has been written %ld times", TestBlock, iLong ); printf ( "\n\r\nWrite 0xAA to block 0 " ); memset ( Block.cData, 0xAA, SF1000_Block_size ); while ( SF1000Write ( 0, Block.cData, SF1000_Block_size ) == -3 ); iLong = SF1000CheckWrites (0); printf ( "\n\rBlock # 0 has been written %ld times", iLong ); printf ( "\n\rWrite 0x55 to block 1 " ); memset ( Block.cData, 0x55, SF1000_Block_size ); while ( SF1000Write ( SF1000_Block_size, Block.cData, SF1000_Block_size ) == -3 ); iLong = SF1000CheckWrites (1); printf ( "\n\rBlock # 1 has been written %ld times", iLong ); SF1000Read ( 0, Block.cData, SF1000_Block_size ); printf ( "\n\rVerify block 0" ); for ( i=0; i<SF1000_Block_size; i++ ) if ( Block.cData[i] != 0xAA ) printf ( " %d %x\n", i, Block.cData[i] ); SF1000Read ( SF1000_Block_size, Block.cData, SF1000_Block_size ); printf ( "\n\rVerify block 1" ); for ( i=0; i<SF1000_Block_size; i++ ) if ( Block.cData[i] != 0x55 ) printf ( " %d %x\n", i, Block.cData[i] ); // This section writes and verifys only 2 bytes to each block printf ( "\n\nWrite 2 bytes to each block\n\r" ); Tstart = MS_TIMER; for ( block = 0; block < SF1000_Nbr_of_Blocks; block++ ) { if ( block%128 == 0 ) printf ( "block %d\r", block ); FlashAddr = (long)block * SF1000_Block_size; Value.ival = block*2; while ( SF1000Write ( FlashAddr, Value.cval, 2 ) == -3 ); } Telap = MS_TIMER - Tstart; Tblock = (float)Telap/(float)SF1000_Nbr_of_Blocks; printf ( "\n\relapsed time = %ldms, time per block = %fms", Telap, Tblock ); printf ( "\n\rRead and verify the value from each block\n" ); Tstart = MS_TIMER; for ( block = 0; block < SF1000_Nbr_of_Blocks; block++ ) { if ( block%128 == 0 ) printf ( "\rblock %d", block ); FlashAddr = (long)block * SF1000_Block_size; SF1000Read ( FlashAddr, Value.cval, 2 ); if ( Value.ival != block*2 ) { printf ( " Error: written= %d read= %d\n\r", block, Value.ival ); } } Telap = MS_TIMER - Tstart; Tblock = (float)Telap/(float)SF1000_Nbr_of_Blocks; printf ( "\n\relapsed time = %ldms, time per block = %fms", Telap, Tblock ); printf ( "\n\r............Done Testing............\n" ); }<file_sep>struct PayloadType // data package sent to remotes { char device; char devType; // M for main station char command; // can be heartbeat, event, transaction char station; unsigned long timestamp; // MS_TIMER char mainArrival; char systemState; char remoteAlert; char transInProgress; char mainStation; char diverterStation; char subStaAddressing; char transFlags; char secureAckStation; int securePin; char transDirection; char purgeMode; char mainBusy; char headDivAlign; }; send_payload_to_remotes(); command.devAddr=ALL_DEVICES; command.command=RETURN_INPUTS; if (param.subStaAddressing) command.station=mainStation; else command.station=param.activeMain; // send the main arrival state to indicate not ready for transaction if (main_arrival || slave_arrival) Payload.mainArrival=arrival_from; else Payload.mainArrival=0; // send the system_state (for headdiverter controller to operate blower) command.data[1]=system_state; command.data[2]=outputvalue[devInUseSolid] & ~mainFlashAtSlave; // was system_direction; command.data[3]=(outputvalue[devInUseFlash] & ~SLAVE_b) | mainFlashAtSlave; command.data[4]=STATION_SET; This happens in Retrieve_Remote_Inputs for (k=0; k<5; k++) { tempData = response.data[k]; tempData &= response.station; // Turn off unused bits remote_data[k] |= (tempData & response.station); // ON Bits remote_data[k] &= ~(tempData ^ response.station); // OFF bits } // force unused doors closed (on) and other unused inputs off remote_data[REMOTE_DOOR] |= ~STATION_SET; remote_data[REMOTE_CIC] &= STATION_SET; remote_data[REMOTE_RTS] &= STATION_SET; remote_data[REMOTE_ARRIVE] &= STATION_SET; if (param.subStaAddressing && slaveAvailable) remote_data[REMOTE_RTS2] &= STATION_SET; else remote_data[REMOTE_RTS2] = 0; set_remote_diverters(systemStation); command.devAddr=ALL_DEVICES; command.command=SET_DIVERTER; command.station=systemStation; command.data[0]=transTypeInfo[transactionType][TT_FROM]; // For head diverter command.data[1]=mainStation; // For slave command.data[2]=param.subStaAddressing; command.data[3]=param.blowerType; //command.data[4]=0xFF; // to help ident main messages command.data[4]=translog.flags; received=send_command(command); if (received) new_state=WAIT_FOR_DIVERTERS; else new_state=CANCEL_STATE; FROM DIVERTER CONTROLLER void monitorUDPactivity(char deviceID) { // track the active stations to report when a station stops communicating // call with deviceID = 0 to refresh statistics #ifdef USE_TCPIP static int recentDevices[NUM_STATIONS+1]; static unsigned long refreshTimer; static int idx; #GLOBAL_INIT { for (idx=0; idx<=NUM_STATIONS; idx++) recentDevices[idx]=0; refreshTimer=0; activeStations=0; } // make sure this device is within range if (deviceID < 10) { // capture this device recentDevices[deviceID]++; } // update and report new statistic every 1 secon if (MS_TIMER - refreshTimer >1000) { // report the new statistic refreshTimer = MS_TIMER; activeStations = 0; for (idx=NUM_STATIONS; idx>0; idx--) // count down { activeStations = (activeStations << 1); // shift activeStations |= (recentDevices[idx]>0) ? 1 : 0; // include bit // clear the history buffer recentDevices[idx]=0; } } #endif }
bb3ea413c394b21f0ef23d287819016fe04c65b4
[ "C" ]
9
C
ms48083/PTS_Embedded
09aeeeff14126aa4c3e3fb0ec7b33a0ab35384bb
6b89cad5b7d880a38481e642883148224a2320ca
refs/heads/master
<file_sep>rule "FC071", "Missing LICENSE file" do tags %w{style license} cookbook do |path| ensure_file_exists(path, "LICENSE") end end
b45f6af0aef997493095d98895ee721b26c1cbc5
[ "Ruby" ]
1
Ruby
hartmantis/foodcritic
01f2773043ed3d78d9f4476c0cd80cfa1af318c4
3ff4407f9faa725047b3ca1ce7e66c3d8aeddbc7
refs/heads/master
<repo_name>eric-robinson/couchbase-lite-ios<file_sep>/Swift/Log.swift // // Log.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Log allows to configure console and file logger or to set a custom logger. public class Log { /// Console logger writing log messages to the system console. public let console = ConsoleLogger() /// File logger writing log messages to files. public let file = FileLogger() /// For setting a custom logger. public var custom: Logger? { didSet { CBLDatabase.log().custom = custom != nil ? CustomLoggerBridge(logger: custom!) : nil } } // MARK: Internal init() { } // For Unit Tests static func log(domain: LogDomain, level: LogLevel, message: String) { let cDomain = CBLLogDomain.init(rawValue: UInt(domain.rawValue)) let cLevel = CBLLogLevel(rawValue: UInt(level.rawValue))! CBLDatabase.log().log(to: cDomain, level: cLevel, message: message) } } /// Briging between Swift and Objective-C custom logger class CustomLoggerBridge: NSObject, CBLLogger { let logger: Logger init(logger: Logger) { self.logger = logger } // MARK: CBLLogger var level: CBLLogLevel { return CBLLogLevel(rawValue: UInt(logger.level.rawValue))! } func log(with level: CBLLogLevel, domain: CBLLogDomain, message: String) { let l = LogLevel(rawValue: UInt8(level.rawValue))! let d = LogDomain(rawValue: UInt8(domain.rawValue))! logger.log(level: l, domain: d, message: message) } } <file_sep>/Swift/FileLogger.swift // // FileLogger.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// File logger used for writing log messages to files. The binary file format will /// be used by default. To change the file format to plain text, set the usePlainText /// property to true. public class FileLogger { private static let defaultMaxSize = UInt64(500 * 1024) /// The minimum log level of the log messages to be logged. The default log level for /// file logger is warning. public var level: LogLevel = .info { didSet { CBLDatabase.log().file.level = CBLLogLevel(rawValue: UInt(level.rawValue))! } } /// The directory to store the log files. public var directory: String = CBLDatabase.log().file.directory { didSet { CBLDatabase.log().file.directory = directory } } /// To use plain text file format instead of the default binary format. public var usePlainText: Bool = false { didSet { CBLDatabase.log().file.usePlainText = usePlainText } } /// The maximum size of a log file before being rotation. The default is 1024 bytes. public var maxSize: UInt64 = defaultMaxSize { didSet { CBLDatabase.log().file.maxSize = maxSize } } /// The maximum number of rotated log files to keep. The default is 1 which means no rotation. public var maxRotateCount: Int = 1 { didSet(value) { CBLDatabase.log().file.maxRotateCount = value } } init() { } } <file_sep>/Swift/Prediction.swift // // Prediction.swift // CouchbaseLite // // Copyright (c) 2018 Couchbase, Inc. All rights reserved. // // Licensed under the Couchbase License Agreement (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf // // 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. // import Foundation /// PredictiveModel protocol that allows to integrate machine learning model into /// CBL Query via invoking the Function.prediction() function. public protocol PredictiveModel { /// The prediction callback called when invoking the Function.prediction() function /// inside a query or an index. The input dictionary object's keys and values will be /// coresponding to the 'input' dictionary parameter of theFunction.prediction() function. /// /// If the prediction callback cannot return a result, the prediction callback /// should return null value, which will be evaluated as MISSING. /// /// - Parameter input: The input dictionary. /// - Returns: The output dictionary. func prediction(input: DictionaryObject) -> DictionaryObject? } /// Predictive model manager class for registering and unregistering predictive models. public class Prediction { /// Register a predictive model by the given name. /// /// - Parameters: /// - model: The predictive model. /// - name: The name of the predictive model. public func registerModel(_ model: PredictiveModel, withName name: String) { CBLDatabase.prediction().register(PredictiveModelBridge(model: model), withName: name) } /// Unregister a predictive model of the given name. /// /// - Parameter name: The name of the predictive model. public func unregisterModel(withName name: String) { CBLDatabase.prediction().unregisterModel(withName: name) } } /// An internal class that bridges between Swift and Objective-C predictive model. class PredictiveModelBridge: NSObject, CBLPredictiveModel { let model: PredictiveModel init(model: PredictiveModel) { self.model = model } func prediction(_ input: CBLDictionary) -> CBLDictionary? { let inDict = DataConverter.convertGETValue(input) as! DictionaryObject return DataConverter.convertSETValue(model.prediction(input: inDict)) as? CBLDictionary } } <file_sep>/Swift/ConsoleLogger.swift // // ConsoleLogger.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Console logger for writing log messages to the system console. public class ConsoleLogger { /// The minimum log level of the log messages to be logged. The default log level for /// console logger is warning. public var level: LogLevel = .warning { didSet { CBLDatabase.log().console.level = CBLLogLevel(rawValue: UInt(level.rawValue))! } } /// The set of log domains of the log messages to be logged. By default, the log /// messages of all domains will be logged. public var domains: Set<LogDomain> = [.all] { didSet { var domain: UInt8 = 0 for d in domains { domain = domain | d.rawValue } CBLDatabase.log().console.domains = CBLLogDomain(rawValue: UInt(domain)) } } // MARK: Internal init() { } } <file_sep>/Swift/Tests/LogTest.swift // // LogTest.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import CouchbaseLiteSwift class LogTest: CBLTestCase { var backup: FileLoggerBackup? override func tearDown() { super.tearDown() if let backup = self.backup { Database.log.file.level = backup.level Database.log.file.directory = backup.directory Database.log.file.maxSize = backup.maxSize Database.log.file.maxRotateCount = backup.maxRotateCount Database.log.file.usePlainText = backup.usePlainText self.backup = nil } } func backupFileLogger() { backup = FileLoggerBackup(level: Database.log.file.level, directory: Database.log.file.directory, usePlainText: Database.log.file.usePlainText, maxSize: Database.log.file.maxSize, maxRotateCount: Database.log.file.maxRotateCount) } func testCustomLoggingLevels() throws { Log.log(domain: .database, level: .info, message: "IGNORE") let customLogger = LogTestLogger() Database.log.custom = customLogger for i in (1...5).reversed() { customLogger.reset() customLogger.level = LogLevel(rawValue: UInt8(i))! Database.log.custom = customLogger Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE") Log.log(domain: .database, level: .info, message: "TEST INFO") Log.log(domain: .database, level: .warning, message: "TEST WARNING") Log.log(domain: .database, level: .error, message: "TEST ERROR") XCTAssertEqual(customLogger.lines.count, 5 - i) } Database.log.custom = nil } func testPlainTextLoggingLevels() throws { backupFileLogger() let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("LogTestLogs") try? FileManager.default.removeItem(atPath: path) Database.log.file.directory = path Database.log.file.usePlainText = true Database.log.file.maxRotateCount = 0 for i in (1...5).reversed() { Database.log.file.level = LogLevel(rawValue: UInt8(i))! Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE") Log.log(domain: .database, level: .info, message: "TEST INFO") Log.log(domain: .database, level: .warning, message: "TEST WARNING") Log.log(domain: .database, level: .error, message: "TEST ERROR") } let files = try FileManager.default.contentsOfDirectory(atPath: path) for file in files { let log = (path as NSString).appendingPathComponent(file) let content = try NSString(contentsOfFile: log, encoding: String.Encoding.utf8.rawValue) var lineCount = 0 content.enumerateLines { (line, stop) in lineCount = lineCount + 1 } let sfile = file as NSString if sfile.range(of: "verbose").location != NSNotFound { XCTAssertEqual(lineCount, 2) } else if sfile.range(of: "info").location != NSNotFound { XCTAssertEqual(lineCount, 3) } else if sfile.range(of: "warning").location != NSNotFound { XCTAssertEqual(lineCount, 4) } else if sfile.range(of: "error").location != NSNotFound { XCTAssertEqual(lineCount, 5) } } } } class LogTestLogger: Logger { var lines: [String] = [] var level: LogLevel = .none func reset() { lines.removeAll() } func log(level: LogLevel, domain: LogDomain, message: String) { lines.append(message) } } struct FileLoggerBackup { var level: LogLevel var directory: String var usePlainText: Bool var maxSize: UInt64 var maxRotateCount: Int } <file_sep>/Swift/Tests/PredictiveQueryTest.swift // // PredictiveQueryTest.swift // CouchbaseLite // // Copyright (c) 2018 Couchbase, Inc. All rights reserved. // // Licensed under the Couchbase License Agreement (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf // // 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. // import XCTest import CouchbaseLiteSwift class PredictiveQueryTest: CBLTestCase { override func setUp() { super.setUp() Database.prediction.unregisterModel(withName: AggregateModel.name) Database.prediction.unregisterModel(withName: TextModel.name) } @discardableResult func createDocument(withNumbers numbers: [Int]) -> MutableDocument { let doc = MutableDocument() doc.setValue(numbers, forKey: "numbers") try! db.saveDocument(doc) return doc } func testRegisterUnregisterModel() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let q = QueryBuilder .select(SelectResult.property("numbers"), SelectResult.expression(prediction)) .from(DataSource.database(db)) // Query before registering the model: expectError(domain: "CouchbaseLite.SQLite", code: 1) { _ = try q.execute() } let aggregateModel = AggregateModel() aggregateModel.registerModel() let rows = try verifyQuery(q) { (n, r) in let numbers = r.array(at: 0)!.toArray() as NSArray XCTAssert(numbers.count > 0) let pred = r.dictionary(at: 1)! XCTAssertEqual(pred.int(forKey: "sum"), numbers.value(forKeyPath: "@sum.self") as! Int) XCTAssertEqual(pred.int(forKey: "min"), numbers.value(forKeyPath: "@min.self") as! Int) XCTAssertEqual(pred.int(forKey: "max"), numbers.value(forKeyPath: "@max.self") as! Int) XCTAssertEqual(pred.int(forKey: "avg"), numbers.value(forKeyPath: "@avg.self") as! Int) } XCTAssertEqual(rows, 2); aggregateModel.unregisterModel() // Query after unregistering the model: expectError(domain: "CouchbaseLite.SQLite", code: 1) { _ = try q.execute() } } func testQueryDictionaryResult() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let aggregateModel = AggregateModel() aggregateModel.registerModel() let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let q = QueryBuilder .select(SelectResult.property("numbers"), SelectResult.expression(prediction)) .from(DataSource.database(db)) let rows = try verifyQuery(q) { (n, r) in let numbers = r.array(at: 0)!.toArray() as NSArray XCTAssert(numbers.count > 0) let pred = r.dictionary(at: 1)! XCTAssertEqual(pred.int(forKey: "sum"), numbers.value(forKeyPath: "@sum.self") as! Int) XCTAssertEqual(pred.int(forKey: "min"), numbers.value(forKeyPath: "@min.self") as! Int) XCTAssertEqual(pred.int(forKey: "max"), numbers.value(forKeyPath: "@max.self") as! Int) XCTAssertEqual(pred.int(forKey: "avg"), numbers.value(forKeyPath: "@avg.self") as! Int) } XCTAssertEqual(rows, 2); } func testQueryValueFromDictionaryResult() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let aggregateModel = AggregateModel() aggregateModel.registerModel() let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let q = QueryBuilder .select(SelectResult.property("numbers"), SelectResult.expression(prediction.property("sum")).as("sum")) .from(DataSource.database(db)) let rows = try verifyQuery(q) { (n, r) in let numbers = r.array(at: 0)!.toArray() as NSArray XCTAssert(numbers.count > 0) let sum = r.int(at: 1) XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int) } XCTAssertEqual(rows, 2); aggregateModel.unregisterModel() } func testQueryWithBlobProperty() throws { let texts = [ "Knox on fox in socks in box. Socks on Knox and Knox in box.", "Clocks on fox tick. Clocks on Knox tock. Six sick bricks tick. Six sick chicks tock." ] for text in texts { let doc = MutableDocument() doc.setBlob(blobForString(text), forKey: "text") try db.saveDocument(doc) } let textModel = TextModel() textModel.registerModel() let model = TextModel.name let input = Expression.dictionary(["text" : ["BLOB", ".text"]]) let prediction = Function.prediction(model: model, input: input) let q = QueryBuilder .select(SelectResult.property("text"), SelectResult.expression(prediction.property("wc")).as("wc")) .from(DataSource.database(db)) .where(prediction.property("wc").greaterThan(Expression.value(15))) let rows = try verifyQuery(q) { (n, r) in let blob = r.blob(forKey: "text")! let text = String(bytes: blob.content!, encoding: .utf8)! XCTAssertEqual(text, texts[1]) XCTAssertEqual(r.int(forKey: "wc"), 16) } XCTAssertEqual(rows, 1); textModel.unregisterModel() } func testQueryWithBlobParameter() throws { try db.saveDocument(MutableDocument()) let textModel = TextModel() textModel.registerModel() let model = TextModel.name let input = Expression.dictionary(["text" : Expression.parameter("text")]) let prediction = Function.prediction(model: model, input: input) let q = QueryBuilder .select(SelectResult.expression(prediction.property("wc")).as("wc")) .from(DataSource.database(db)) let params = Parameters() params.setBlob(blobForString("Knox on fox in socks in box. Socks on Knox and Knox in box."), forName: "text") q.parameters = params let rows = try verifyQuery(q) { (n, r) in XCTAssertEqual(r.int(at: 0), 14) } XCTAssertEqual(rows, 1); textModel.unregisterModel() } func testIndexPredictionValue() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let aggregateModel = AggregateModel() aggregateModel.registerModel() let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum"))) try db.createIndex(index, withName: "SumIndex") let q = QueryBuilder .select(SelectResult.property("numbers"), SelectResult.expression(prediction.property("sum")).as("sum")) .from(DataSource.database(db)) .where(prediction.property("sum").equalTo(Expression.value(15))) let explain = try q.explain() as NSString XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound) let rows = try verifyQuery(q) { (n, r) in let numbers = r.array(at: 0)!.toArray() as NSArray XCTAssert(numbers.count > 0) let sum = r.int(at: 1) XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int) } XCTAssertEqual(rows, 1); XCTAssertEqual(aggregateModel.numberOfCalls, 2); } func testIndexMultiplePredictionValues() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let aggregateModel = AggregateModel() aggregateModel.registerModel() let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let sumIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum"))) try db.createIndex(sumIndex, withName: "SumIndex") let avgIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("avg"))) try db.createIndex(avgIndex, withName: "AvgIndex") let q = QueryBuilder .select(SelectResult.expression(prediction.property("sum")).as("sum"), SelectResult.expression(prediction.property("avg")).as("avg")) .from(DataSource.database(db)) .where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or( prediction.property("avg").equalTo(Expression.value(8)))) let explain = try q.explain() as NSString XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound) XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound) let rows = try verifyQuery(q) { (n, r) in XCTAssert(r.int(at: 0) == 15 || r.int(at: 1) == 8) } XCTAssertEqual(rows, 2); } func testIndexCompoundPredictiveValues() throws { createDocument(withNumbers: [1, 2, 3, 4, 5]) createDocument(withNumbers: [6, 7, 8, 9, 10]) let aggregateModel = AggregateModel() aggregateModel.registerModel() let model = AggregateModel.name let input = Expression.value(["numbers": Expression.property("numbers")]) let prediction = Function.prediction(model: model, input: input) let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")), ValueIndexItem.expression(prediction.property("avg"))) try db.createIndex(index, withName: "SumAvgIndex") let q = QueryBuilder .select(SelectResult.expression(prediction.property("sum")).as("sum"), SelectResult.expression(prediction.property("avg")).as("avg")) .from(DataSource.database(db)) .where(prediction.property("sum").equalTo(Expression.value(15)).and( prediction.property("avg").equalTo(Expression.value(3)))) let explain = try q.explain() as NSString XCTAssertNotEqual(explain.range(of: "USING INDEX SumAvgIndex").location, NSNotFound) let rows = try verifyQuery(q) { (n, r) in XCTAssertEqual(r.int(at: 0), 15) XCTAssertEqual(r.int(at: 1), 3) } XCTAssertEqual(rows, 1); XCTAssertEqual(aggregateModel.numberOfCalls, 4); } func testEuclidientDistance() throws { let tests: [[Any]] = [ [[10, 10], [13, 14], 5], [[1,2, 3], [1, 2, 3], 0], [[], [], 0], [[1, 2], [1, 2, 3], NSNull()], [[1, 2], "foo", NSNull()] ] for test in tests { let doc = MutableDocument() doc.setValue(test[0], forKey: "v1") doc.setValue(test[1], forKey: "v2") doc.setValue(test[2], forKey: "distance") try db.saveDocument(doc) } let distance = Function.euclideanDistance(between: Expression.property("v1"), and: Expression.property("v2")) let q = QueryBuilder .select(SelectResult.expression(distance), SelectResult.property("distance")) .from(DataSource.database(db)) let rows = try verifyQuery(q) { (n, r) in XCTAssertEqual(r.int(at: 0), r.int(at: 1)) } XCTAssertEqual(Int(rows), tests.count); } func testSquaredEuclidientDistance() throws { let tests: [[Any]] = [ [[10, 10], [13, 14], 25], [[1,2, 3], [1, 2, 3], 0], [[], [], 0], [[1, 2], [1, 2, 3], NSNull()], [[1, 2], "foo", NSNull()] ] for test in tests { let doc = MutableDocument() doc.setValue(test[0], forKey: "v1") doc.setValue(test[1], forKey: "v2") doc.setValue(test[2], forKey: "distance") try db.saveDocument(doc) } let distance = Function.squaredEuclideanDistance(between: Expression.property("v1"), and: Expression.property("v2")) let q = QueryBuilder .select(SelectResult.expression(distance), SelectResult.property("distance")) .from(DataSource.database(db)) let rows = try verifyQuery(q) { (n, r) in if r.value(at: 1) == nil { XCTAssertNil(r.value(at: 0)) } else { XCTAssertEqual(r.double(at: 0), r.double(at: 1)) } } XCTAssertEqual(Int(rows), tests.count); } func testCosineDistance() throws { let tests: [[Any]] = [ [[10, 0], [0, 99], 1.0], [[1, 2, 3], [1, 2, 3], 0.0], [[1, 0, -1], [-1, -1, 0], 1.5], [[], [], NSNull()], [[1, 2], [1, 2, 3], NSNull()], [[1, 2], "foo", NSNull()] ] for test in tests { let doc = MutableDocument() doc.setValue(test[0], forKey: "v1") doc.setValue(test[1], forKey: "v2") doc.setValue(test[2], forKey: "distance") try db.saveDocument(doc) } let distance = Function.cosineDistance(between: Expression.property("v1"), and: Expression.property("v2")) let q = QueryBuilder .select(SelectResult.expression(distance), SelectResult.property("distance")) .from(DataSource.database(db)) let rows = try verifyQuery(q) { (n, r) in if r.value(at: 1) == nil { XCTAssertNil(r.value(at: 0)) } else { XCTAssertEqual(r.double(at: 0), r.double(at: 1)) } } XCTAssertEqual(Int(rows), tests.count); } } // MARK: Models class TestPredictiveModel: PredictiveModel { class var name: String { return "Untitled" } var numberOfCalls = 0 func prediction(input: DictionaryObject) -> DictionaryObject? { numberOfCalls = numberOfCalls + 1 return self.predict(input: input) } func predict(input: DictionaryObject) -> DictionaryObject? { return nil } func registerModel() { Database.prediction.registerModel(self, withName: type(of: self).name) } func unregisterModel() { Database.prediction.unregisterModel(withName: type(of: self).name) } func reset() { numberOfCalls = 0 } } class AggregateModel: TestPredictiveModel { override class var name: String { return "AggregateModel" } override func predict(input: DictionaryObject) -> DictionaryObject? { guard let numbers = input.array(forKey: "numbers")?.toArray() as NSArray? else { NSLog("WARNING: numbers is nil") return nil } let output = MutableDictionaryObject() output.setValue(numbers.value(forKeyPath: "@sum.self"), forKey: "sum") output.setValue(numbers.value(forKeyPath: "@min.self"), forKey: "min") output.setValue(numbers.value(forKeyPath: "@max.self"), forKey: "max") output.setValue(numbers.value(forKeyPath: "@avg.self"), forKey: "avg") return output } } class TextModel: TestPredictiveModel { override class var name: String { return "TextModel" } override func predict(input: DictionaryObject) -> DictionaryObject? { guard let blob = input.blob(forKey: "text") else { NSLog("WARNING: text is nil") return nil } let text = String(bytes: blob.content!, encoding: .utf8)! as NSString var wc = 0 var sc = 0 var curSentLoc = NSNotFound text.enumerateLinguisticTags(in: NSRange(location: 0, length: text.length), scheme: NSLinguisticTagSchemeTokenType, options: [], orthography: nil) { (tag, token, sent, stop) in if tag == NSLinguisticTagWord { wc = wc + 1 } if sent.location != NSNotFound && curSentLoc != sent.location { curSentLoc = sent.location sc = sc + 1 } } let output = MutableDictionaryObject() output.setInt(wc, forKey: "wc") output.setInt(sc, forKey: "sc") return output } }
db715a1b781a698cfeec9aca4384a98d5c809dc4
[ "Swift" ]
6
Swift
eric-robinson/couchbase-lite-ios
4ae48b9d3e79283f560c8fa60892d658e6fc5227
bd50bb792de9fb9063da4648d904f6e9e6407795
refs/heads/master
<file_sep>test-plugin ============ VmWare Tab plugin prototype Prerequisites: ------------- <pre> apt-get install nodejs npm npm install -g grunt pip install fuel-plugin-builder</pre> Build: ----- 1. Clone plugin source code from GitHub<br/> <pre> git clone https://github.com/AlgoTrader/test-plugin.git</pre> 2. Clone Fuel-Web source code from GitHub<br/> <pre>git clone https://github.com/stackforge/fuel-web.git cd ./fuel-web git fetch https://review.openstack.org/stackforge/fuel-web refs/changes/00/112600/24 && git checkout FETCH_HEAD cd ..</pre> 3. Copy UI part of plugin from test-plugin to fuel-web:<br> <pre> mkdir -p ./fuel-web/nailgun/static/plugins/test-plugin cp -R ./test-plugin/ui/* ./fuel-web/nailgun/static/plugins/test-plugin</pre> 4. Build the fuel-web UI part<br> <pre> cd ./fuel-web/nailgun npm install && npm update grunt build --static-dir=static_compressed cd ../..</pre> 5. Copy plugin ui build results back to ./test-plugin <pre> rm -rf ./test-plugin/ui mkdir ./test-plugin/ui cp -R ./fuel-web/nailgun/static_compressed/plugins/test-plugin/* ./test-plugin/ui</pre> 6. Use Fuel Plugin Builder to build the plugin <pre> cd ./test-plugin fpb --build ./</pre> In current directory, there should be file **test-plugin-1.0.0.fp** created Install ------- <pre>fuel plugins --install test-plugin-1.0.0.fp --force</pre> <file_sep>/* * Copyright 2014 Mirantis, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ define( [ 'react', 'jsx!component_mixins' ], function (React, componentMixins) { 'use strict'; return React.createClass({ renderBody: function () { return ( <div style={{padding:'6px'}}> <h1>Boo plugin is there</h1> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laboru </div> </div> ); }, render: function() { return this.renderBody(); } }); });
92f6554c42134337558079d380cb351ffc8c5681
[ "Markdown", "JavaScript" ]
2
Markdown
AlgoTrader/test-plugin
a227d66f6a32bf1b06cdb6e378a975994bd4fe07
3da4d9df3f1bd102fdc800d0028dd14c4f9d9b62
refs/heads/master
<repo_name>djanluka/matf-hackathon<file_sep>/backend/src/classes/socket.js class Socket { constructor(server) { this.io = require('socket.io')(server) this.io.on('connection', socket => { console.log('Heey connection'); socket.on('startModel', () => { console.log('startModel') const CO = "0.47" const program = "/home/boris/matf-hackathon/backend/pollution/load_model.py" + " CO"; var child = require('child_process').exec(program) const exec = require("child_process").execSync; var resultCO = exec(program); console.log(resultCO) }) }) } } module.exports = Socket;
7b0a9aa344f2b07e4f70e8d5b96ac0fe2e222229
[ "JavaScript" ]
1
JavaScript
djanluka/matf-hackathon
2aeb2fc318d5b06e0ad09d6f442ecfd89a102486
3d8ecbd2b4ad3b6e0a2fed3638936aef09a4cc39
refs/heads/master
<repo_name>le-hu-dev/react-demo<file_sep>/src/components/SignOut/index.js import React from 'react'; import { withFirebase } from '../Firebase'; const SignOutButton = ({ firebase }) => ( <button class="btn btn-md-custom btn-outline-warning my-2 my-sm-0" type="button" onClick={firebase.doSignOut}>Sign Out</button> ); export default withFirebase(SignOutButton);<file_sep>/src/components/Account/index.js import React, { Component } from 'react'; import { compose } from 'recompose'; import { Link } from 'react-router-dom'; import { AuthUserContext, withAuthorization, withEmailVerification, } from '../Session'; import { withFirebase } from '../Firebase'; import PasswordChangeForm from '../PasswordChange'; const SIGN_IN_METHODS = [ { id: 'password', provider: null, }, { id: 'google.com', provider: 'googleProvider', }, { id: 'facebook.com', provider: 'facebookProvider', }, { id: 'twitter.com', provider: 'twitterProvider', }, ]; const AccountPage = () => ( <div class="container"> <div class="row top-to-header"> <AuthUserContext.Consumer> {authUser => ( <div class="col-sm-10 col-md-8 col-lg-6 mx-auto"> <h3>Account: {authUser.email}</h3> <PasswordChangeForm /> <LoginManagement authUser={authUser} /> </div> )} </AuthUserContext.Consumer> </div> </div> ); class LoginManagementBase extends Component { constructor(props) { super(props); this.state = { activeSignInMethods: [], error: null, }; } componentDidMount() { this.fetchSignInMethods(); } fetchSignInMethods = () => { this.props.firebase.auth .fetchSignInMethodsForEmail(this.props.authUser.email) .then(activeSignInMethods => this.setState({ activeSignInMethods, error: null }),) .catch(error => this.setState({ error })); }; onSocialLoginLink = provider => { this.props.firebase.auth.currentUser .linkWithPopup(this.props.firebase[provider]) .then(this.fetchSignInMethods) .catch(error => this.setState({ error })); }; onDefaultLoginLink = password => { const credential = this.props.firebase.emailAuthProvider.credential(this.props.authUser.email, password,); this.props.firebase.auth.currentUser .linkAndRetrieveDataWithCredential(credential) .then(this.fetchSignInMethods) .catch(error => this.setState({ error })); }; onUnlink = providerId => { this.props.firebase.auth.currentUser .unlink(providerId) .then(this.fetchSignInMethods) .catch(error => this.setState({ error })); }; render() { const { activeSignInMethods, error } = this.state; return ( <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Sign In Methods</h5> {error && <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong>Error!</strong> {error.message} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>} <div class="list-group"> {SIGN_IN_METHODS.map(signInMethod => { const onlyOneLeft = activeSignInMethods.length === 1; const isEnabled = activeSignInMethods.includes(signInMethod.id,); return ( <Link to="#" className="list-group-item list-group-item-action" key={signInMethod.id}> {signInMethod.id === 'password' ? ( <DefaultLoginToggle onlyOneLeft={onlyOneLeft} isEnabled={isEnabled} signInMethod={signInMethod} onLink={this.onDefaultLoginLink} onUnlink={this.onUnlink} /> ) : ( <SocialLoginToggle onlyOneLeft={onlyOneLeft} isEnabled={isEnabled} signInMethod={signInMethod} onLink={this.onSocialLoginLink} onUnlink={this.onUnlink} /> )} </Link> ); })} </div> </div> </div> ); } } const SocialLoginToggle = ({ onlyOneLeft, isEnabled, signInMethod, onLink, onUnlink, }) => isEnabled ? ( <button type="button" class="btn btn-md-custom btn-outline-primary btn-block text-uppercase" onClick={() => onUnlink(signInMethod.id)} disabled={onlyOneLeft}> Deactivate {signInMethod.id} </button> ) : ( <button type="button" class="btn btn-md-custom btn-outline-primary btn-block text-uppercase" onClick={() => onLink(signInMethod.provider)}> Link {signInMethod.id} </button> ); class DefaultLoginToggle extends Component { constructor(props) { super(props); this.state = { password: '', confirmedPassword: '' }; } onSubmit = event => { event.preventDefault(); this.props.onLink(this.state.password); this.setState({ password: '', confirmedPassword: '' }); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; render() { const { onlyOneLeft, isEnabled, signInMethod, onUnlink, } = this.props; const { password, confirmedPassword } = this.state; const isInvalid = password !== confirmedPassword || password === ''; return isEnabled ? ( <button type="button" class="btn btn-md-custom btn-outline-primary btn-block text-uppercase" onClick={() => onUnlink(signInMethod.id)} disabled={onlyOneLeft}> Deactivate {signInMethod.id} </button> ) : ( <div class="card card-signin my-5"> <div class="card-body"> <form class="form-signin" onSubmit={this.onSubmit}> <div class="form-label-group"> <input type="password" id="inputPassword" name="password" value={password} onChange={this.onChange} class="form-control" placeholder="New Password" required /> <label for="inputPassword">New Password</label> </div> <div class="form-label-group"> <input type="password" id="inputConfirmedPassword" name="confirmedPassword" value={confirmedPassword} onChange={this.onChange} class="form-control" placeholder="Confirm New Password" required /> <label for="inputConfirmedPassword">Confirm New Password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" disabled={isInvalid} type="submit"> Link {signInMethod.id} </button> </form> </div> </div> ); } } const LoginManagement = withFirebase(LoginManagementBase); const condition = authUser => !!authUser; export default compose( withEmailVerification, withAuthorization(condition), )(AccountPage);<file_sep>/src/components/Todo/index.js import React from "react" import { compose } from "recompose" import { withAuthorization, withEmailVerification } from "../Session" import { withFirebase } from "../Firebase" import Todo from "./Todo" const TodoPage = () => ( <div className="container"> <div className="row top-to-header"> <div className="col-sm-11 col-md-11 col-lg-10 mx-auto"> <h1>My Todo List</h1> <Todo /> </div> </div> </div> ) const condition = authUser => !!authUser export default compose( withFirebase, withEmailVerification, withAuthorization(condition) )(TodoPage) <file_sep>/src/components/Todo/TodoItem.js import React, { Component } from "react" class TodoItem extends Component { constructor(props) { super(props) this.state = { editMode: false, editText: this.props.todo.text } } onToggleEditMode = () => { this.setState(state => ({ editMode: !state.editMode, editText: this.props.todo.text })) } onChangeEditText = event => { this.setState({ editText: event.target.value }) } onSaveEditText = () => { this.props.onEditTodo(this.props.todo, this.state.editText) this.setState({ editMode: false }) } render() { const { todo, onRemoveTodo, onCheckTodo } = this.props const { editMode, editText } = this.state const isDone = todo.completed ? "done" : "undone" return ( <li class="list-group-item d-flex justify-content-between align-items-center"> {editMode ? ( <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-pen-square"></i></span> </div> <input type="text" class="form-control text-md" placeholder="Enter your Todo item" value={editText} onChange={this.onChangeEditText} /> <div class="input-group-append"> <button type="button" class="btn-sm btn-outline-primary ml-1" onClick={this.onSaveEditText}><i class="fas fa-save"></i> </button> <button type="button" class="btn-sm btn-outline-primary ml-1" onClick={this.onToggleEditMode}><i class="fas fa-undo-alt"></i> </button> </div> </div> ) : ( <div> <label className={isDone}> <input type="checkbox" className="mr-2" onChange={() => onCheckTodo(todo)} checked={todo.completed} /> {todo.text} {todo.editedAt && <span>(Edited)</span>} </label> </div> )} {!editMode && ( <div> <button type="button" class="btn-sm btn-outline-primary ml-1 my-sm-0" onClick={this.onToggleEditMode}><i class="fas fa-pen-square"></i> </button> <button type="button" class="btn-sm btn-outline-danger ml-1 my-sm-0" onClick={() => onRemoveTodo(todo.uid)}><i class="fas fa-minus-square"></i> </button> </div> )} </li> ) } } export default TodoItem <file_sep>/src/components/PasswordChange/index.js import React, { Component } from 'react'; import { withFirebase } from '../Firebase'; const INITIAL_STATE = { password: '', confirmedPassword: '', success: null, error: null, }; class PasswordChangeForm extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } onSubmit = event => { const { password } = this.state; this.props.firebase.doPasswordUpdate(password) .then((success) => { this.setState({ success }); this.setState({ ...INITIAL_STATE }); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); } render() { const { password, confirmedPassword, success, error } = this.state; const isInvalid = password !== confirmedPassword || password === ''; return ( <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Change Password</h5> {success && <div class="alert alert-success alert-dismissible fade show" role="alert"> <strong>Success!</strong> Your password is updated. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>} {error && <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong>Error!</strong> {error.message} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div>} <form class="form-signin" onSubmit={this.onSubmit}> <div class="form-label-group"> <input type="password" id="inputPassword" name="password" value={password} onChange={this.onChange} class="form-control" placeholder="New Password" required /> <label for="inputPassword">New Password</label> </div> <div class="form-label-group"> <input type="password" id="inputConfirmedPassword" name="confirmedPassword" value={confirmedPassword} onChange={this.onChange} class="form-control" placeholder="Confirm New Password" required /> <label for="inputConfirmedPassword">Confirm New Password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" disabled={isInvalid} type="submit"><i class="fas fa-key"></i> Update My Password</button> </form> </div> </div> ) } } export default withFirebase(PasswordChangeForm);<file_sep>/src/components/Navigation/index.js import React from "react"; import { Link } from "react-router-dom"; import { AuthUserContext } from "../Session"; import SignOutButton from "../SignOut"; import * as ROUTES from "../../constants/routes"; import * as ROLES from "../../constants/roles"; const Navigation = () => ( <header> <nav className="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <Link className="navbar-brand" to={ROUTES.LANDING}> React Firebase </Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon" /> </button> <AuthUserContext.Consumer> {authUser => authUser ? ( <NavigationAuth authUser={authUser} /> ) : ( <NavigationNonAuth /> ) } </AuthUserContext.Consumer> </nav> </header> ); const NavigationAuth = ({ authUser }) => ( <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <Link className="nav-link" to={ROUTES.HOME}> Home </Link> </li> <li class="nav-item"> <Link className="nav-link" to={ROUTES.TODO}> Todo </Link> </li> <li class="nav-item"> <Link className="nav-link" to={ROUTES.SEARCH}> Search </Link> </li> <li class="nav-item"> <Link className="nav-link" to={ROUTES.ACCOUNT}> Account </Link> </li> {authUser.roles.includes(ROLES.ADMIN) && ( <li class="nav-item"> <Link className="nav-link" to={ROUTES.ADMIN}> Admin </Link> </li> )} </ul> <SignOutButton /> </div> ); const NavigationNonAuth = () => ( <div className="collapse navbar-collapse justify-content-end" id="navbarCollapse" > <div className="navbar-nav"> <Link className="nav-item btn btn-md-custom btn-outline-success my-2 my-sm-0" to={ROUTES.SIGN_IN} > Sign In </Link> </div> </div> ); export default Navigation; <file_sep>/src/components/Search/index.js import React from "react"; import Search from "./comp/Search"; const SearchPage = () => ( <div class="container"> <div class="row top-to-header"> <div class="col-sm-11 col-md-11 col-lg-10 mx-auto"> <h1>iTune Search</h1> <p>This Page will fetch data from iTunes Search API.</p> <Search name="Class" /> </div> </div> </div> ); export default SearchPage; <file_sep>/src/components/SignIn/index.js import React, { Component } from "react"; import { withRouter } from "react-router-dom"; import { compose } from "recompose"; import "./index.css"; import { SignUpLink } from "../SignUp"; import { PasswordForgotLink } from "../PasswordForgot"; import { withFirebase } from "../Firebase"; import * as ROUTES from "../../constants/routes"; const SignInPage = () => ( <div className="container"> <div className="row top-to-header"> <div className="col-sm-10 col-md-8 col-lg-6 mx-auto"> <SignInForm /> </div> </div> </div> ); const INITIAL_STATE = { email: "", password: "", error: null }; const ERROR_CODE_ACCOUNT_EXISTS = "auth/account-exists-with-different-credential"; const ERROR_MSG_ACCOUNT_EXISTS = ` An account with an email address to this social account already exists. Try to login from this account insteat and associate your social account on your personal account page. `; class SignInFormBase extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } onSubmit = event => { const { email, password } = this.state; this.props.firebase .doSignInWithEmailAndPassword(email, password) .then(() => { this.setState({ ...INITIAL_STATE }); this.props.history.push(ROUTES.HOME); }) .catch(error => { // this.setState({ ...INITIAL_STATE }); // this.props.history.push(ROUTES.HOME); // return; if (error.code === ERROR_CODE_ACCOUNT_EXISTS) { error.message = ERROR_MSG_ACCOUNT_EXISTS; } this.setState({ error }); }); event.preventDefault(); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; render() { const { email, password, error } = this.state; const isInvalid = password === "" || email === ""; return ( <div className="card card-signin my-5"> <div className="card-body"> <h5 className="card-title text-center">Sign In</h5> {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <div className="form-label-group"> <input type="email" id="inputEmail" name="email" value={email} onChange={this.onChange} className="form-control" placeholder="Email Address" required autoFocus /> <label htmlFor="inputEmail">Email address</label> </div> <div className="form-label-group"> <input type="password" id="inputPassword" name="password" value={password} onChange={this.onChange} className="form-control" placeholder="Password" required /> <label htmlFor="inputPassword">Password</label> </div> <div className="custom-control custom-checkbox mb-3"> <input type="checkbox" className="custom-control-input" id="checkRememberMe" /> <label className="custom-control-label" htmlFor="checkRememberMe"> Remember Me </label> </div> <button className="btn btn-lg btn-primary btn-block text-uppercase" disabled={isInvalid} type="submit" > <i className="fas fa-sign-in-alt" /> Sign in </button> <PasswordForgotLink /> <hr className="my-4" /> </form> </div> <SignInGoogle /> <SignInFacebook /> {/* <SignInTwitter /> */} <div className="card-body"> <SignUpLink /> </div> </div> ); } } class SignInCoogleBase extends Component { constructor(props) { super(props); this.state = { error: null }; } onSubmit = event => { this.props.firebase .doSignInWithGoogle() .then(socialAuthUser => { // Create a user in your Firebase Realtime Database too return this.props.firebase.user(socialAuthUser.user.uid).set({ username: socialAuthUser.user.displayName, email: socialAuthUser.user.email, roles: [] }); }) .then(() => { this.setState({ error: null }); this.props.history.push(ROUTES.HOME); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; render() { const { error } = this.state; return ( <div className="col-sm-11 col-md-11 col-lg-11 mx-auto"> {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <button className="btn btn-lg btn-google btn-block text-uppercase" type="submit" > <i className="fab fa-google mr-2" /> Sign in with Google </button> </form> </div> ); } } class SignInFacebookBase extends Component { constructor(props) { super(props); this.state = { error: null }; } onSubmit = event => { this.props.firebase .doSignInWithFacebook() .then(socialAuthUser => { // Create a user in your Firebase Realtime Database too return this.props.firebase.user(socialAuthUser.user.uid).set({ username: socialAuthUser.additionalUserInfo.profile.name, email: socialAuthUser.additionalUserInfo.profile.email, roles: [] }); }) .then(() => { this.setState({ error: null }); this.props.history.push(ROUTES.HOME); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; render() { const { error } = this.state; return ( <div className="col-sm-11 col-md-11 col-lg-11 mx-auto top-to-item"> {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <button className="btn btn-lg btn-facebook btn-block text-uppercase" type="submit" > <i className="fab fa-facebook-f mr-2" /> Sign in with Facebook </button> </form> </div> ); } } class SignInTwitterBase extends Component { constructor(props) { super(props); this.state = { error: null }; } onSubmit = event => { this.props.firebase .doSignInWithTwitter() .then(socialAuthUser => { // Create a user in your Firebase Realtime Database too return this.props.firebase.user(socialAuthUser.user.uid).set({ username: socialAuthUser.additionalUserInfo.profile.name, email: socialAuthUser.additionalUserInfo.profile.email, roles: [] }); }) .then(() => { this.setState({ error: null }); this.props.history.push(ROUTES.HOME); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; render() { const { error } = this.state; return ( <div className="col-sm-11 col-md-11 col-lg-11 mx-auto top-to-item"> {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <button className="btn btn-lg btn-twitter btn-block text-uppercase" type="submit" > <i className="fab fa-twitter-f mr-2" /> Sign in with Twitter </button> </form> </div> ); } } const SignInForm = compose( withRouter, withFirebase )(SignInFormBase); const SignInGoogle = compose( withRouter, withFirebase )(SignInCoogleBase); const SignInFacebook = compose( withRouter, withFirebase )(SignInFacebookBase); const SignInTwitter = compose( withRouter, withFirebase )(SignInTwitterBase); export default SignInPage; export { SignInForm, SignInGoogle, SignInFacebook, SignInTwitter }; <file_sep>/src/components/Landing/index.js import React from "react"; const LandingPage = () => ( <div className="container"> <div className="row top-to-header"> <div className="col-sm-11 col-md-11 col-lg-10 mx-auto"> <h1>Welcome to React + Firebase Tutorial</h1> <p>This Landing Page is accessible by every user.</p> </div> </div> </div> ); export default LandingPage; <file_sep>/src/components/Message/Messages.js import React, { Component } from 'react'; import { AuthUserContext } from '../Session'; import { withFirebase } from '../Firebase'; import MessageList from './MessageList'; class Messages extends Component { constructor(props) { super(props); this.state = { text: '', loading: false, messages: [], limit: 5, }; } componentDidMount() { this.onListenToMessages(); } onListenToMessages() { this.setState({ loading: true }); this.props.firebase.messages() .orderByChild('createdAt') .limitToLast(this.state.limit) .on('value', snapshot => { const messageObject = snapshot.val(); if (messageObject) { const messageList = Object.keys(messageObject).map(key => ({ ...messageObject[key], uid: key, })); this.setState({ messages: messageList, loading: false, }); } else { this.setState({ messages: null, loading: false }); } }); } componentWillUnmount() { this.props.firebase.messages().off(); } onChangeText = event => { this.setState({ text: event.target.value }); }; onCreateMessage = (event, authUser) => { this.props.firebase.messages().push({ text: this.state.text, userId: authUser.uid, createdAt: this.props.firebase.serverValue.TIMESTAMP, }); this.setState({ text: '' }); event.preventDefault(); } onEditMessage = (message, text) => { this.props.firebase.message(message.uid).set({ ...message, text, editedAt: this.props.firebase.serverValue.TIMESTAMP, }); }; onRemoveMessage = uid => { this.props.firebase.message(uid).remove(); }; onNextPage = () => { this.setState( state => ({ limit: state.limit + 5 }), this.onListenToMessages, ); }; render() { const { users } = this.props; const { text, messages, loading } = this.state; return ( <AuthUserContext.Consumer> {authUser => ( <div> {loading && <div>loading...</div>} {messages ? ( <MessageList messages={messages.map(message => ({ ...message, user: users ? users[message.userId] : { userId: message.userId }, }))} onEditMessage={this.onEditMessage} onRemoveMessage={this.onRemoveMessage} /> ) : ( <div class="alert alert-primary" role="alert">There are no messages ...</div> )} {!loading && messages && ( <div class="d-flex justify-content-end"> <button type="button" class="btn btn-outline-primary my-2 my-sm-0" onClick={this.onNextPage}><i class="fas fa-arrow-circle-down"></i> More</button> </div> )} <div class="top-to-item"> <form onSubmit={event => this.onCreateMessage(event, authUser)}> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-sms"></i></span> </div> <input type="text" class="form-control" placeholder="Enter your message" value={text} onChange={this.onChangeText} /> <div class="input-group-append"> <button type="submit" class="btn btn-outline-primary my-2 my-sm-0"><i class="fas fa-share-square"></i> Send</button> </div> </div> </form> </div> </div> )} </AuthUserContext.Consumer> ); } } export default withFirebase(Messages);<file_sep>/src/components/Search/comp/Search.js import React, { useState, useCallback, useRef, useEffect } from "react" import { data, itunesSearch } from "./data" import Form from "./Form" export default ({ name }) => ( <> Hello {name}! <br /> <BtnSelector initKey="ebook" /> {/*<div>{JSON.stringify(data.results[0])}</div>*/} </> ) const MediaType = { movie: "Movies", music: "Music", software: "Apps", ebook: "Books" } const prevSearches = {} const useState1 = initKey => { const [skey, setKey] = useState(initKey) const value = useState("") const datas = useState([]) const prevText = useRef("") let selSearches = prevSearches[skey] if (!selSearches) selSearches = prevSearches[skey] = { text: prevText.current, data: [] } useEffect( () => { if (selSearches.text) value[1](selSearches.text) }, [skey] ) // value[1](selSearches.text) const onSetKey = key => { prevText.current = selSearches.text // = value[0] setKey(key) } const onSearch = term => { selSearches.text = term itunesSearch(term, skey, data => { datas[1]((selSearches.data = data.results)) }) } // console.log(selSearches.text) return [skey, onSetKey, value, selSearches, onSearch, prevText] } const BtnSelector = ({ initKey = "movie" }) => { const [skey, setKey, value, selSearches, onSubmit, ref] = useState1(initKey) return ( <> {Object.entries(MediaType).map(([key, children]) => ( <button {...{ key, children, disabled: key == skey, onClick: () => setKey(key) }} /> ))} <br /> <br /> <Form onSubmit={onSubmit} value={value} ref={selSearches}> {/*selSearches.text*/} <button>Search</button> </Form> <hr /> {selSearches.data.map(item => ( <Item {...item} key={item.trackId || item.collectionId} /> ))} </> ) } const MediaButton = ({ media }) => { const [value, setValue] = useState({ text: "", data: [] }) } // const Btn = //https://material-ui.com/demos/selection-controls/ //https://github.com/azz/styled-css-grid import { Grid, Cell } from "styled-css-grid" const Item = ({ artworkUrl100, artistName, collectionName, trackName }) => ( <> <Grid columns={4} gap={"24"}> <div className="pic"> <img src={artworkUrl100} alt="" style={{ paddingRight: "1em" }} /> </div> <Cell width={3}> <div className="sel"> <button>Fav</button>{" "} </div> <div className="artist">{artistName}</div> <div className="track">{collectionName}</div> <div className="collection">{trackName}</div> </Cell> </Grid> <hr /> </> ) <file_sep>/src/components/Todo/Todo.js import React, { Component } from "react" import { AuthUserContext } from "../Session" import { withFirebase } from "../Firebase" import TodoList from "./TodoList" class Todo extends Component { constructor(props) { super(props) this.state = { text: "", loading: false, //data source todos: [] } } componentDidMount() { this.onListenToTodos() } onListenToTodos() { this.setState({ loading: true }) this.props.firebase .todos() .orderByChild("createdAt") .on("value", snapshot => { const todoObject = snapshot.val() if (todoObject) { const todoList = Object.keys(todoObject).map(key => ({ ...todoObject[key], uid: key })) this.setState({ todos: todoList, loading: false }) } else { this.setState({ todos: null, loading: false }) } }) } componentWillUnmount() { this.props.firebase.todos().off() } onChangeText = event => { this.setState({ text: event.target.value }) } onCreateTodo = (event, authUser) => { this.props.firebase.todos().push({ text: this.state.text, userId: authUser.uid, createdAt: this.props.firebase.serverValue.TIMESTAMP, // completed ? yse/no completed: false }) this.setState({ text: "" }) event.preventDefault() } // text = {"aasdfasdf"} onEditTodo = (todo, text) => { this.props.firebase.todo(todo.uid).set({ ...todo, text, editedAt: this.props.firebase.serverValue.TIMESTAMP }) } onRemoveTodo = uid => { this.props.firebase.todo(uid).remove() } onCheckTodo = todo => { //set style; this.props.firebase.todo(todo.uid).set({ ...todo, completed: !todo.completed, editedAt: this.props.firebase.serverValue.TIMESTAMP }) } // onNextPage = () => { // this.setState(state => ({ limit: state.limit + 5 }), this.onListenToTodos) // } render() { // const { users } = this.props const { text, todos, loading } = this.state return ( <AuthUserContext.Consumer> {authUser => ( <div> {loading && <div>loading...</div>} <label> {authUser.email} </label> {todos ? ( <div> <TodoList todos={todos.filter(todo => authUser.uid === todo.userId)} onEditTodo={this.onEditTodo} onRemoveTodo={this.onRemoveTodo} onCheckTodo={this.onCheckTodo} /> </div> ) : ( <div class="alert alert-primary" role="alert"> There are no todos ... </div> )} <div class="top-to-item"> <form onSubmit={event => this.onCreateTodo(event, authUser)}> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fas fa-list-alt" /> </span> </div> <input type="text" class="form-control" placeholder="Enter your Todo item" value={text} onChange={this.onChangeText} /> <div class="input-group-append"> <button type="submit" class="btn btn-outline-primary my-2 my-sm-0" > <i class="fas fa-share-square" /> Add </button> </div> </div> </form> </div> </div> )} </AuthUserContext.Consumer> ) } } export default withFirebase(Todo) <file_sep>/src/components/PasswordForgot/index.js import React, { Component } from "react"; import { Link } from "react-router-dom"; import { withFirebase } from "../Firebase"; import * as ROUTES from "../../constants/routes"; const PasswordForgotPage = () => ( <div className="container"> <div className="row top-to-header"> <div className="col-sm-10 col-md-8 col-lg-6 mx-auto"> <PasswordForgotForm /> </div> </div> </div> ); const INITIAL_STATE = { email: "", success: null, error: null }; class PasswordForgotFormBase extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } onSubmit = event => { const { email } = this.state; this.props.firebase .doPasswordReset(email) .then(success => { this.setState({ success }); this.setState({ ...INITIAL_STATE }); }) .catch(error => { this.setState({ error }); }); event.preventDefault(); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; render() { const { email, success, error } = this.state; const isInvalid = email === ""; return ( <div className="card card-signin my-5"> <div className="card-body"> <h5 className="card-title text-center">Forgot Password</h5> {success && ( <div className="alert alert-success alert-dismissible fade show" role="alert" > <strong>Success!</strong> Please check your email to reset your password. <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <div className="form-label-group"> <input type="email" id="inputEmail" name="email" value={this.state.email} onChange={this.onChange} className="form-control" placeholder="Email Address" required autofocus /> <label for="inputEmail">Email Address</label> </div> <button className="btn btn-lg btn-primary btn-block text-uppercase" disabled={isInvalid} type="submit" > <i className="fas fa-envelope" /> Reset My Password </button> </form> </div> </div> ); } } const PasswordForgotLink = () => ( <div className="d-flex justify-content-end top-to-item"> <Link className="card-link" to={ROUTES.PASSWORD_FORGOT}> Forgot Password? </Link> </div> ); const PasswordForgotForm = withFirebase(PasswordForgotFormBase); export default PasswordForgotPage; export { PasswordForgotForm, PasswordForgotLink }; <file_sep>/src/components/Todo/TodoList.js import React from "react" import TodoItem from "./TodoItem" const TodoList = ({ todos, onEditTodo, onRemoveTodo, onCheckTodo }) => ( <ul class="list-group top-to-header"> {todos.map(todo => ( <TodoItem key={todo.uid} todo={todo} onEditTodo={onEditTodo} onRemoveTodo={onRemoveTodo} onCheckTodo={onCheckTodo} /> ))} </ul> ) export default TodoList <file_sep>/src/components/Search/comp/Form.js import React, { useState } from "react"; const useInputValue = ([value, setValue]) => { // const [value, setValue] = useState(initialValue); // console.log(value+initialValue) return { value, onChange: e => setValue(e.target.value), resetValue: () => setValue("") }; }; export default ({ onSubmit, children, value, ref }) => { const { resetValue, ...text } = useInputValue(value); if(ref)ref.text=text.value return ( <form onSubmit={e => { e.preventDefault(); onSubmit(text.value); // resetValue(); }} > <input {...text} />{children} </form> ); }; <file_sep>/src/components/User/UserList.js import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { withFirebase } from '../Firebase'; import * as ROUTES from '../../constants/routes'; class UserList extends Component { constructor(props) { super(props); this.state = { loading: false, users: [], }; } componentDidMount() { this.setState({ loading: true }); this.props.firebase.users().on('value', snapshot => { const usersObject = snapshot.val(); const usersList = Object.keys(usersObject).map(key => ({ ...usersObject[key], uid: key, })); this.setState({ users: usersList, loading: false, }); }); } componentWillUnmount() { this.props.firebase.users().off(); } render() { const { users, loading } = this.state; return ( <div class="card card-signin my-5"> <div class="card-header bg-dark text-white"> Users </div> <div class="card-body"> {loading && <div>Loading...</div>} <table class="table table-hover"> <thead> <tr> <th>User ID</th> <th>Username</th> <th>Email</th> <th> </th> </tr> </thead> <tbody> {users.map(user => ( <tr key={user.uid}> <td>{user.uid}</td> <td>{user.username}</td> <td>{user.email}</td> <td> <Link className="btn-sm btn-primary my-2 my-sm-0" to={{ pathname: `${ROUTES.ADMIN}/${user.uid}`, state: { user }, }}><i class="fas fa-address-card"></i></Link> </td> </tr> ))} </tbody> </table> </div> </div> ); } } export default withFirebase(UserList);<file_sep>/src/components/SignUp/index.js import React, { Component } from "react"; import { Link, withRouter } from "react-router-dom"; import { compose } from "recompose"; import "../SignIn/index.css"; import { withFirebase } from "../Firebase"; import * as ROUTES from "../../constants/routes"; import * as ROLES from "../../constants/roles"; const SignUpPage = () => ( <div className="container"> <div className="row top-to-header"> <div className="col-sm-10 col-md-8 col-lg-6 mx-auto"> <SignUpForm /> </div> </div> </div> ); const INITIAL_STATE = { username: "", email: "", password: "", confirmedPassword: "", // agreed: false, isAdmin: false, error: null }; const ERROR_CODE_ACCOUNT_EXISTS = "auth/email-already-in-use"; const ERROR_MSG_ACCOUNT_EXISTS = ` An account with this email address already exists. Try to login with this account insteat. If you think the account is already used from one of the social logins, try to sign in with one of them. Afterward, associate your accounts on your personal account page. `; class SignUpFormBase extends Component { constructor(props) { super(props); this.state = { ...INITIAL_STATE }; } onSubmit = event => { const { username, email, password, isAdmin } = this.state; const roles = []; if (isAdmin) { roles.push(ROLES.ADMIN); } this.props.firebase .doCreateUserWithEmailAndPassword(email, password) .then(authUser => { // Create a user in your Firebase Realtime Database return this.props.firebase.user(authUser.user.uid).set({ username, email, roles }); }) .then(() => { return this.props.firebase.doSendEmailVerification(); }) .then(() => { this.setState({ ...INITIAL_STATE }); this.props.history.push(ROUTES.HOME); }) .catch(error => { if (error.code === ERROR_CODE_ACCOUNT_EXISTS) { error.message = ERROR_MSG_ACCOUNT_EXISTS; } this.setState({ error }); }); event.preventDefault(); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; onChangeCheckAdmin = event => { this.setState({ [event.target.name]: event.target.checked }); }; render() { const { username, email, password, confirmedPassword, // agreed, isAdmin, error } = this.state; const isInvalid = // !agreed || password !== <PASSWORD>Password || password === "" || email === "" || username === ""; return ( <div className="card card-signin my-5"> <div className="card-body"> <h5 className="card-title text-center">Create Account</h5> {error && ( <div className="alert alert-danger alert-dismissible fade show" role="alert" > <strong>Error!</strong> {error.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> )} <form className="form-signin" onSubmit={this.onSubmit}> <div className="form-label-group"> <input type="text" id="inputUsername" name="username" value={username} onChange={this.onChange} className="form-control" placeholder="Full Name" required autofocus /> <label for="inputUsername">Full Name</label> </div> <div className="form-label-group"> <input type="email" id="inputEmail" name="email" value={email} onChange={this.onChange} className="form-control" placeholder="Email Address" required autofocus /> <label for="inputEmail">Email Address</label> </div> <div className="form-label-group"> <input type="<PASSWORD>" id="inputPassword" name="password" value={<PASSWORD>} onChange={this.onChange} className="form-control" placeholder="Password" required /> <label for="inputPassword">Password</label> </div> <div className="form-label-group"> <input type="password" id="inputConfirmedPassword" name="confirmedPassword" value={confirmedPassword} onChange={this.onChange} className="form-control" placeholder="Confirm Password" required /> <label for="inputConfirmedPassword">Confirm Password</label> </div> <div className="custom-control custom-checkbox mb-3"> <input type="checkbox" id="checkAdmin" name="isAdmin" checked={isAdmin} onChange={this.onChangeCheckAdmin} className="custom-control-input" /> <label className="custom-control-label" for="checkAdmin"> Admin Role </label> </div> <div className="custom-control custom-checkbox mb-3"> <input type="checkbox" id="checkTerms" className="custom-control-input" /> <label className="custom-control-label" for="checkTerms"> I agree to the{" "} <Link className="card-link" to={ROUTES.SIGN_UP}> Terms of Privacy </Link> </label> </div> <button className="btn btn-lg btn-primary btn-block text-uppercase" disabled={isInvalid} type="submit" > <i className="fas fa-user-plus" /> Sign up </button> </form> </div> </div> ); } } const SignUpForm = compose( withRouter, withFirebase )(SignUpFormBase); const SignUpLink = () => ( <div className="d-flex justify-content-center"> <p className="card-text"> Don't have an account?{" "} <Link className="card-link" to={ROUTES.SIGN_UP}> Sign Up </Link> </p> </div> ); // const SignUpForm = withRouter(withFirebase(SignUpFormBase)); export default SignUpPage; export { SignUpForm, SignUpLink };
1f593744b12902594290e883c18799f772efbadc
[ "JavaScript" ]
17
JavaScript
le-hu-dev/react-demo
aba383080423ce7116d28fada176bda16a98845f
b7ad67e7d1899e7507258721c2e3f123100a94c0
refs/heads/main
<repo_name>Shahriar201/HRMS_beta<file_sep>/app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; class LoginController extends Controller { public function login(Request $request){ $request->validate([ 'email' => 'string|email', 'password'=> '<PASSWORD>' ]); ///log in the if credential is correct $logincredentials = ['email' => $request->input('email'), 'password' => $request->input('password') ]; if(Auth::attempt( $logincredentials)){ $user = Auth::user(); $user->last_login = now(); $user->save(); return response()->json(compact('user')); } else{ return response()->json(['error'=>"Email or Password is not valid"],422); } } }<file_sep>/app/Http/Controllers/EmployeeController.php <?php namespace App\Http\Controllers; use App\Http\Requests\EmployeeRequest; use Illuminate\Http\Request; class EmployeeController extends Controller { public function store(Request $request){ dd($request->all()); } }<file_sep>/resources/js/app.js require('./bootstrap'); import {createApp} from 'vue'; import Master from './layout/Master.vue'; import router from './router/index'; const app = createApp(Master); app.use(router); app.mount('#app'); <file_sep>/resources/js/api/Employee.js import Api from './Api.js'; import Csrf from './Csrf.js'; export default { async addEmployee(form){ await Csrf.getCsrf(); return Api.post('employees/store',form); }, } <file_sep>/app/Http/Controllers/Auth/LogoutController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LogoutController extends Controller { public function logout(){ try{ Auth::guard('web')->logout(); return response()->json(['success'=>"You are logout successfully"],200); } //if some error occured then catch the error and response 500 error catch(Exception $e){ return response()->json(['error'=>"Some Error occured for logout".$e->getMessage()],500); } } }
31f75244e9bcf25a2f0bdf2f391c6962f46ec295
[ "JavaScript", "PHP" ]
5
PHP
Shahriar201/HRMS_beta
daa271dc25f44c98cd23430c1d32ede90ba6ffa4
8889b1d23abf41980ff94214a6c184aa8a83b5b1
refs/heads/main
<repo_name>adamiantorno/CS50W-commerce<file_sep>/auctions/migrations/0002_auto_20201003_1428.py # Generated by Django 3.1.1 on 2020-10-03 18:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0001_initial'), ] operations = [ migrations.AddField( model_name='listing', name='is_active', field=models.BooleanField(default=True), ), migrations.AlterField( model_name='listing', name='category', field=models.CharField(choices=[('HME', 'Home'), ('CLT', 'Clothing & Accessories'), ('ART', 'Art')], max_length=50), ), ] <file_sep>/auctions/migrations/0005_auto_20201012_1826.py # Generated by Django 3.1.1 on 2020-10-12 22:26 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0004_auto_20201012_1751'), ] operations = [ migrations.RemoveField( model_name='comment', name='user', ), migrations.AddField( model_name='comment', name='user', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL), ), ] <file_sep>/README.md # CS50W Commerce This is my submission for Harvard's CS50 Web Dev course. This project focuses on Django and SQL interacting together. I also used this project as an oppurtunity to use Class-Based Django views and not just function based views which are what the course teaches. Youtube Link for 5 min Video Demo: https://youtu.be/eKTw2cAweRg <file_sep>/auctions/migrations/0008_auto_20201017_1616.py # Generated by Django 3.1.1 on 2020-10-17 20:16 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auctions', '0007_auto_20201014_0125'), ] operations = [ migrations.AlterField( model_name='watchlist', name='listing', field=models.ManyToManyField(blank=True, to='auctions.Listing'), ), migrations.AlterField( model_name='watchlist', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep>/auctions/views.py from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.db import IntegrityError from django.db.models import Max from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.generic import View, CreateView, ListView, DetailView, FormView from django.views.generic.edit import FormMixin, SingleObjectMixin from .models import User, Listing, Bid, Comment, Watchlist from .forms import ListingForm, CategoryForm, CommentForm, BidForm # List all Active listings class ListingListView(ListView): form_class = CategoryForm template_name = 'auctions/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CategoryForm() return context # Get specific categories and order by most recently created def get_queryset(self): queryset = Listing.objects.filter(is_active=True).order_by('-date_created') if self.request.GET.get('category'): if self.request.GET.get('category') is not None: queryset = Listing.objects.filter(category=self.request.GET.get('category')).order_by('-date_created') return queryset # List all Listing on logged in users watchlist @method_decorator(login_required, name='dispatch') class WatchlistListView(ListView): template_name = 'auctions/watchlist.html' def get_queryset(self): queryset = Listing.objects.filter(watchlists__user=self.request.user) return queryset # Add or remove listing to watchlist @login_required def watch_update(request, product_id): # Get objects to edit listing = Listing.objects.get(id=product_id) if Watchlist.objects.filter(user=request.user).exists(): watch = Watchlist.objects.get(user=request.user) else: watch = Watchlist.objects.create(user=request.user) #Add or remove from watchlist if listing.watchlists.filter(user=request.user).exists(): watch.listing.remove(listing) else: watch.listing.add(listing) watch.save() return HttpResponseRedirect(reverse('listing', kwargs={'pk': product_id})) # Close bid and determine winner def close_bid(request, product_id): # Get objects and variables listing = Listing.objects.get(id=product_id) highest_bid = Bid.objects.filter(listing_id=product_id).order_by('-bid')[0] # Set listing values listing.winner = highest_bid.user listing.is_active = False listing.save() return HttpResponseRedirect(reverse('listing', kwargs={'pk': product_id})) # Listing Detail Page @method_decorator(login_required, name='post') class ListingDetailView(FormMixin, DetailView): model = Listing template_name = 'auctions/listing.html' form_class = CommentForm second_form_class = BidForm # Return to same page if post is successful def get_success_url(self): return reverse('listing', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # watchlist context if self.request.user.is_authenticated: context['on_watchlist'] = Watchlist.objects.filter(listing__id=self.object.pk, user=self.request.user).exists() # comment context context['commentform'] = CommentForm() context['comments'] = Comment.objects.filter(listing_id=self.object.pk).order_by('-timestamp') # bidding context if not 'bidform' in kwargs: context['bidform'] = BidForm(listing_id=self.object.pk) if Bid.objects.filter(listing_id=self.object.pk).exists(): context['highest_bid'] = Bid.objects.filter(listing_id=self.object.pk).aggregate(var=Max('bid')).get('var', None) context['bidder'] = User.objects.get(bids__bid=context['highest_bid']) context['num_bids'] = Bid.objects.filter(listing_id=self.object.pk).count() return context def post(self, request, *args, **kwargs): self.object = self.get_object() # Comment Form if request.POST.get('comment'): form = CommentForm(request.POST) if form.is_valid(): return self.comment_form_valid(form) else: return self.form_invalid(form) # Bid Form elif request.POST.get('bid'): form = BidForm(data=request.POST, listing_id=self.object.pk) if form.is_valid(): return self.bid_form_valid(form) else: return self.render_to_response(self.get_context_data(bidform=form)) # Set commenter as logged in user def comment_form_valid(self, form): comment = form.save(commit=False) comment.listing = Listing.objects.get(pk=self.object.pk) comment.user = User.objects.get(username=self.request.user) comment.save() return super().form_valid(form) # Set bidder as logged in user def bid_form_valid(self, form): new_bid = form.save(commit=False) new_bid.listing = Listing.objects.get(pk=self.object.pk) new_bid.user = User.objects.get(username=self.request.user) new_bid.save() return super().form_valid(form) # Create a new lisitng if logged in @method_decorator(login_required, name='dispatch') class ListingCreateView(CreateView): form_class = ListingForm template_name = 'auctions/create.html' # need to lock into currently logged in user def form_valid(self, form): listing = form.save(commit=False) listing.creator = User.objects.get(username=self.request.user) listing.save() return HttpResponseRedirect(reverse('index')) # Login Page def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["<PASSWORD>"] user = authenticate(request, username=username, password=<PASSWORD>) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") # Logout def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) # Register new user def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["<PASSWORD>"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/register.html") # # https://github.com/django/django/blob/master/docs/topics/class-based-views/mixins.txt # class ListingDisplay(DetailView): # model = Listing # template_name = 'auctions/listing.html' # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context['commentform'] = CommentForm() # context['comments'] = Comment.objects.filter(listing_id=self.object.pk).order_by('-timestamp') # context['bidform'] = BidForm(listing_id=self.object.pk) # if Bid.objects.filter(listing_id=self.object.pk).exists(): # context['highest_bid'] = Bid.objects.filter(listing_id=self.object.pk).aggregate(var=Max('bid')).get('var', None) # context['bidder'] = User.objects.get(bids__bid=context['highest_bid']) # context['num_bids'] = Bid.objects.filter(listing_id=self.object.pk).count() # context['on_watchlist'] = Watchlist.objects.filter(listing__id=self.object.pk, user=self.request.user) # return context # @method_decorator(login_required, name='dispatch') # class ListingInterest(SingleObjectMixin, FormView): # model = Listing # template_name = 'auctions/listing.html' # form_class = CommentForm # second_form_class = BidForm # def get_success_url(self): # return reverse('listing', kwargs={'pk': self.object.pk}) # def post(self, request, *args, **kwargs): # self.object = self.get_object() # if request.POST.get('comment'): # # form_class = self.get_form_class() # form = CommentForm(request.POST) # if form.is_valid(): # return self.comment_form_valid(form) # else: # return self.form_invalid(form) # elif request.POST.get('bid'): # # form_class = self.second_form_class # form = BidForm(data=request.POST, listing_id=self.object.pk) # if form.is_valid(): # return self.bid_form_valid(form) # else: # print(form.errors) # return HttpResponseRedirect(self.get_success_url()) # def comment_form_valid(self, form): # comment = form.save(commit=False) # comment.listing = Listing.objects.get(pk=self.object.pk) # comment.user = User.objects.get(username=self.request.user) # comment.save() # return super().form_valid(form) # def bid_form_valid(self, form): # new_bid = form.save(commit=False) # new_bid.listing = Listing.objects.get(pk=self.object.pk) # new_bid.user = User.objects.get(username=self.request.user) # new_bid.save() # return super().form_valid(form) # # Connext lisitng Detail and Post Items # class ListingDetailView(View): # def get(self, request, *args, **kwargs): # view = ListingDisplay.as_view() # return view(request, *args, **kwargs) # def post(self, request, *args, **kwargs): # view = ListingInterest.as_view() # return view(request, *args, **kwargs)<file_sep>/auctions/migrations/0004_auto_20201012_1751.py # Generated by Django 3.1.1 on 2020-10-12 21:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0003_auto_20201008_2312'), ] operations = [ migrations.AlterField( model_name='comment', name='comment', field=models.CharField(max_length=500), ), ] <file_sep>/auctions/migrations/0006_auto_20201012_1828.py # Generated by Django 3.1.1 on 2020-10-12 22:28 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0005_auto_20201012_1826'), ] operations = [ migrations.AlterField( model_name='comment', name='user', field=models.ManyToManyField(related_name='comments', to=settings.AUTH_USER_MODEL), ), ] <file_sep>/auctions/forms.py from django import forms from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError from django.db.models import Max from .models import Listing, Comment, Bid, Watchlist class ListingForm(forms.ModelForm): class Meta: model = Listing exclude = [ 'creator', 'date_created', 'is_active', 'winner' ] labels = { 'title': _(''), 'description': _(''), 'image': _(''), 'start_bid': _('Starting Bid ($)') } # Initialize placeholders and classes for fields def __init__(self, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update(placeholder='Title') self.fields['description'].widget.attrs.update(placeholder='Add Description') self.fields['start_bid'].widget.attrs.update(placeholder='0.00') self.fields['image'].widget.attrs.update(placeholder='Enter Image URL') for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class CategoryForm(forms.ModelForm): class Meta: model = Listing fields = [ 'category' ] class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment'] labels = { 'comment': _('') } def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) self.fields['comment'].widget.attrs['class'] = 'form-control' self.fields['comment'].widget.attrs['placeholder'] = 'Add a Comment' class BidForm(forms.ModelForm): class Meta: model = Bid fields = ['bid'] labels = { 'bid': _('') } def __init__(self, *args, **kwargs): self.listing_id = kwargs.pop('listing_id') super(BidForm, self).__init__(*args, **kwargs) self.fields['bid'].widget.attrs['class'] = 'form-control' self.fields['bid'].widget.attrs['placeholder'] = '$0.00 - Place a bid' # Form Validation that bid is greater than starting and highest bid def clean_bid(self): new_bid = self.cleaned_data['bid'] og_bid = Listing.objects.get(pk=self.listing_id).start_bid highest_bid = og_bid if Bid.objects.filter(listing_id=self.listing_id).exists(): highest_bid = Bid.objects.filter(listing_id=self.listing_id).aggregate(var=Max('bid')).get('var', None) if not (new_bid > highest_bid and new_bid > og_bid): self.add_error(None, ValidationError('Error: Your bid must be greater than the current highest bid and starting bid!')) return new_bid <file_sep>/auctions/migrations/0007_auto_20201014_0125.py # Generated by Django 3.1.1 on 2020-10-14 05:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auctions', '0006_auto_20201012_1828'), ] operations = [ migrations.RemoveField( model_name='comment', name='user', ), migrations.AddField( model_name='comment', name='user', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='auctions.user'), preserve_default=False, ), migrations.AlterField( model_name='listing', name='category', field=models.CharField(choices=[('ART', 'Art'), ('CLT', 'Clothing & Accessories'), ('ELE', 'Electronics'), ('HME', 'Home'), ('KIT', 'Kitchen'), ('ENT', 'Entertainment'), ('TOY', 'Toys & Games'), ('SPT', 'Sports & Outdoors')], max_length=50), ), ] <file_sep>/auctions/migrations/0003_auto_20201008_2312.py # Generated by Django 3.1.1 on 2020-10-09 03:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auctions', '0002_auto_20201003_1428'), ] operations = [ migrations.AddField( model_name='comment', name='timestamp', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AlterField( model_name='comment', name='listing', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='auctions.listing'), ), migrations.AlterField( model_name='listing', name='category', field=models.CharField(choices=[('ART', 'Art'), ('CLT', 'Clothing & Accessories'), ('ELE', 'Electronics'), ('HME', 'Home')], max_length=50), ), migrations.AlterField( model_name='listing', name='creator', field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='listings', to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='listing', name='image', field=models.URLField(blank=True, max_length=264, null=True), ), ] <file_sep>/auctions/migrations/0009_auto_20201023_2225.py # Generated by Django 3.1.1 on 2020-10-24 02:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auctions', '0008_auto_20201017_1616'), ] operations = [ migrations.AlterField( model_name='bid', name='listing', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bids', to='auctions.listing'), ), migrations.AlterField( model_name='watchlist', name='listing', field=models.ManyToManyField(blank=True, related_name='watchlists', to='auctions.Listing'), ), ] <file_sep>/auctions/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User, Listing, Bid, Comment, Watchlist # Register your models here. class WatchlistAdmin(admin.ModelAdmin): filter_horizontal = ('listing',) admin.site.register(User, UserAdmin) admin.site.register(Listing) admin.site.register(Bid) admin.site.register(Comment) admin.site.register(Watchlist, WatchlistAdmin)<file_sep>/auctions/models.py from django.contrib.auth.models import AbstractUser from django.urls import reverse from django.db import models from datetime import date class User(AbstractUser): pass class Listing(models.Model): CATEGORIES = ( ('ART', 'Art'), ('CLT', 'Clothing & Accessories'), ('ELE', 'Electronics'), ('HME', 'Home'), ('KIT', 'Kitchen'), ('ENT', 'Entertainment'), ('TOY', 'Toys & Games'), ('SPT', 'Sports & Outdoors') ) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='listings', editable=False) title = models.CharField(max_length=100) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) image = models.URLField(max_length=264, blank=True, null=True) start_bid = models.DecimalField(max_digits=10, decimal_places=2) category = models.CharField(max_length=50, choices=CATEGORIES) is_active = models.BooleanField(default=True) winner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f"${self.start_bid} {self.title} - {self.creator}" def get_absolute_url(self): return reverse('listing', kwargs={'pk': self.pk}) class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bids') listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='bids') bid = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return f"${self.bid} for {self.listing} from {self.user}" class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=500) timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return f"{self.comment} - {self.user}" class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) listing = models.ManyToManyField(Listing, blank=True, related_name='watchlists') def __str__(self): return f"{self.user}'s Watchlist" <file_sep>/auctions/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.ListingListView.as_view(), name="index"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("register/", views.register, name="register"), path("create/", views.ListingCreateView.as_view() , name="create"), path("listing/<int:pk>", views.ListingDetailView.as_view(), name="listing"), path("watchlist", views.WatchlistListView.as_view(), name="watchlist"), path("update/<int:product_id>", views.watch_update, name="watch_update"), path("close/<int:product_id>", views.close_bid, name="close_bid") ]
afbb447255d9a1d55f8b91e0234969f0f1f02441
[ "Markdown", "Python" ]
14
Python
adamiantorno/CS50W-commerce
017d690b8b344158f0bdcff165f60702f173618b
6e731312b4ba63a32502cafb53d757ea7794deb7
refs/heads/master
<file_sep># Desenvolvimento Web Armazenamento de Projetos WEB <file_sep>var boximg1 = document.getElementById('box-imagem1'); var boximg2 = document.getElementById('box-imagem2'); var boximg3 = document.getElementById('box-imagem3'); var boximg4 = document.getElementById('box-imagem4'); var boximg5 = document.getElementById('box-imagem5'); var boximg6 = document.getElementById('box-imagem6'); var tituloimg1 = document.getElementById('titulo-img1'); var tituloimg2 = document.getElementById('titulo-img2'); var tituloimg3 = document.getElementById('titulo-img3'); var tituloimg4 = document.getElementById('titulo-img4'); var tituloimg5 = document.getElementById('titulo-img5'); var tituloimg6 = document.getElementById('titulo-img6'); var paragrafoimg1 = document.getElementById('paragrafo-img1'); var paragrafoimg2 = document.getElementById('paragrafo-img2'); var paragrafoimg3 = document.getElementById('paragrafo-img3'); var paragrafoimg4 = document.getElementById('paragrafo-img4'); var paragrafoimg5 = document.getElementById('paragrafo-img5'); var paragrafoimg6 = document.getElementById('paragrafo-img6'); var botaoimg1 = document.getElementById('botao-imag1'); var botaoimg2 = document.getElementById('botao-imag2'); var botaoimg3 = document.getElementById('botao-imag3'); var botaoimg4 = document.getElementById('botao-imag4'); var botaoimg5 = document.getElementById('botao-imag5'); var botaoimg6 = document.getElementById('botao-imag6'); boximg1.addEventListener('mousemove', entrar1); boximg2.addEventListener('mousemove', entrar2); boximg3.addEventListener('mousemove', entrar3); boximg4.addEventListener('mousemove', entrar4); boximg5.addEventListener('mousemove', entrar5); boximg6.addEventListener('mousemove', entrar6); boximg1.addEventListener('mouseout', sair1); boximg2.addEventListener('mouseout', sair2); boximg3.addEventListener('mouseout', sair3); boximg4.addEventListener('mouseout', sair4); boximg5.addEventListener('mouseout', sair5); boximg6.addEventListener('mouseout', sair6); /* Função Entrada */ function entrar1(){ boximg1.style.transitionDuration = '1s'; boximg1.style.backgroundImage = "url('imagens/conteines/natureza.jpg')"; tituloimg1.innerText = 'Natureza Divina'; paragrafoimg1.innerHTML = 'Natureza com seus doms de frutas'; botaoimg1.style.display = 'block'; } function entrar2(){ boximg2.style.transitionDuration = '1s'; boximg2.style.backgroundImage = "url('imagens/conteines/roupas.jpg')"; tituloimg2.innerText = 'Estilo De Vida'; paragrafoimg2.innerHTML = 'Seja Vocês mesmo e curta a vida'; botaoimg2.style.display = 'block'; } function entrar3(){ boximg3.style.transitionDuration = '1s'; boximg3.style.backgroundImage = "url('imagens/conteines/viajem.jpg')"; tituloimg3.innerText = 'Conheça o Mundo'; paragrafoimg3.innerHTML = 'Existe um mundo fora de casa'; botaoimg3.style.display = 'block'; } function entrar4(){ boximg4.style.transitionDuration = '1s'; boximg4.style.backgroundImage = "url('imagens/conteines/amizade2.jpg')"; tituloimg4.innerText = 'Faça Amizade'; paragrafoimg4.innerHTML = 'A existencia se vai muito rapido, faça amigos'; botaoimg4.style.display = 'block'; } function entrar5(){ boximg5.style.transitionDuration = '1s'; boximg5.style.backgroundImage = "url('imagens/conteines/trabalho2.jpg')"; tituloimg5.innerText = 'Tranforme seu hobby em Trabalho'; paragrafoimg5.innerHTML = 'trabalhe com aquilo que você ama'; botaoimg5.style.display = 'block'; } function entrar6(){ boximg6.style.transitionDuration = '1s'; boximg6.style.backgroundImage = "url('imagens/conteines/praia2.jpg')"; tituloimg6.innerText = 'Curta a Vista do Mar'; paragrafoimg6.innerHTML = 'pegue sol, sua vida sera melhor'; botaoimg6.style.display = 'block'; } /* Função Saida */ function sair1(){ boximg1.style.backgroundImage = "url('imagens/conteines/florest.jpg')"; tituloimg1.innerText = ''; paragrafoimg1.innerHTML = ''; botaoimg1.style.display = 'none'; } function sair2(){ boximg2.style.backgroundImage = "url('imagens/conteines/pessoa.jpg')"; tituloimg2.innerText = ''; paragrafoimg2.innerHTML = ''; botaoimg2.style.display = 'none'; } function sair3(){ boximg3.style.backgroundImage = "url('imagens/conteines/fotos.jpg')"; tituloimg3.innerText = ''; paragrafoimg3.innerHTML = ''; botaoimg3.style.display = 'none'; } function sair4(){ boximg4.style.backgroundImage = "url('imagens/conteines/amizade.jpg')"; tituloimg4.innerText = ''; paragrafoimg4.innerHTML = ''; botaoimg4.style.display = 'none'; } function sair5(){ boximg5.style.backgroundImage = "url('imagens/conteines/trabalho.jpg')"; tituloimg5.innerText = ''; paragrafoimg5.innerHTML = ''; botaoimg5.style.display = 'none'; } function sair6(){ boximg6.style.backgroundImage = "url('imagens/conteines/praia.jpg')"; tituloimg6.innerText = ''; paragrafoimg6.innerHTML = ''; botaoimg6.style.display = 'none'; } function proximapagina(){ window.location.href = 'paginas/natureza.html'; /* C/Historico */ /* window.location.replace('paginas/natureza.html'); S/Historico */ /* window.open('paginas/natureza.html', 'pagina'); Abre uma nova pagina e mantem a antiga */ } <file_sep>var boximg = document.getElementsByClassName('conteiner'); var tituloimg = document.getElementsByClassName('conteiner-titulo'); var paragrafoimg = document.getElementsByClassName('conteiner-paragrafo'); var botaoimg = document.getElementsByClassName('botao-class'); boximg[0].addEventListener('mousemove', entrar1); boximg[1].addEventListener('mousemove', entrar2); boximg[2].addEventListener('mousemove', entrar3); boximg[3].addEventListener('mousemove', entrar4); boximg[4].addEventListener('mousemove', entrar5); boximg[5].addEventListener('mousemove', entrar6); boximg[0].addEventListener('mouseout', sair1); boximg[1].addEventListener('mouseout', sair2); boximg[2].addEventListener('mouseout', sair3); boximg[3].addEventListener('mouseout', sair4); boximg[4].addEventListener('mouseout', sair5); boximg[5].addEventListener('mouseout', sair6); function entrar1(){ boximg[0].style.transitionDuration = '1s'; boximg[0].style.backgroundImage = "url('imagens/conteines/natureza.jpg')"; tituloimg[0].innerText = 'Natureza Divina'; paragrafoimg[0].innerHTML = 'Natureza com seus doms de frutas'; botaoimg[0].style.display = 'block'; } function entrar2(){ boximg[1].style.transitionDuration = '1s'; boximg[1].style.backgroundImage = "url('imagens/conteines/roupas.jpg')"; tituloimg[1].innerText = 'Estilo De Vida'; paragrafoimg[1].innerHTML = 'Seja Vocês mesmo e curta a vida'; botaoimg[1].style.display = 'block'; } function entrar3(){ boximg[2].style.transitionDuration = '1s'; boximg[2].style.backgroundImage = "url('imagens/conteines/viajem.jpg')"; tituloimg[2].innerText = 'Conheça o Mundo'; paragrafoimg[2].innerHTML = 'Existe um mundo fora de casa'; botaoimg[2].style.display = 'block'; } function entrar4(){ boximg[3].style.transitionDuration = '1s'; boximg[3].style.backgroundImage = "url('imagens/conteines/amizade2.jpg')"; tituloimg[3].innerText = 'Faça Amizade'; paragrafoimg[3].innerHTML = 'A existencia se vai muito rapido, faça amigos'; botaoimg[3].style.display = 'block'; } function entrar5(){ boximg[4].style.transitionDuration = '1s'; boximg[4].style.backgroundImage = "url('imagens/conteines/trabalho2.jpg')"; tituloimg[4].innerText = 'Tranforme seu hobby em Trabalho'; paragrafoimg[4].innerHTML = 'trabalhe com aquilo que você ama'; botaoimg[4].style.display = 'block'; } function entrar6(){ boximg[5].style.transitionDuration = '1s'; boximg[5].style.backgroundImage = "url('imagens/conteines/praia2.jpg')"; tituloimg[5].innerText = 'Curta a Vista do Mar'; paragrafoimg[5].innerHTML = 'pegue sol, sua vida sera melhor'; botaoimg[5].style.display = 'block'; } function sair1(){ boximg[0].style.backgroundImage = "url('imagens/conteines/florest.jpg')"; tituloimg[0].innerText = ''; paragrafoimg[0].innerHTML = ''; botaoimg[0].style.display = 'none'; } function sair2(){ boximg[1].style.backgroundImage = "url('imagens/conteines/pessoa.jpg')"; tituloimg[1].innerText = ''; paragrafoimg[1].innerHTML = ''; botaoimg[1].style.display = 'none'; } function sair3(){ boximg[2].style.backgroundImage = "url('imagens/conteines/fotos.jpg')"; tituloimg[2].innerText = ''; paragrafoimg[2].innerHTML = ''; botaoimg[2].style.display = 'none'; } function sair4(){ boximg[3].style.backgroundImage = "url('imagens/conteines/amizade.jpg')"; tituloimg[3].innerText = ''; paragrafoimg[3].innerHTML = ''; botaoimg[3].style.display = 'none'; } function sair5(){ boximg[4].style.backgroundImage = "url('imagens/conteines/trabalho.jpg')"; tituloimg[4].innerText = ''; paragrafoimg[4].innerHTML = ''; botaoimg[4].style.display = 'none'; } function sair6(){ boximg[5].style.backgroundImage = "url('imagens/conteines/praia.jpg')"; tituloimg[5].innerText = ''; paragrafoimg[5].innerHTML = ''; botaoimg[5].style.display = 'none'; } function proximapagina(){ window.location.href = 'paginas/natureza.html'; /* C/Historico */ /* window.location.replace('paginas/natureza.html'); S/Historico */ /* window.open('paginas/natureza.html', 'pagina'); Abre uma nova pagina e mantem a antiga */ }
5a95ede4651c9b7f41624ed8f6e2599bad27622d
[ "Markdown", "JavaScript" ]
3
Markdown
MatheusBruno/Projetos
c0a6983489aa92e198802a9ad5c71bdaa7d23d84
5aee933d82d68db6a34a390d82ed07abebe5d890
refs/heads/main
<file_sep>from spaceship import* from asteroid import* from blast import* from blasteroid import* <file_sep>1. import pygame 2. import math 3. from start import* 4. main()
1cda9671e72debf6f8bc6d4215e0fed0fb347a49
[ "Python", "Text" ]
2
Python
sharmion/inhastorage
322bbc26d65f67d8c09c8caaac334dc666f43ad2
3a3fcc90dcfed16a0e95a0a74c928be9b05a23cf
refs/heads/master
<repo_name>iantramble/aer-201<file_sep>/CoordinateSystem.ino //Motors const int leftMotorForwards = 5; const int leftMotorBackwards = 3; const int rightMotorForwards = 9; const int rightMotorBackwards = 6; //Photoresistors const int leftPhoto = A2; const int centrePhoto = A1; const int rightPhoto = A0; //important constants const int buffer = 60; const int timebuffer = 1000; const int desiredy = 4; int leftnat, centnat, rightnat; int linecount = 0; unsigned long lastline = 0; boolean first = false; void setup(){ pinMode(leftMotorForwards, OUTPUT); pinMode(leftMotorBackwards, OUTPUT); pinMode(rightMotorForwards, OUTPUT); pinMode(rightMotorBackwards, OUTPUT); pinMode(leftPhoto, INPUT); pinMode(centrePhoto, INPUT); pinMode(rightPhoto, INPUT); Serial.begin(9600); } void loop(){ analogWrite(rightMotorForwards, 230); analogWrite(leftMotorForwards, 230); if(!first){ leftnat = calibrate(leftPhoto); centnat = calibrate(centrePhoto); rightnat = calibrate(rightPhoto); first = true; } if(linecount == desiredy) { digitalWrite(leftMotorForwards, LOW); digitalWrite(rightMotorForwards, LOW); delay(1000); analogWrite(leftMotorBackwards,140); analogWrite(rightMotorBackwards,140); while (!((averageRead(rightPhoto) < (rightnat - buffer)) && averageRead(centrePhoto) < (centnat - buffer)) || (averageRead(centrePhoto) < (centnat - buffer) && averageRead(leftPhoto) < (leftnat - buffer))){ } digitalWrite(leftMotorBackwards, LOW); digitalWrite(rightMotorBackwards, LOW); delay(1000); turn(true); exit(0); } if(averageRead(leftPhoto) < (leftnat - buffer) && averageRead(rightPhoto) < (rightnat - buffer) && averageRead(centrePhoto) < (centnat - buffer)) { /* for(int i = 0; i < 5; i++) { if(!(averageRead(leftPhoto) < (leftnat - buffer) && averageRead(rightPhoto) < (rightnat - buffer) && averageRead(centrePhoto) < (centnat - buffer))) { goto justadrill; } }*/ if(millis() - lastline > timebuffer){ while(averageRead(leftPhoto) < (leftnat - buffer) && averageRead(rightPhoto) < (rightnat - buffer)){} linecount++; Serial.print("Were crossing line number: "); Serial.println(linecount); lastline = millis(); } } else if(averageRead(leftPhoto) < (leftnat - buffer) && averageRead(centrePhoto) > (centnat - buffer))//left but not centre { Serial.println("Time to turn left"); adjust(true); } else if(averageRead(rightPhoto) < (rightnat - buffer) && averageRead(centrePhoto) > (centnat - buffer))//right but not centre { Serial.println("Time to turn right"); adjust(false); } /* else//everythings normal { analogWrite(rightMotorForwards, 230); analogWrite(leftMotorForwards, 230); } */ /* Serial.print("Right: "); Serial.print(averageRead(rightPhoto)); Serial.print(" centre: "); Serial.print(averageRead(centrePhoto)); Serial.print(" Left: "); Serial.println(averageRead(leftPhoto)); delay(500); */ } void adjust(boolean left){ unsigned long timer = millis(); if (left){ //curve left analogWrite(rightMotorForwards, 230); analogWrite(leftMotorForwards, 170); //in case we cross line while curving left encounteredlineright: //wait till centre sees black again or right sees black while(averageRead(centrePhoto) > (centnat - buffer) && averageRead(rightPhoto) > (rightnat - buffer)) { } //if centre became black (i.e. crossed line before halfway of curve or just normal case) if(averageRead(centrePhoto) < (centnat - buffer)) { //start a timer // for(int i = 0; i < 10; i++) //{ // if we're crossing a grid line if (averageRead(leftPhoto) < (leftnat - buffer)) { //double check you're not seeing the same line twice if(millis() - lastline > timebuffer) { //increment line count linecount++; if(linecount == desiredy){return;} Serial.print("(in first half adjust)Were crossing line number: "); Serial.println(linecount); lastline = millis(); while(averageRead(centrePhoto) < (centnat - buffer) && averageRead(leftPhoto) < (leftnat - buffer)){} //continue curving goto encounteredlineright; } } //} } //we cross line with right going black first else if(averageRead(rightPhoto) < (rightnat - buffer) && millis() - lastline > timebuffer && averageRead(centrePhoto) > (centnat - buffer)) { linecount++; if(linecount == desiredy){return;} Serial.print("(in second half adjust)Were crossing line number: "); Serial.println(linecount); lastline = millis(); timer = timer - 10; delay(100); } //for adjustment factor timer = millis() - timer; analogWrite(rightMotorForwards, 170); analogWrite(leftMotorForwards, 230); for(unsigned long i = 0; i < timer/2; i++) { if (averageRead(leftPhoto) < (leftnat - buffer) && millis() - lastline > timebuffer) { linecount++; lastline = millis(); } delay(1); } digitalWrite(leftMotorForwards, LOW); digitalWrite(rightMotorForwards, LOW); } else{ analogWrite(leftMotorForwards, 230); analogWrite(rightMotorForwards, 170); encounteredlineleft: while(averageRead(centrePhoto) > (centnat - buffer) && averageRead(leftPhoto) > (leftnat - buffer)) { } if(averageRead(centrePhoto) < (centnat - buffer)) { //start a timer // for(int i = 0; i < 10; i++) //{ // if we're crossing a grid line if (averageRead(rightPhoto) < (rightnat - buffer)) { if(millis() - lastline > 500) { //increment line count linecount++; if(linecount == desiredy){return;} Serial.print("(in first half adjust)Were crossing line number: "); Serial.println(linecount); lastline = millis(); while(averageRead(centrePhoto) < (centnat - buffer) && averageRead(rightPhoto) < (rightnat - buffer)){} //continue curving goto encounteredlineleft; } } //} } else if(averageRead(leftPhoto) < (leftnat - buffer) && millis() - lastline > timebuffer) { linecount++; if(linecount == desiredy){return;} Serial.print("(in second half adjust)Were crossing line number: "); Serial.println(linecount); lastline = millis(); timer -= 10; delay(100); } timer = millis() - timer; analogWrite(leftMotorForwards, 170); analogWrite(rightMotorForwards, 230); for(unsigned long i = 0; i < timer/2; i++) { if (averageRead(rightPhoto) < (rightnat - buffer) && millis() - lastline > timebuffer) { linecount++; lastline = millis(); } delay(1); } digitalWrite(rightMotorForwards, LOW); digitalWrite(leftMotorForwards, LOW); } } int averageRead(int pin){ int sum = 0; for (int i = 0; i < 3; i++){ sum += analogRead(pin); } return (int)(sum / 3); } int calibrate(int photo){ int count = 0; for(int i = 0; i < 5; i++) { count += analogRead(photo); } return (int)(count / 5); } void turn(boolean left){ //check if right/left went from white to black boolean rightCheck = false; boolean leftCheck = false; analogWrite(rightMotorForwards, 100); analogWrite(leftMotorBackwards, 100); delay(700); // if (averageRead(rightPhoto) < (rightnat - buffer)) // rightCheck = true; // // if (averageRead(leftPhoto) < (leftnat - buffer)) // leftCheck = true; digitalWrite(leftMotorBackwards, LOW); digitalWrite(rightMotorForwards, LOW); } <file_sep>/connectFour.c /* Artificial intelligence for a modified game of connect four. Game doesn't end after a player scores a connect four, it ends after a certain amount of time. Connect four is a 6 point swing (4 points for player who gets the connect four, -2 points for the opponenet). Impliments a minimax strategy (assuming turn-based). Computer represented by a 1, player represented by a 2. */ #include <stdio.h> struct arrayByVal { int game[6][7]; }; //**structs can be passed by value (i.e. by making a copy), but arrays cannot** //Used to display gameboard in main function int display(int gameBoard[6][7]){ for (int i = 5; i >= 0; i--){ for (int j = 0; j < 7; j++){ if (gameBoard[i][j] == 0) printf("| "); else printf("|%d",gameBoard[i][j]); } printf("|\n"); } return 0; } int power(int base,int exp){ int product = 1; for (int i = 0; i < exp;i++) product *= base; return product; } //Used to determine which row a piece placed into a column will fall into int placeMove(int gameState[6][7],int col){ int i; for (i = 0; gameState[i][col] != 0 && i < 6; i++){} return i; } //Used to check for vertical,horizontal,and diagonal connect fours and return the resulting score int bScore(int gameState[6][7]){ long branchScore = 0; //CHECK FOR HORIZONTAL CONNECT FOUR int horzCount; int team; for (int i = 0; i < 6; i++){ //row i team = gameState[i][0]; horzCount = 0; for (int j = 0; j < 7; j++){ //col j if (gameState[i][j] != 0){ if (gameState[i][j] == team){ horzCount++; } else if (horzCount == 0){ horzCount++; team = gameState[i][j]; } else { team = gameState[i][j]; horzCount = 1; } } else horzCount = 0; //Horizontal heuristics /*if (horzCount == 3){ if (j < 6){ //check if open on right if (gameState[i][j+1] == 0){ if (team == 1) branchScore += 100; else if (team == 2) branchScore -= 100; } } if (j > 2){ //check if open on left if (gameState[i][j-3] == 0){ if (team == 1) branchScore += 100; else if (team == 2) branchScore -= 100; } } }*/ if (horzCount == 4){ if (team == 1){ branchScore += 1000; } else if (team == 2){ branchScore -= 1000; } } } } //CHECK FOR VERTICAL CONNECT FOUR int verCount; for (int i = 0; i < 7; i++){ //col i team = gameState[0][i]; verCount = 0; for (int j = 0; j < placeMove(gameState,i); j++){ //row j if (gameState[j][i] != 0){ if (gameState[j][i] == team){ verCount++; } else if (verCount == 0){ verCount++; team = gameState[j][i]; } else { team = gameState[j][i]; verCount = 1; } } else verCount = 0; //Vertical heuristics /*if (verCount == 3){ if (j < 5){ if (gameState[j+1][i] == 0){ if (team == 1) branchScore += 100; else if (team == 2) branchScore -= 100; } } }*/ if (verCount == 4){ if (team == 1){ branchScore += 1000; } else if (team == 2){ branchScore -= 1000; } } } } //CHECK FOR DIAGONAL CONNECT FOUR //Need to check for all left diagonals and all right diagonals xxx int rightDiagTeam, leftDiagTeam; int leftCount; int rightCount;; for (int i = 0; i < 6; i++){ //start row i int j = 0; //start col j do { rightDiagTeam = gameState[i][j]; leftDiagTeam = gameState[i][6-j]; leftCount = 0; rightCount = 0; for (int k = 0; (k < 6 - j) || (k < 6 - i); k++){ if (gameState[i+k][j+k] != 0){ if (rightCount == 0){ rightCount++; rightDiagTeam = gameState[i+k][j+k]; } else if (gameState[i+k][j+k] == rightDiagTeam){ rightCount++; } else { rightDiagTeam = gameState[i+k][j+k]; rightCount = 1; } } else rightCount = 0; if (gameState[i+k][6-j-k] != 0){ if (leftCount == 0){ leftCount++; leftDiagTeam = gameState[i+k][6-j-k]; } else if (gameState[i+k][6-j-k] == leftDiagTeam){ leftCount++; } else { leftDiagTeam = gameState[i+k][6-j-k]; leftCount = 1; } } else leftCount = 0; //Diagonal heuristics /*if (rightCount == 3){ if (i + k < 3 && j + k < 4){ if (gameState[i+k+1][j+k+1] == 0){ if (rightDiagTeam == 1) branchScore += 100; else if (rightDiagTeam == 2) branchScore -= 100; } } if (i + k > 2 && j + k > 2){ if (gameState[i+k-3][j+k-3] == 0){ if (rightDiagTeam == 1) branchScore += 100; else if (rightDiagTeam == 2) branchScore -= 100; } } }*/ if (rightCount == 4){ if (rightDiagTeam == 1){ branchScore += 1000; } else if (rightDiagTeam == 2){ branchScore -= 1000; } } /*if (leftCount == 3){ if (i+k < 3 && 6-j-k > 2){ if (gameState[i+k+1][5-j-k] == 0){ if (leftDiagTeam == 1) branchScore += 100; else if (leftDiagTeam == 2) branchScore -= 100; } } if (i+k > 2 && 6-j-k < 4){ if (gameState[i+k-3][3-j-k] == 0){ if (leftDiagTeam == 1) branchScore += 100; else if (leftDiagTeam == 2) branchScore -= 100; } } }*/ if (leftCount == 4){ if (leftDiagTeam == 1){ branchScore += 1000; } else if (leftDiagTeam == 2){ branchScore -= 1000; } } } j++; } while(j < 7 && j*i == 0); } return branchScore; } //Returns score obtained by making the initial move int score(struct arrayByVal gameState, int col, int row, int player,int depth, long prevTotal){ (gameState.game)[row][col] = player; long branchScore = bScore(gameState.game); //BASE CASE if (depth == 5) return ((branchScore - prevTotal)/power(7,depth)); //SWITCH PLAYER - assuming turn based if (player == 2) player = 1; else player = 2; //SUM USING RECURSION long columnScore = ((branchScore - prevTotal)/power(7,depth)); int recurseRow; for (int i = 0; i < 7; i++) { recurseRow = placeMove(gameState.game,i); if (recurseRow < 6) { columnScore += score(gameState,i,recurseRow,player,depth+1,branchScore); } } return columnScore; } //Uses score to actually select which column is best int pickCol(struct arrayByVal gameState){ int colScore; int col = 0; int row = placeMove(gameState.game,col); int bestScore; //Find the first col that is not full while (row == 6){ row = placeMove(gameState.game,++col); } bestScore = score(gameState,col,row,1,0,bScore(gameState.game)); for (int i = col + 1; i < 7; i++){ row = placeMove(gameState.game,i); //printf("Col: %d, Row: %d\n",i,row); if (row < 6) { colScore = score(gameState,i,row,1,0,bScore(gameState.game)); if (colScore >= bestScore){ bestScore = colScore; col = i; } } } return col; } int main(){ struct arrayByVal gameBoard = { 0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,0 }; //initialize array to empty int row,col,move; while (1){ //gameBoard.game[0][3] = 1; display(gameBoard.game); printf("Enter column: "); scanf("%d", &col); printf("\n"); row = placeMove(gameBoard.game,col); (gameBoard.game)[row][col] = 2; move = pickCol(gameBoard); row = placeMove(gameBoard.game,move); (gameBoard.game)[row][move] = 1; } return 0; }
c5c92454e6ecaaf5005119af43d4e37b1a885415
[ "C", "C++" ]
2
C++
iantramble/aer-201
7d383967edd3c2c0b570bb5115d2072c03731e58
8c1a98a2cc274358637435cf7c2087934dea6901
refs/heads/master
<repo_name>wenzhix/testgit<file_sep>/LoginAction.java package com.action; import com.opensymphony.xwork2.ActionSupport; /** * 测试登陆 * @author xiaowen * @2016-5-9 下午5:20:23 */ public class LoginAction extends ActionSupport{ private static final long serialVersionUID = 1L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String execute(){ System.out.println("登陆"); if("admim".equals(getUsername())&&"<PASSWORD>".equals(getPassword())){ return SUCCESS; }else{ System.out.println("密码或用户名错误"); //return ERROR; } return LOGIN; } } <file_sep>/readme.txt java教程网欢迎你的加入,更多学习资源尽在java教程网。网站:http://java.662p.com/forum.php<file_sep>/code/Demo02.java package com.test; //三元操作符的类型务必一致 public class Demo02 { public static void main(String[] args) { int i=80; String a=String.valueOf(i<100?90:100); String b=String.valueOf(i<100?90:100.0); System.out.println("两者是否相等:"+a.equals(b)); } }<file_sep>/code/Demo03.java package com.test; //别让null值和空值威胁到变长方法 public class Demo03 { public void methodA(String str,Integer...is){ } public void methodA(String str,String...strs){ } public static void main(String[] args) { Demo03 d=new Demo03(); d.methodA("China", 0); d.methodA("China", "people"); String str=null; //d.methodA("China"); d.methodA("China", str); } }<file_sep>/Demo.java package com.test; public class Demo { public static void main(String[] args) { //不要在常量和变量中出现易混淆的字母 long i=1l;//注意后面那个是L来的 System.out.println("i的两倍是:"+(i+i));//结果是2而不是22 } }
a7d6349385cb950cfa1be8fcf8ba4bfa43a5f80b
[ "Java", "Text" ]
5
Java
wenzhix/testgit
3becab9e76afaa2f59af1acaccd037bc3fc7e706
bf9f2a2029536e88d7766bd9d463c554f17d6a40
refs/heads/master
<file_sep>import React from 'react' const AddExpensePage = () => ( <div> <p>AddExpensePage</p> </div> ) export default AddExpensePage
a5f3ff81d6a96f4879dc4de6ee5c341962d5e86f
[ "JavaScript" ]
1
JavaScript
julia-/expensify-app
85bbacc552e398d0f668381d0eed3195463cfa60
308034e3d7d7397512cfb691fa1a0f761e6d1a3e
refs/heads/master
<repo_name>booka/bok<file_sep>/app/controllers/bok_children_controller.rb class BokChildrenController < ApplicationController inherit_resources defaults :resource_class => Bok, :collection_name => 'boks', :instance_name => 'bok' belongs_to :bok respond_to :html, :xml, :json, :js def index @bok = Bok.find(params[:bok_id]) @boks = @bok.children.search(params[:search]).all index! do |format| format.json { render_json(@bok, @boks) } end end end <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController inherit_resources respond_to :html, :xml, :json, :js end <file_sep>/test/unit/helpers/bok_children_helper_test.rb require 'test_helper' class BokChildrenHelperTest < ActionView::TestCase end <file_sep>/config/routes.rb ActionController::Routing::Routes.draw do |map| map.resource :user_sessions map.resources :boks do |boks| boks.resources :bok_children, :as => :children end map.resources :users end <file_sep>/app/models/bok_response.rb # To change this template, choose Tools | Templates # and open the template in the editor. class BokResponse EMPTY = [] attr_accessor :bok, :children, :updated def initialize(bok = nil, children = nil) @bok = bok @children = children end def to_json() @bok = {:bok => nil} if @bok.nil? @children = EMPTY if @children.nil? @updated = EMPTY if @updated.nil? [@bok, {:boks => @children}, {:updated => @updated}] end end <file_sep>/db/seeds.rb ActiveRecord::Base.logger = Logger.new(STDOUT) User.destroy_all Bok.destroy_all ['Nico', 'Dani', 'Tere', 'Omi', 'Paula', 'Malex'].each do |name| User.create!(:name => name, :login => <EMAIL>", :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>', :rol => 'admin') end User.create!(:name => 'Test', :login => '<EMAIL>', :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>') site = Bok.new(:title => 'Plataforma booka', :bok_type => 'Site', :user_id => 1, :position => 1) site.save(false) ['Plataforma booka', 'Jardines interfaz', 'Arquitectura y género'].each do |name| project = Bok.create(:title => name, :bok_type => 'Project', :parent => site, :position => 1, :user_id => 1) ['Call', 'Indice', 'Forum'].each do |type| Bok.create(:title => name, :bok_type => type, :parent => project, :project => project, :user_id => 1, :position => 1) end archives = Bok.create(:title => name, :bok_type => 'Archives', :parent => project, :project => project, :user_id => 1, :position => 1) 1.upto(5) do |num| Bok.create(:title => "Documento #{num}", :bok_type => 'Document', :parent => archives, :project => project, :user_id => 1, :position => num) end Bok.create(:title => 'Documento de prueba', :bok_type => 'Document', :parent => archives, :project => project, :user_id => 1, :position => 2) Bok.create(:title => 'Jugando con booka', :bok_type => 'Document', :parent => archives, :project => project, :user_id => 1, :position => 1) end <file_sep>/app/helpers/application_helper.rb # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def title(text) content_for(:title) { text } "<h1>#{text}</h1>" end end <file_sep>/app/controllers/user_sessions_controller.rb class UserSessionsController < ApplicationController inherit_resources respond_to :html, :xml, :json, :js actions :create, :destroy, :show, :new protect_from_forgery :only => [] def new @user_session = UserSession.new new! end def show @user_session = current_user_session @user_session ||= UserSession.new @user_session.token = form_authenticity_token show! do |success| success.json {render :json => @user_session.to_json} end end def create @user_session = UserSession.new(params[:user_session]) @user_session.token = form_authenticity_token create! do |success| success.json {render :json => @user_session.to_json} end end end <file_sep>/app/controllers/boks_controller.rb class BoksController < ApplicationController inherit_resources respond_to :html, :xml, :json, :js def index @boks = Bok.search(params[:search]).all index! do |format| format.json { render :json => BokResponse.new(nil, @boks).to_json} end end def show @bok = Bok.find(params[:id]) @boks = @bok.children show! do |format| format.json { render :json => BokResponse.new(@bok, @boks).to_json} end end def create @bok = Bok.new(params[:bok]) @bok.save! respond_to do |format| response = BokResponse.new(@bok, nil) update_position(@bok, response) format.json { render :json => response.to_json} end end def update request.format = params[:format] unless params[:format].empty? update! do |format| response = BokResponse.new(@bok, nil) update_position(@bok, response) format.json { render :json => response.to_json} end end private def update_position(bok, response) new_position = params[:bok][:position] unless new_position.blank? bok.insert_at(new_position) response.updated = bok.lower_sibilings end end end <file_sep>/app/models/user_session.rb class UserSession < Authlogic::Session::Base attr_accessor :token def name self.user.name if self.user end def email self.user.login if self.user end def user_id self.user.id if self.user end def to_json {:user_name => name, :user_id => user_id, :user_email => email, :token => token} end end<file_sep>/app/models/bok.rb class Bok < ActiveRecord::Base belongs_to :user belongs_to :parent, :class_name => 'Bok' belongs_to :project, :class_name => 'Bok' has_many :children, :foreign_key => 'parent_id', :class_name => 'Bok', :order => 'position' acts_as_list :scope => :parent_id attr_reader :user_name validates_presence_of :bok_type, :user_id, :position, :parent_id #, :project_id def user_name user ? user.name : '' end def lower_sibilings Bok.all(:conditions => ['parent_id = ? AND position > ?', parent_id, position], :order => 'position') end end
b9821a9e5a585517353fc49c5b3bbb28fdbae6d2
[ "Ruby" ]
11
Ruby
booka/bok
d1b451555e880b7f85b41d9616efd2a73c1e598e
7ca1af8e117846ce657045fa5cd4660fe085ff80
refs/heads/master
<repo_name>eduper11/hackabos-modulo2<file_sep>/practica03/ejerciciofuncio1.js //una funcion que retorne true si soy mayor de edad o retorne una alerta de confirmación de si mis padres me dieron persmiso // function checkAge(age) { // if (age >= 18) { // return true; // } else { // return confirm("te dejaron tus padres"); // } // } // checkAge (17) // console.log(object); //SOLUCION CON TERNARIO (dale un repaso porfa) // return age >= 18 ? true : confirm("Acceder con permiso paterno") // return age >= 18 || confirm("Acceder con el permiso paternal") // Crea una funcion que acepte dos parámetros X y N y devuelva X elevado a N. // function elevate(x, n) { // // return x ** n; // let result = x; // for (i = 1; i < n; i++) { // result *= x; // } // return result; // } // console.log(elevate(2, 3)); //Una función que reciba euros y devuelva dolares // function changeEuros(inputE) { // if (isfinite.inputE) { // return inputE * 1.13 // } // console.log(changeEuros(4)); // Una funcion que reciba un nombre de una persona de cualquier forma tipo "rUbEn" y te devuelva con formato lógico "Ruben" // function MaysPrim(name) { // name = name.toLowerCase(); // return name.charAt(0).toUpperCase() + name.slice(1); // } // console.log(MaysPrim("rUbEn")); // Una funcion que recibe un string cualquiera y te dice si es palindromo o no //se lee igual de izd a der que de der a izda function palindromo(name) { name = name.toLowerCase(); // reversename = name.tolowercase().reverse(); for (let i = 0; i < name.length; i++) { if (name.charAt(0) == name.charAt(name.length - 1 - i)) { return alert("Enhorabuena, esto es un palíndromo"); } } } <file_sep>/practica03/ejercicio1.js //Cual es el ultimo valor que alerta este bloque: // let i = 4; // while(i) { // alert(i--) // } // //Solución: 1 // //que valores alerta este bloque // ler i = 0 // while (++i < 3) alert(i) //1,2 // let x = 0 // while x (x++ < 3) alert(x)// 1,2,3 //buscador de numeros primos //teniendo x => n.....n+ //hacer un código que muestre los numeros primos de x let x = prompt("numeros primos?"); pepe: for (i = 2; i <= x; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { continue pepe; } } console.log(i); } <file_sep>/practica01/ejercicio3.js let operacion = ""; let resultado = 0; let num1 = +prompt("indica primer número"); if (isFinite(num1)) { let num2 = +prompt("indica segundo número"); if (isFinite(num2)) { operacion = prompt("Que operación quieres hacer?") .trim() .toLowerCase(); if (operacion == "suma") { resultado = num1 + num2; } else if (operacion == "resta") { resultado = num1 - num2; } else if (operacion == "div") { resultado = num1 / num2; } else if (operacion == "mult") { resultado = num1 * num2; } else { ("Por favor, introduzca una operación válida"); } alert(resultado); } else { alert("Por favor, indica un número válido"); } } else { alert("Por favor, indica un número válido"); } <file_sep>/practica01/ teoria.js // ! NOT let isTall = true; isTall = !isTall; let isRed = 0; isRed = !isRed; alert(!!"hola") //true alert(boolean("hola"0)) //true //bucles let flag = false; while (true) { console.log("hola"); flag = true; if(flag ==true) { brake; } } let cont = 0; while (cont <= 3) { console.log(cont); cont++; } let cont2 = 0 while (true) { console.log(cont2); cont2++; if (cont2 == 3){ break; } } let limit = 0 do { console.log(limit); limit++; }while (limit < 5); let array = [1,2,3,4,5]; for (let i = 0, i < array.length; i++) { const element = array [i]; console.log(element); } // mostrará los elementos dentro de array uno a uno, hasta let array = [ {name: "pepe", isAdmin: true} {name: "paco", isAdmin: false} {name: "julia", isAdmin: true} {name: "sancho", isAdmin: false} {name: "abel", isAdmin: true} ] // [i] es cada uno de los items de array for(let i = 0; i < array.length; i++) { if (array[i].isAdmin) { console.log(array[i].name); } } // hacer con ifs let array = [ {name: "pepe", isAdmin: true} {name: "paco", isAdmin: false} {name: "julia", isAdmin: true} {name: "sancho", isAdmin: false} {name: "abel", isAdmin: true} ] //continue solo se usa con el for SOLO for (let index = 0; index < array.length; index++) { const element = array[index]; } // /cambiar el nombre a los users que no sean admins a "default" usando continue un bucle puede tener un nombre: principal: for (let index = 0; index < array.length; index++) { for (let index = 0; index < array.length; index++) { if (condition) { break pepe ; } } }<file_sep>/practica02/ejer_tutobasico2.js // Coderbyte pruebas de challenges // //escoge la más larga del tring // let anyString = prompt("Dame una cadena de palabras"); // let anyString.split(``); // if (typeof anyString == "string") { // let pepe = anyString.split(` `); // let lenghtword = 0; // let word = null; // for (let i = 0; i < pepe.length; i++) { // // console.log("hola"); // if (pepe[i].length > lenghtword) { // // console.log("pp"); // lenghtword = pepe[i].length; // word = pepe[i]; // } // } // console.log(word); // debugger; // } // console.log(palindromo("asa")); // function palindrome(name) { // name = name.toLowerCase().replace(/\s+/g, ""); // rename = name // .split("") // .reverse() // .toString() // .replace(/,/g, ""); // ojo con el replace, si no se define su ámbito de aplicación "g" (global) en caso de signos solo sustituye el primero que se encuentra // // // // console.log(rename); // // for (let i = 0; i < rename.length - 1; i++) { // if (name === rename) { // alert("esto es un palíndromo"); // } else { // alert("no es un palíndromo"); // } // } // } // palindrome("jaimiti y sus bicis"); // Se van sus naves //como encontrar una letra en un string, y validarla solo si está rodeada del simbolo + // function characterSearch(str) { // str = str.toLowerCase().split(""); // for (let i = 0; i < str.length; i++) { // console.log("hola"); // if (str[i] > "a" && str[i] < "z") { // console.log("hola2"); // if (i === 0 || i === str.length) { // console.log("hola3"); // return false; // } // } else if (str[i - 1] !== "+" && str[i + 1] !== "+") { // console.log("hola4"); // return false; // } else { // console.log("hola5"); // return true; // } // } // } // Coderbyte me ha tangadooooooooo, funciona perfecto!!!! // characterSearch("+d===+a+"); //"+d===+a+ // conversor sexagesimal. // function TimeConvert(num) { // let hour = num / 60; // let minute = (num - hour) / 60; // console.log(minute); // } // TimeConvert(64); // function letVowels(str) { // let m = str.match(/[aeiou]/gi); // return m === null ? 0 : m.length; // } // console.log(letVowels("jaimito y su ladrillo")); <file_sep>/practica02/ejercicio2.js // let age = +prompt("Que edad tienes?"); // switch (age) { // case age < 18: // alert("Eres un niño"); // break; // case age >= 18: // alert("Puedes votar"); // break; // } // El switch necesita poner cada caso por separado, no voy a escribir todas las líneas, ya que es obvio el resultado // let browser = prompt("Dime un browser"); // switch (browser) { // case "Vivaldi": // console.log("El browser mas mejor del mundo"); // break; // case "IE": // console.log("Eeeeeeeewwwwwww"); // case "Chrome": // case "Mozilla": // console.log("Very good"); // break; // default: // console.log("Has introducido un valor erroneo"); // } <file_sep>/ejercicioTemplate/teoria_1.js //switch es bastante básico, usar solo para condiciones muy muy básicas // let key // switch (key) { // case value: // break; // default: // break; // } // Fuciones DRY (dont repeat yourself) // function getPepe(params) { // console.log("Soy Pepe"); // } // function sum(num1, num2) { // return num1 + num2; // } // EN UNA FUNCION SI NO SE RETORNA NADA, RETORNA UN "UNDEFINED" // function isEven(num) { // if (URLSearchParams.isAdmin == false) return "no estas autentificado"; // if (num % 2 == 0) { // return true; // } // return false; // } // Funciones declarativas // function name(params) { // } // funciones expresivas // let sum = function(params) { // } // callbacks // parámetros de una funcion que se llaman si algo ha salido bien o mal // function checkAge(age, accept, decline) { // if (age >= 18) { // accept(); // } else { // decline(); // } // } // function accept() { // console.log("Todo ok"); // } // function decline() { // console.log("Todo mal"); // } // checkAge(18, accept, decline); // //funcion ARROW // quitamos la palabra function, y ponemos despues de los params una flecha (=>) // const nombte = (num1, num2) => { // return num1 + num2; // } // const suma = (num1, num2) => { // let acces = checkPermissions(); // if (!acces) return "no puedes entrar": // num1 + num2; // Son funciones anónimas( no tienen nombre) // POdemos obviar el return si es una sola línea, y si es un arrow function // const cube = num1 => { // debugger; // console.log("loquesea"); // return num1 **3; // }; // cube(3; // Symbol crea valores únicos, es decir // Objects // let Objects = { // } // las propiedades pueden ser string o symbol (recuerda que symbol crea valores únicos, es decir, name = symbol (x) y name2 = symbol (x) name y name2 serán diferentes) // let obj = { // name: "Alex", // oranges: 23, // apples: 234 // }; let loquesea = prompt("dame apples o oranges") obj[loquesea]; para pedir propiedades dinámicas (aquí saldría 234, le está pidiendo la propiedad oranges) funcion generadora de objetos o constructora function Persons(name, lasName) { //se diferencia porque se empieza con mayuscula this.name = name; this.lastName = lastName; } let person1 = new Persons("Murillo", "Ferreira") console.log(person1); // //OJO, los métodos son los que tienen funciones, y live en este caso es la propiedad, (repasar sintaxis objetos JS) let obj = { live: 100, increaseLive: function() { this.live += 50; return this; }, decreaseLive: function { this.live -= 50; return this;//este return nos permite hacer métodos abajo }, showLive: function { console.log(this.live); } } //a esto me refiero con la nota del return personaje.increaseLive().increaseLive().decreaseLive() CLASES // Cambiar sintaxis object constructor a "clases" Acumulador: class Acumulador2 { constructor(defaultvalue){ this.defaultvalue = defaultvalue } introduce() { let x = +prompt ("acumulame"); this.defaultvalue += x; return this; } samecolor (coche1, coche2) { //static sirve para hacer esta función global, y que no pertenezca a cada coche en concreto, en este caso// static samecolor () { //static sirve para hacer esta función global, y que no pertenezca a cada coche en concreto, en este caso// al ser estática, si nosotros lo llamamos desde c1 o c2, nos va a dar error, porque este método no pertenece a ningun coche, si no que es global return coche1.color === coche2.color; } } //errores, fechas, tipos mas a fondo, asincronía try { //código que queremos probar }catch(e) { let car1 = new Car(3200, true); let van1 = new Van("red", 3400, tru //si hay un error, va a entrar automáticamente dentro console.error(e); //imprime por pantalla pero en rojo // console.warn(e); //otro tipo de console } error = { name : "ReferenceError", message: "", stack: "hay un error at." //es de donde viene el error } // logging -> elastisearch (base de datos sobre todo de texto (full search text)) o kibana también es otro tipo class LoginError extends Error { //muy útil para crear varios tipos de errores constructor() { super(); this.name = "LoginError"; } } //shift + f12 Te abre un pequeño editor donde aparece donde aparece más esa clase, etc // ctrl + click sobre una clase para ver sus métodos //haz una función que diga "hola" c/ 3 ses setTimeout(() { //podemos hacer cualquier cosa dentro de setTimeout, como una función } ), timeout) //timeout está en ms(milisegundos) setTimeout(function() { console.log("Hola"); }, 3000); setInterval(() => { console.log("adios"); }, 3000); //funcion para conocer cómo accede el this (2 arriba) en un array let obj = { name: "pepe", hola: function() { setTimeout(() => { console.log("Hello " + this.name); }, 3000); } }; obj.hola(); //TYPOS //numeros Math.ceil() //lo contrario que el floor, devuelve el entero más pequeño mayor o igual a un número dado. Math.floor() //Math.floor((1.74837 * 100) /100) para redondear a 2 decimales //4.1 4 //4.6 4 Math.round() //redonde matemáticamente Math.trunc() toFixed let num = 4.32324 //toFixed redondea a "2" en este caso, y devuelve en string num.toFixed(2) console.log(parseFloat("58458.3352.3565")); Math.max(2,3,4,8) //min hace lo inverso Math.random() //STRINGS let cadena = "ñlaksdjflkjsad"; //for of (let "" of "string", array...etc) //for in (let key in objetc) for (let letra of cadena) { console.log(letra); // coge cada una de las letras del string } cadena. charAt(1) cadena.includes() //retorna un true si se incluye el parámetro en un string cadena.indexOf() //retorna la posicion donde se encuentra el parámetro en la cadena. si no está, devuelve un -1 cadena.normalize() cadena.join() //ARRAYS let name = [a, r, r, a, y] name.length name.push() //mete un elemento en el array, siempre en ultima posición, y return la nueva longitud del elemento, que será un number name.pop() elimina el ultimo valor del Array, y returna el que elimina name.unshift() //mete lo que pongas en el parametro, y te devuelve la nueva longitud name.shift() //borra el primer parámetro de un array y retorna el que borra for(let name of names) { } name.splice( , ) //a partir de su param borra tantos elementos como se indique en el segundo param y devuelve los borrados name.map() //(son métodos funcionales) creas un array(name2) donde map recorre name (es como un for of) y segun esta función, retorna name + 2, siendo name2 = [a+2, r+2, r+2.......] name.filter() //funciona igual que map, pero filter filtra, es decir, map recorre todos, y filter recorre solo los que tu le digas let name2 = name.map((name)=> { return name + "2" }) // ó [1,3,5,8].reduce(() => { }); //DESTRUCTURING let arrayNormal = ["Abel", "Pepe"] let [name1, name2] = arrayNormal //se puede decir que así estamos desestructurando, para estructurarlo en un nuevo elemento console.log(name2); //name2 será "Abel" let arrayNormal = ["ruben", "Costa"] let obj4 = {} [obj4.name, obj4.lastName] = arrayNormal let obj = { window: 100, innerHeight: "2oopx" //...rest => significa "todo el resto", pero no tiene por que llevar rest, se puede llamar de cualquier forma. el quiz son los ..., que asocian el resto de propiedades a los ... }; let { window: w = 0, innerheight } = obj; //con el ejemplo de window estamos llamando a window "w". Si no hubiese nada en window, valdría 0, pero si hay window, prevalece el valor que tiene en el objeto DEBERES //JSON JS Y FECHAS como manejar una fecha? let fecha1 = new Date() ler ahora = Date.now() //json no puede llevar comentarios. porque se busca la mayor eficiencia, por eso tiene una estructura muy marcada, para que el flow sea el más óptimo. librería de fechas: momentjs, dayjs, npmjs(web) para libreríasjs asincronía let promesa = new Promise(function(resolve, reject) { setTimeout(() => { resolve("los datos me han llegado perfecto") }, 1000); } promesa .then(resultado => console.log(resultado)) .catch(err => clg(err)); JSON let obj = { name: "Pepe" age: 48 }; let json = JSON.stringify(obj); //este obj es un string ,y ya no está en JSON let newObj = JSON.parse(json); //pasar json a un object<file_sep>/practica06/ejercicio1.js //Crear un objeto personaje que tenga un cotador de vida y que tenga dos metodos: increaseLife que incrementa la vida en 50 puntos y decreaseLife que la baja en 50 puntos. Tiene que tener otra función que muestre la vida total //que los métodos del objeto de arriba se puedan llamar encadenadamente: //OJO, los métodos son los que tienen funciones, y live en este caso es la propiedad, (repasar sintaxis objetos JS) // let obj = { // live: 100, // increaseLive: function() { // this.live += 50; // return this; // }, // decreaseLive = function() { // this.live -= 50; // return this;//este return nos permite hacer métodos abajo // }, // showLive: function() { // console.log(this.live); // } // } // //a esto me refiero con la nota del return // personaje.increaseLive().increaseLive().decreaseLive() // cree un objeto acumulador usando la funcion constructora acumulador con un valor inicial. Ese objeto debe tener un metodo "introduce" que te salta un prompt y te lo suma en el acumulador // function Acumulador(defaultvalue) { // this.defaultvalue = 4, // this.introduce = function() { // let x = +prompt ("acumulame"); // this.defaultvalue += x; // return this; // }; // } // let acumulador1 = new acumulador(21) // acumulador1.introduce(); // console.log(acumulador1); // investigar como funciona proto // Cambiar sintaxis object constructor a "clases" // class Acumulador2 { // constructor(defaultvalue){ // this.defaultvalue = defaultvalue // } // introduce() { // let x = +prompt ("acumulame"); // this.defaultvalue += x; // return this; // } // } // crear una clase delfin, el delfin que tenga un nombre, un peso, longitud, color y los metodos saltar que console.log(salntando); y un método general de reproducción que al pasarle dos delfines con el mismo color nos da un true (mini dolphin) class Animal { constructor(eyes) { this.eyes = eyes; } jump() { console.log("Animal saltando"); } } class Dolphin extends Animal { constructor(name, peso, longitud, color) { super(2); this.name = name; this.peso = peso; this.longitud = longitud; this.color = color; } jump() { console.log("saltando"); return this; } static reproduction(dolphin1, dolphin2) { dolphin1.color === dolphin2.color ? "Mini dolphin" : false; // if (dolphin1.color === dolphin2.color) { // return console.log("minidolphin"); } } let dolphin1 = new Dolphin("Paco", 50, 2, "azul"); let dolphin2 = new Dolphin("Suso", 20, 3, "azul"); dolphin1.jump(); Dolphin.reproduction(dolphin1, dolphin2); <file_sep>/practica03/ejercicio5.js // recorre array 3x3 que e(pensando en un tablero de hundir la flota) pedimos un valor (1)(ponemos barco) (0)(no metemos nada, agua). Si no ponemos nada en la casilla, el bucle se para. pepe: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { // console.log(`coordenada ${i}${j}`); coordenada = prompt(`Escoge 1 o 0 para la coordenada ${i},${j}`); if (coordenada == "1") { } else if (coordenada == "0") { } else if (coordenada == null) { break pepe; } else { alert("Has introducido un valor erroneo"); break pepe; } console.log(`Has seleccionado ${coordenada} para la casilla ${i}${j}`); } } <file_sep>/practica08_repaso/ejercicio1.js // Reemplazar en este código las expresiones de función con funciones de flecha: // ```js run // function preguntar(pregunta, si, no) { // if (confirm(pregunta)) si(); // else no(); // } // preguntar( // "Estás de acuerdo con las condiciones de uso?", // function() { // alert("Aceptaste las condiciones de uso."); // }, // function() { // alert("No aceptaste las condiciones de uso."); // } // ); // ``` // let preguntar = (pregunta, si, no) => { // confirm(pregunta) ? si : no; // }; // preguntar( // "Estás de acuerdo con las condiciones de uso?", // () => alert("Aceptaste las condiciones"), // () => alert("No aceptaste las condiciones de uso") // ); // Escribir una función `isEmpty(objeto)` que devuelve `true` si el objeto no tiene propiedades y `false` de lo contrario.Escribir // let calendar = {}; // function isEmpty(calendar) { // for (let key in calendar) { // if (calendar.hasOwnProperty(key)) return false; // } // return true; // } // alert(isEmpty(calendar)); // true // calendar["June"] = "Es mi cumple!"; // alert(isEmpty(calendar)); // false // let calendar = {}; // function isEmpty(calendar) { // for (let key in calendar) { // if (calendar.hasOwnProperty(key)) return false; // } // return true; // } // alert(isEmpty(calendar)); // calendar["Mayo"] = "cumpleaños"; // alert(isEmpty(calendar)); // const city = { // name: "Madrid" // }; // // Esto funciona? // city.name = "Coruna"; // console.log(city.name); // check las siguientes expresiones: // let user = { // name: "Pepe", // sayName: function() { // alert(this.name); // } // }; // user.sayName(); // let user = { // name: "John", // sayName: function() { // alert(this.name); // } // }; // user.sayName(); // user.sayName(); // function createPost() { // return { // name: "New Website", // description: this // }; // } // let post = createPost(); // console.log(post.description); // resultado? por que? // function createPost() { // return { // name: "New Website", // description() { // return this; // } // }; // } // let post = createPost(); // console.log(post.description()); // ??? por que?? // function timeConvert(num) { // if (isFinite(num)) { // let hours = Math.floor(num / 60); // let mins = num % 60; // return num1 + ":" + num2; // } // } // console.log(timeConvert(65)); // function getAlph(str) { // return str // .split("") // .sort() // .join(""); // } // console.log(getAlph("hello my friend")); <file_sep>/ejercicioTemplate/app.js /* * 1, 2, 3... GO! */ let isADmin = confirm("Eres el admin?"); let age = +prompt("Cuantos años tienes?", 10); if(typeof age == "number") //typeof para saber si es un numeros nunca if (isFinite(age)) //para saber si es un numeros nunca // un programa que pida tu nombre por promt y lance una alerta si el nombre es "Admin" "hello master" //es "User" "hello user" //es otra cosa "I dont know you" let isAdmin = prompt("Who are you?").toLowerCase.trim; if (isAdmin == "Admin") { prompt("Hello Master"); } else if (isAdmin == "User") { prompt("Hello Master"); } else { prompt("I dont know you") } if (isAdmin === "admin" || isAdmin === "user") { alert("Hello `{user2}`") }<file_sep>/practica9_lastday/ejercicio1.js // let promesa = new Promise(function(resolve, reject) { // setTimeout(() => { // resolve("los datos me han llegado perfecto") // }, 1000); // } // Promise.then(resultado => console.log(resultado)); //Una función que tenga un setTimeout de 2 segundos que devuelva una respuesta al pasarle una url y llamar a un api público (que es url) // let data = toOrderData ("https//randomuser.me/api/") // async function example(params) { // return Promise.resolve("todo ha ido bien"); // } // example().then(data=> console.log(data)); // let data = await example() // escribir una function testNum que le pasas un parámetro y retorna una Promise que comprueba que el valor sea mayor que 10, si no la rechaza //escribir 2 funciones que susen Promises que puedas encadenar. La primera función // se llama transformToCaps(), que tomará un array de palabras y las pasara a mayusculas, // y la segunda orderWords() ordenará las palabras en orden alfabético. // Si el array tiene algun dato que no sea un string, debe lanzar un reject // async function githubExample(url = "https://api.github.com/users/eduper11") { // try { // let res = await fetch(url); // let user = await res.json(); // console.log(user); // } catch (e) { // console.log(e); // } // } // githubExample(); // function ArrayAddition(arr) // async function githubExample (url = "https://api.github.com/users/eduper11") { // try { // let res = await fetch(url); // let user = await res.json(); // console.log(user); // } catch (e) { // console.log(e); // } // } // function testNum (name) { // return promise = new Promise (function (resolve, reject) { // if (name > 10) { // resolve (console.log(param);) // } // }) // } const users = [ { id: 1, name: "ricardo", profesion_id: 1 }, { id: 2, name: "alejandro", profesion_id: 1 }, { id: 3, name: "diego", profesion_id: 2 } ]; const profesion = { 1: "programador", 2: "diseñador" }; function getUser(callback) { setTimeout(() => { callback(null, users); }, 2000); } getUser ((err, users) => console.log(users));<file_sep>/practica07/ejercicio1.js //Crear una clase furgoneta que exteinda de vehiculo //crear una clase coche que extienda de vehiculo // vehiculo tiene propiedades por defecto: puertas 5, peso 3000kg // furgoneta sustituye el peso a 5000 // coche sustituye el peso a 3500kg y añade radio (true/false) // furgoneta además añade extra un color y un tipo que puede ser especial o no (true, false) // class Vehicle { // constructor(doors = 5, weight = 3000) { // this.doors = doors; // this.weight = weight; // } // } // class Car extends Vehicle { // constructor(weight = 3500, radio = true) { // super(); // this.weight = weight; // this.radio = radio; // } // } // class Van extends Vehicle { // // las propiedades que tienen un valor por defecto, ponlo al final siempre // constructor(color, weight = 5000,especial = false) { // super(); // this.weight = 5000; // this.color = color; // this.especial = false; // } // } // let car1 = new Car(3200, true); // let van1 = new Van("red", 3400, true); // setTimeout(function() { // console.log("Hola"); // }, 3000); // setInterval(() => { // console.log("adios"); // }, 3000); // let obj = { // name: "pepe", // hola: function() { // setTimeout(() => { // console.log("Hello " + this.name); // }, 3000); // } // }; // obj.hola(); // let cadena = "ñlaksdjflkjsad"; // for (let i = 0; i < cadena.length; i++) { // console.log(cadena[i]); // } // let names = ["pepe", "rafa", "tito", "maria"]; // names.splice(); // for (let i = 0; i < names.length; i++) { // if (i % 2 == 0) { // names.splice(i,1) // console.log(names[i]); // } // } // function deletePair(names) { // for (let i = 1; i < names.length; i++) { // names.splice(i, 1); // } // } // ó // let names2 = names.filter((name,i) => { // if(i % 2 == 0) { // return names // } // }) // deletePair(names); // console.log(names); // Funcion que al pasarle un array de users que los pase a type = Admin, y luego otra que al pasarle el array, nos los filtre por la localización que le pasemos // let people = [ // { // name: "Pepe", // location: "Coruna", // type: "user" // }, // { // name: "Andrea", // location: "Madrid", // type: "user" // }, // { // name: "Maria", // location: "Coruna", // type: "user" // }, // { // name: "Alex", // location: "Bcn", // type: "user" // } // ]; // function changeAdmin(people) { // return people.map(person => { // person.type = "Admin"; // return person; // }); // } // // console.log(changeAdmin(people)); // // console.log(people); // function changeLocation(people, location) { // return people.filter((person, index, array) => { // if (location == person.location) return true; // false; // }); // } // console.log(changeLocation(people, "Coruna")); // function changeAdminonlyEven(people) { // { // return people.map((person, index) => { // if (index % 2 !== 0) person.type = "Admin"; // return person; // }); // } // } // console.log(changeAdminonlyEven(people)); // let arrayNormal = ["Abel", "Pepe"]; // let [name1, name2] = arrayNormal; // let name1 = arrayNormal[0]; // let name2 = arrayNormal[1]; // console.log(name2); // let arrayNormal = ["ruben", "Costa"] // let obj4 = {} // [obj4.name, obj4.lastName] = arrayNormal //EJERCICIO DE DESTRUCTURING // let obj = { // window: 100, // innerHeight: "2oopx" //...rest => significa "todo el resto" // }; // let { window: w = 0, innerheight } = obj; //con el ejemplo de window estamos llamando a window "w". Si no hubiese nada en window, valdría 0, pero si hay window, prevalece el valor que tiene en el objeto
e70bece58536a46d4f77a99d55345a9976028db8
[ "JavaScript" ]
13
JavaScript
eduper11/hackabos-modulo2
b3040e013371a844d25fa9ece1b9556501434507
fce0728f7ef6baa2e28915615e8a3c060822b28e
refs/heads/master
<file_sep>package spreadoffire; import java.util.Scanner; import javax.swing.JFrame; /** * The main class of project from MVC pattern * * @author OOPgroup8 * @version V2.0 2014.10.14 */ public class SpreadOfFire { static int width, height; /** * @param args the command line arguments */ public static void main(String[] args) { JFrame myGUI=new Controller(); //TUI(); } public static void TUI(){ System.out.println("Set the size of the forest (grid) : "); System.out.print("Width = "); Scanner a = new Scanner(System.in); int width = a.nextInt(); System.out.print("Height = "); Scanner b = new Scanner(System.in); int height = b.nextInt(); System.out.println("Set the probability of a tree in a cell catching fire : (0-100) "); Scanner c = new Scanner(System.in); int probC = c.nextInt(); Model grid = new Model(width,height,probC,0,100,0); System.out.println("Initial grid"); grid.showGraph(); int step=1; while(!grid.finish()){ grid.checkBurn(); System.out.println("Step "+step); grid.showGraph(); step++; grid.resetCheck(); } System.out.println("Total step = "+ (step-1)); } } <file_sep>package spreadoffire; import java.awt.Color; /** * The cell class that contain the properties of cell * * @author OOPgroup8 * @version V2.0 2014.11.16 */ public class Cell { public static final int BLUE=3,GREEN=2,RED=1,YELLOW=0; private int color,lightningStep; /** * Constructor - create the empty cell */ public Cell(){ this.color=Cell.YELLOW; } /** * Constructor - create the cell * @param color */ public Cell(int color){ this.color=color; } /** * Get the color of cell * @return color */ public int get(){ return color; } /** * Set the color of cell * @param color */ public void set(int color){ this.color=color; } /** * Check if the cell is empty or not * @return true if cell empty */ public boolean isEmpty(){ return color==YELLOW; } /** * Set the lightning step * @param s */ public void setLightningStep(int s){ this.lightningStep=s; } /** * Decrease the lightning step */ public void stepLightning(){ this.lightningStep--; } /** * Get the current lightning step * @return lightningStep */ public int getLightningStep(){ return lightningStep; } /** * Get the RGB Color of cell * @return RGB Color */ public Color getColor(){ if(color==BLUE)return Color.BLUE; if(color==GREEN)return Color.GREEN; if(color==RED)return Color.RED; return Color.YELLOW; } }
38e1b19e378a4c0cb2ddbe10616492e5c04abd1d
[ "Java" ]
2
Java
rl404/OOP-Group-8-SpreadOfFire
f279dadf1732cd2672c6c43abf09cc9e7cace938
fa9533f6af9759adaafedb7a06425f7c465d566c